Java Code Examples for org.jetbrains.annotations.NotNull

The following examples show how to use org.jetbrains.annotations.NotNull. These examples are extracted from open source projects.
Example 1
Project: eosio-java   File: EOSFormatter.java    License: MIT License 6 votes vote down vote up
/**
 * Decompresses a public key based on the algorithm used to generate it.
 *
 * @param compressedPublicKey Compressed public key as byte[]
 * @param algorithmEmployed Algorithm used during key creation
 * @return Decompressed public key as byte[]
 * @throws EOSFormatterError when public key decompression fails.
 */
@NotNull
private static byte[] decompressPublickey(byte[] compressedPublicKey,
        AlgorithmEmployed algorithmEmployed)
        throws EOSFormatterError {
    try {
        ECParameterSpec parameterSpec = ECNamedCurveTable
                .getParameterSpec(algorithmEmployed.getString());
        ECPoint ecPoint = parameterSpec.getCurve().decodePoint(compressedPublicKey);
        byte[] x = ecPoint.getXCoord().getEncoded();
        byte[] y = ecPoint.getYCoord().getEncoded();
        if (y.length > STANDARD_KEY_LENGTH) {
            y = Arrays.copyOfRange(y, 1, y.length);
        }
        return Bytes.concat(new byte[]{UNCOMPRESSED_PUBLIC_KEY_BYTE_INDICATOR}, x, y);
    } catch (Exception e) {
        throw new EOSFormatterError(ErrorConstants.PUBLIC_KEY_DECOMPRESSION_ERROR, e);
    }
}
 
Example 2
Project: idea-php-generics-plugin   File: AnnotationLightCodeInsightFixtureTestCase.java    License: MIT License 6 votes vote down vote up
public void assertIndex(@NotNull ID<String, ?> id, boolean notCondition, @NotNull String... keys) {
    for (String key : keys) {

        final Collection<VirtualFile> virtualFiles = new ArrayList<VirtualFile>();

        FileBasedIndex.getInstance().getFilesWithKey(id, new HashSet<>(Collections.singletonList(key)), virtualFile -> {
            virtualFiles.add(virtualFile);
            return true;
        }, GlobalSearchScope.allScope(getProject()));

        if(notCondition && virtualFiles.size() > 0) {
            fail(String.format("Fail that ID '%s' not contains '%s'", id.toString(), key));
        } else if(!notCondition && virtualFiles.size() == 0) {
            fail(String.format("Fail that ID '%s' contains '%s'", id.toString(), key));
        }
    }
}
 
Example 3
Project: sentry-android   File: SentryEnvelopeItem.java    License: MIT License 6 votes vote down vote up
public static @NotNull SentryEnvelopeItem fromSession(
    final @NotNull ISerializer serializer, final @NotNull Session session) throws IOException {
  Objects.requireNonNull(serializer, "ISerializer is required.");
  Objects.requireNonNull(session, "Session is required.");

  final CachedItem cachedItem =
      new CachedItem(
          () -> {
            try (final ByteArrayOutputStream stream = new ByteArrayOutputStream();
                final Writer writer = new BufferedWriter(new OutputStreamWriter(stream, UTF_8))) {
              serializer.serialize(session, writer);
              return stream.toByteArray();
            }
          });

  SentryEnvelopeItemHeader itemHeader =
      new SentryEnvelopeItemHeader(
          SentryItemType.Session, () -> cachedItem.getBytes().length, "application/json", null);

  return new SentryEnvelopeItem(itemHeader, () -> cachedItem.getBytes());
}
 
Example 4
Project: leetcode-editor   File: HttpRequestUtils.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse process(@NotNull HttpRequests.Request request) throws IOException {

    if (StringUtils.isNoneBlank(httpRequest.getBody())) {
        request.write(httpRequest.getBody());
    }

    URLConnection urlConnection = request.getConnection();

    if (!(urlConnection instanceof HttpURLConnection)) {
        httpResponse.setStatusCode(-1);
        return httpResponse;
    } else {
        httpResponse.setStatusCode(((HttpURLConnection) urlConnection).getResponseCode());
    }

    try {
        httpResponse.setBody(request.readString());
    } catch (IOException ignore) {
    }
    return httpResponse;
}
 
Example 5
Project: eosio-java   File: EOSFormatter.java    License: MIT License 6 votes vote down vote up
/**
 * Extract serialized transaction from a signable transaction
 * <p>
 * Signable signature structure:
 * <p>
 * chainId (64 characters) + serialized transaction + 32 bytes of 0
 *
 * @param eosTransaction - the input signable transaction
 * @return - extracted serialized transaction from the input signable transaction
 * @throws EOSFormatterError if input is invalid
 */
public static String extractSerializedTransactionFromSignable(@NotNull String eosTransaction)
        throws EOSFormatterError {
    if (eosTransaction.isEmpty()) {
        throw new EOSFormatterError(ErrorConstants.EMPTY_INPUT_EXTRACT_SERIALIZIED_TRANS_FROM_SIGNABLE);
    }

    if (eosTransaction.length() <= MINIMUM_SIGNABLE_TRANSACTION_LENGTH) {
        throw new EOSFormatterError(String.format(ErrorConstants.INVALID_INPUT_SIGNABLE_TRANS_LENGTH_EXTRACT_SERIALIZIED_TRANS_FROM_SIGNABLE, MINIMUM_SIGNABLE_TRANSACTION_LENGTH));
    }

    if (!eosTransaction.endsWith(Hex.toHexString(new byte[32]))) {
        throw new EOSFormatterError(ErrorConstants.INVALID_INPUT_SIGNABLE_TRANS_EXTRACT_SERIALIZIED_TRANS_FROM_SIGNABLE);
    }

    try {
        String cutChainId = eosTransaction.substring(CHAIN_ID_LENGTH);
        return cutChainId.substring(0, cutChainId.length() - Hex.toHexString(new byte[32]).length());
    } catch (Exception ex) {
        throw new EOSFormatterError(ErrorConstants.EXTRACT_SERIALIZIED_TRANS_FROM_SIGNABLE_ERROR, ex);
    }
}
 
Example 6
Project: markdown-image-kit   File: AliyunOssClient.java    License: MIT License 6 votes vote down vote up
/**
 * Upload string.
 *
 * @param ossClient the ossClient client
 * @param instream  the instream
 * @param fileName  the file name
 * @return the string
 */
public String upload(@NotNull OSS ossClient,
                     @NotNull InputStream instream,
                     @NotNull String fileName) {
    try {
        // 创建上传 Object 的 Metadata
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(instream.available());
        objectMetadata.setCacheControl("no-cache");
        objectMetadata.setHeader("Pragma", "no-cache");
        objectMetadata.setContentType(ImageUtils.getImageType(fileName));
        objectMetadata.setContentDisposition("inline;filename=" + fileName);
        ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
        return getUrl(ossClient, filedir, fileName);
    } catch (IOException | OSSException | ClientException e) {
        log.trace("", e);
    }
    return "";
}
 
Example 7
Project: IntelliJDeodorant   File: PsiUtils.java    License: MIT License 6 votes vote down vote up
private static boolean isInsideTestDirectory(final @NotNull PsiJavaFile file) {
    Optional<PsiDirectory> optionalDirectory = getDirectoryWithRootPackageFor(file);

    if (!optionalDirectory.isPresent()) {
        return false;
    }

    PsiDirectory directory = optionalDirectory.get();

    while (directory != null) {
        String dirName = directory.getName().toLowerCase();
        if (dirName.equals("test") || dirName.equals("tests")) {
            return true;
        }

        directory = directory.getParentDirectory();
    }

    return false;
}
 
Example 8
Project: markdown-image-kit   File: ProjectSettingsPage.java    License: MIT License 6 votes vote down vote up
/**
 * 处理被选中的单选框
 *
 * @param group  the group
 * @param button the button
 */
private void addChangeTagRadioButton(@NotNull ButtonGroup group, JRadioButton button) {
    group.add(button);
    // 构造一个监听器,响应checkBox事件
    ActionListener actionListener = e -> {
        Object sourceObject = e.getSource();
        if (sourceObject instanceof JRadioButton) {
            JRadioButton sourceButton = (JRadioButton) sourceObject;
            if (ImageMarkEnum.CUSTOM.text.equals(sourceButton.getText())) {
                customHtmlTypeTextField.setEnabled(true);
            } else {
                customHtmlTypeTextField.setEnabled(false);
            }
        }
    };
    button.addActionListener(actionListener);
}
 
Example 9
Project: invest-openapi-java-sdk   File: TradingParameters.java    License: Apache License 2.0 5 votes vote down vote up
public TradingParameters(@NotNull final String ssoToken,
                         @NotNull final String[] tickers,
                         @NotNull final CandleInterval[] candleIntervals,
                         final boolean sandboxMode) {
    this.ssoToken = ssoToken;
    this.tickers = tickers;
    this.candleIntervals = candleIntervals;
    this.sandboxMode = sandboxMode;
}
 
Example 10
Project: Box   File: Deobfuscator.java    License: Apache License 2.0 5 votes vote down vote up
public Deobfuscator(JadxArgs args, @NotNull List<DexNode> dexNodes, Path deobfMapFile) {
	this.args = args;
	this.dexNodes = dexNodes;

	this.minLength = args.getDeobfuscationMinLength();
	this.maxLength = args.getDeobfuscationMaxLength();
	this.useSourceNameAsAlias = args.isUseSourceNameAsClassAlias();

	this.deobfPresets = new DeobfPresets(this, deobfMapFile);
}
 
Example 11
Project: schedge   File: ParseSection.java    License: MIT License 5 votes vote down vote up
public static SectionAttribute parse(@NotNull String rawData) {
  logger.debug("parsing raw catalog section data into SectionAttribute...");

  rawData = rawData.trim();

  if (rawData.equals("")) {
    logger.warn("Got bad data: empty string");
    return null; // the course doesn't exist
  }

  Document doc = Jsoup.parse(rawData);
  Element failed = doc.selectFirst("div.alert.alert-info");
  if (failed != null) {
    logger.warn("Got bad data: " + failed.text());
    return null; // the course doesn't exist
  }

  Elements elements = doc.select("a");
  String link = null;
  for (Element element : elements) {
    String el = element.attr("href");
    if (el.contains("mapBuilding")) {
      link = el;
    }
  }

  doc.select("a").unwrap();
  doc.select("i").unwrap();
  doc.select("b").unwrap();
  Element outerDataSection = doc.selectFirst("body > section.main");
  Element innerDataSection = outerDataSection.selectFirst("> section");
  Element courseNameDiv = innerDataSection.selectFirst("> div.primary-head");
  String courseName = courseNameDiv.text();
  Elements dataDivs =
      innerDataSection.select("> div.section-content.clearfix");
  Map<String, String> secData = parseSectionAttributes(dataDivs);

  return parsingElements(secData, courseName, link);
}
 
Example 12
Project: synopsys-detect   File: CondaCliDetectableTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void assertExtraction(@NotNull final Extraction extraction) {
    Assertions.assertEquals(1, extraction.getCodeLocations().size());

    NameVersionGraphAssert graphAssert = new NameVersionGraphAssert(Forge.ANACONDA, extraction.getCodeLocations().get(0).getDependencyGraph());
    graphAssert.hasRootSize(2);
    graphAssert.hasRootDependency("mkl", "2017.0.3-0-osx-64");
    graphAssert.hasRootDependency("numpy", "1.13.1-py36_0-osx-64");

}
 
Example 13
Project: smart-home-java   File: MySmartHomeApp.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public void onDisconnect(DisconnectRequest disconnectRequest, Map<?, ?> headers) {
  String token = (String) headers.get("authorization");
  try {
    String userId = database.getUserId(token);
    database.setHomegraph(userId, false);
  } catch (Exception e) {
    LOGGER.error("failed to get user id for token: %d", token);
  }
}
 
Example 14
Project: alibaba-rsocket-broker   File: RSocketEncodingFacadeImpl.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public ByteBuf encodingParams(@Nullable Object[] args, RSocketMimeType encodingType) {
    try {
        ObjectEncodingHandler handler = handlerMap.get(encodingType);
        return handler.encodingParams(args);
    } catch (Exception e) {
        log.error(RsocketErrorCode.message("RST-700500", "Object[]", encodingType.getName()), e);
        return EMPTY_BUFFER;
    }
}
 
Example 15
Project: idea-php-generics-plugin   File: GenericsUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Resolve the given parameter to find possible psalm docs recursively
 *
 * $foo->foo([])
 *
 * TODO: method search in recursion
 */
@NotNull
public static Collection<ParameterArrayType> getTypesForParameter(@NotNull PsiElement psiElement) {
    PsiElement parent = psiElement.getParent();

    if (parent instanceof ParameterList) {
        PsiElement functionReference = parent.getParent();
        if (functionReference instanceof FunctionReference) {
            PsiElement resolve = ((FunctionReference) functionReference).resolve();

            if (resolve instanceof Function) {
                Parameter[] functionParameters = ((Function) resolve).getParameters();

                int currentParameterIndex = PhpElementsUtil.getCurrentParameterIndex((ParameterList) parent, psiElement);
                if (currentParameterIndex >= 0 && functionParameters.length - 1 >= currentParameterIndex) {
                    String name = functionParameters[currentParameterIndex].getName();
                    PhpDocComment docComment = ((Function) resolve).getDocComment();

                    if (docComment != null) {
                        return GenericsUtil.getParameterArrayTypes(docComment, name);
                    }
                }
            }
        }
    }

    return Collections.emptyList();
}
 
Example 16
Project: sentry-android   File: EnvelopeSender.java    License: MIT License 5 votes vote down vote up
public EnvelopeSender(
    final @NotNull IHub hub,
    final @NotNull IEnvelopeReader envelopeReader,
    final @NotNull ISerializer serializer,
    final @NotNull ILogger logger,
    final long flushTimeoutMillis) {
  super(logger, flushTimeoutMillis);
  this.hub = Objects.requireNonNull(hub, "Hub is required.");
  this.envelopeReader = Objects.requireNonNull(envelopeReader, "Envelope reader is required.");
  this.serializer = Objects.requireNonNull(serializer, "Serializer is required.");
  this.logger = Objects.requireNonNull(logger, "Logger is required.");
}
 
Example 17
Project: XS2A-Sandbox   File: AccountMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
private AccountDetailsTO getDetails() {
    AccountDetailsTO details = new AccountDetailsTO();
    details.setIban(IBAN);
    details.setAccountStatus(ENABLED);
    details.setAccountType(CASH);
    details.setBalances(Collections.singletonList(new AccountBalanceTO(new AmountTO(CURRENCY, BigDecimal.TEN), INTERIM_AVAILABLE, null, null, null, null)));
    details.setCurrency(CURRENCY);
    return details;
}
 
Example 18
Project: sentry-android   File: EnvelopeFileObserver.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("deprecation")
EnvelopeFileObserver(
    String path,
    IEnvelopeSender envelopeSender,
    @NotNull ILogger logger,
    final long flushTimeoutMillis) {
  super(path);
  this.rootPath = Objects.requireNonNull(path, "File path is required.");
  this.envelopeSender = Objects.requireNonNull(envelopeSender, "Envelope sender is required.");
  this.logger = Objects.requireNonNull(logger, "Logger is required.");
  this.flushTimeoutMillis = flushTimeoutMillis;
}
 
Example 19
Project: invest-openapi-java-sdk   File: StreamingRequest.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public String onOffPairId() {
    return new StringBuilder("Candle(")
            .append(figi)
            .append(",")
            .append(interval.name())
            .append(")")
            .toString();
}
 
Example 20
Project: invest-openapi-java-sdk   File: LimitOrder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Создаёт экземпляр со всеми его компонентами.
 *
 * Выбрасывает {@code IllegalArgumentException} при указании лотов менее, чем 1.
 *
 * @param lots Количество лотов.
 * @param operation Тип операции.
 * @param price Желаемая цена.
 */
public LimitOrder(final int lots,
                  @NotNull final Operation operation,
                  @NotNull final BigDecimal price) {
    if (lots < 1) {
        throw new IllegalArgumentException("Количество лотов должно быть положительным.");
    }

    this.lots = lots;
    this.operation = operation;
    this.price = price;
}
 
Example 21
Project: synopsys-detect   File: LongValueParser.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public Long parse(@NotNull final String value) throws ValueParseException {
    try {
        return Long.parseLong(value);
    } catch (NumberFormatException e) {
        throw new ValueParseException(value, "long", e);
    }
}
 
Example 22
Project: markdown-image-kit   File: MoveToOtherStorageAction.java    License: MIT License 5 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent event) {

    final Project project = event.getProject();
    if (project != null) {
        MoveToOtherOssSettingsDialog dialog = showDialog();
        if (dialog == null) {
            return;
        }
        String domain = dialog.getDomain().getText().trim();
        if (StringUtils.isBlank(domain)) {
            return;
        }
        if (!OssState.getStatus(dialog.getCloudComboBox().getSelectedIndex()- 1)) {
            return;
        }

        int cloudIndex = dialog.getCloudComboBox().getSelectedIndex() - 1;
        CloudEnum cloudEnum = OssState.getCloudType(cloudIndex);

        EventData data = new EventData()
            .setActionEvent(event)
            .setProject(project)
            .setClient(ClientUtils.getClient(cloudEnum))
            // client 有可能为 null, 使用 cloudEnum 安全点
            .setClientName(cloudEnum.title);

        // http://www.jetbrains.org/intellij/sdk/docs/basics/persisting_state_of_components.html
        PropertiesComponent propComp = PropertiesComponent.getInstance();
        // 过滤掉配置用户输入后的其他标签
        propComp.setValue(MarkdownFileFilter.FILTER_KEY, domain.equals(MOVE_ALL) ? "" : domain);

        new ActionTask(project,
                       MikBundle.message("mik.action.move.process", cloudEnum.title),
                       ActionManager.buildMoveImageChain(data)).queue();
    }
}
 
Example 23
Project: sentry-android   File: HttpTransport.java    License: MIT License 5 votes vote down vote up
/**
 * Check if an itemType is retry after or not
 *
 * @param itemType the itemType (eg event, session, etc...)
 * @return true if retry after or false otherwise
 */
@SuppressWarnings("JdkObsolete")
@Override
public boolean isRetryAfter(final @NotNull String itemType) {
  final DataCategory dataCategory = getCategoryFromItemType(itemType);
  final Date currentDate = new Date(currentDateProvider.getCurrentTimeMillis());

  // check all categories
  final Date dateAllCategories = sentryRetryAfterLimit.get(DataCategory.All);
  if (dateAllCategories != null) {
    if (!currentDate.after(dateAllCategories)) {
      return true;
    }
  }

  // Unknown should not be rate limited
  if (DataCategory.Unknown.equals(dataCategory)) {
    return false;
  }

  // check for specific dataCategory
  final Date dateCategory = sentryRetryAfterLimit.get(dataCategory);
  if (dateCategory != null) {
    return !currentDate.after(dateCategory);
  }

  return false;
}
 
Example 24
Project: idea-php-generics-plugin   File: PhpTypeProviderUtil.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a signature for PhpType implementation which must be resolved inside 'getBySignature'
 *
 * eg. foo(MyClass::class) => "#F\\foo|#K#C\\Foo.class"
 *
 * foo($this->foo), foo('foobar')
 */
@Nullable
public static String getReferenceSignatureByFirstParameter(@NotNull FunctionReference functionReference, char trimKey) {
    String refSignature = functionReference.getSignature();
    if(StringUtil.isEmpty(refSignature)) {
        return null;
    }

    PsiElement[] parameters = functionReference.getParameters();
    if(parameters.length == 0) {
        return null;
    }

    PsiElement parameter = parameters[0];

    // we already have a string value
    if ((parameter instanceof StringLiteralExpression)) {
        String param = ((StringLiteralExpression)parameter).getContents();
        if (StringUtil.isNotEmpty(param)) {
            return refSignature + trimKey + param;
        }

        return null;
    }

    // whitelist here; we can also provide some more but think of performance
    // Service::NAME, $this->name and Entity::CLASS;
    if ((parameter instanceof ClassConstantReference || parameter instanceof FieldReference)) {
        String signature = ((PhpReference) parameter).getSignature();
        if (StringUtil.isNotEmpty(signature)) {
            return refSignature + trimKey + signature;
        }
    }

    return null;
}
 
Example 25
Project: sentry-android   File: LifecycleWatcher.java    License: MIT License 5 votes vote down vote up
LifecycleWatcher(
    final @NotNull IHub hub,
    final long sessionIntervalMillis,
    final boolean enableSessionTracking,
    final boolean enableAppLifecycleBreadcrumbs) {
  this(
      hub,
      sessionIntervalMillis,
      enableSessionTracking,
      enableAppLifecycleBreadcrumbs,
      CurrentDateProvider.getInstance());
}
 
Example 26
Project: sentry-android   File: RootChecker.java    License: MIT License 5 votes vote down vote up
public RootChecker(
    final @NotNull Context context,
    final @NotNull IBuildInfoProvider buildInfoProvider,
    final @NotNull ILogger logger) {
  this(
      context,
      buildInfoProvider,
      logger,
      new String[] {
        "/system/app/Superuser.apk",
        "/sbin/su",
        "/system/bin/su",
        "/system/xbin/su",
        "/data/local/xbin/su",
        "/data/local/bin/su",
        "/system/sd/xbin/su",
        "/system/bin/failsafe/su",
        "/data/local/su",
        "/su/bin/su",
        "/su/bin",
        "/system/xbin/daemonsu"
      },
      new String[] {
        "com.devadvance.rootcloak",
        "com.devadvance.rootcloakplus",
        "com.koushikdutta.superuser",
        "com.thirdparty.superuser",
        "eu.chainfire.supersu", // SuperSU
        "com.noshufou.android.su" // superuser
      },
      Runtime.getRuntime());
}
 
Example 27
Project: Android-Keyboard   File: ItemTouchHelperCallback.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean onMove(@NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder
        , @NotNull RecyclerView.ViewHolder target) {
    if(dragFrom == -1) {
        dragFrom =  viewHolder.getAdapterPosition();
    }
    dragTo = target.getAdapterPosition();
    mAdapter.onItemMove(viewHolder.getAdapterPosition(), target.getAdapterPosition());
    return true;
}
 
Example 28
Project: dagger-reflect   File: WrongRetentionDetector.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private static String getRetentionPolicyForQualifiedName(@NotNull String retentionPolicy) {
  // Values are same for Kotlin and Java
  for (RetentionPolicy policy : RetentionPolicy.values()) {
    final String javaQualifiedName = CLASS_JAVA_RETENTION_POLICY + "." + policy.name();
    final String kotlinQualifiedName = CLASS_KOTLIN_RETENTION_POLICY + "." + policy.name();
    if (javaQualifiedName.equals(retentionPolicy)
        || kotlinQualifiedName.equals(retentionPolicy)) {
      return policy.name();
    }
  }
  return null;
}
 
Example 29
Project: alibaba-rsocket-broker   File: HessianEncoder.java    License: Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public Flux<DataBuffer> encode(@NotNull Publisher<?> inputStream, @NotNull DataBufferFactory bufferFactory, ResolvableType elementType, MimeType mimeType, Map<String, Object> hints) {
    return Flux.from(inputStream)
            .handle((obj, sink) -> {
                try {
                    sink.next(encode(obj, bufferFactory));
                } catch (Exception e) {
                    sink.error(e);
                }
            });
}
 
Example 30
Project: idea-php-generics-plugin   File: AnnotationLightCodeInsightFixtureTestCase.java    License: MIT License 5 votes vote down vote up
public void assertLineMarkerIsEmpty(@NotNull PsiElement psiElement) {

        final List<PsiElement> elements = collectPsiElementsRecursive(psiElement);

        for (LineMarkerProvider lineMarkerProvider : LineMarkerProviders.INSTANCE.allForLanguage(psiElement.getLanguage())) {
            Collection<LineMarkerInfo> lineMarkerInfos = new ArrayList<>();
            lineMarkerProvider.collectSlowLineMarkers(elements, lineMarkerInfos);

            if(lineMarkerInfos.size() > 0) {
                fail(String.format("Fail that line marker is empty because it matches '%s'", lineMarkerProvider.getClass()));
            }
        }
    }
 
Example 31
Project: markdown-image-kit   File: MarkdownUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Get image path string.
 *
 * @param mark the mark
 * @return the string
 */
@NotNull
private static String getImagePath(String mark){
    if (StringUtils.isBlank(mark)) {
        return "";
    }

    return mark.substring(mark.indexOf(ImageContents.IMAGE_MARK_MIDDLE) + ImageContents.IMAGE_MARK_MIDDLE.length(),
                          mark.indexOf(ImageContents.IMAGE_MARK_SUFFIX)).trim();
}
 
Example 32
Project: idea-php-generics-plugin   File: CompletionNavigationProvider.java    License: MIT License 5 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet result) {
    PsiElement position = parameters.getPosition();

    ArrayCreationExpression parentOfType = PsiTreeUtil.getParentOfType(position, ArrayCreationExpression.class);
    if (parentOfType != null) {
        result.addAllElements(GenericsUtil.getTypesForParameter(parentOfType).stream()
            .map(CompletionNavigationProvider::createParameterArrayTypeLookupElement)
            .collect(Collectors.toSet())
        );
    }
}
 
Example 33
Project: synopsys-detect   File: ValueParseException.java    License: Apache License 2.0 5 votes vote down vote up
public ValueParseException(@NotNull final String rawValue, @NotNull final String typeName, @NotNull final String additionalMessage, @Nullable final Exception innerException) {
    super(String.format("Unable to parse raw value '%s' and coerce it into type '%s'. %s", rawValue, typeName, additionalMessage), innerException);
    this.rawValue = rawValue;
    this.typeName = typeName;
    this.additionalMessage = additionalMessage;
    this.innerException = innerException;
}
 
Example 34
Project: IntelliJDeodorant   File: RefactoringsApplier.java    License: MIT License 5 votes vote down vote up
private static @NotNull
Map<PsiClass, List<MoveMethodRefactoring>> prepareRefactorings(
        final @NotNull List<MoveMethodRefactoring> refactorings
) {
    return refactorings.stream().collect(
            Collectors.groupingBy(MoveMethodRefactoring::getTargetClass, Collectors.toList())
    );
}
 
Example 35
Project: alibaba-rsocket-broker   File: RSocketBrokerResponderHandler.java    License: Apache License 2.0 4 votes vote down vote up
public RSocketBrokerResponderHandler(@NotNull ConnectionSetupPayload setupPayload,
                                     @NotNull RSocketCompositeMetadata compositeMetadata,
                                     @NotNull AppMetadata appMetadata,
                                     @NotNull RSocketAppPrincipal principal,
                                     RSocket peerRsocket,
                                     ServiceRoutingSelector routingSelector,
                                     TopicProcessor<CloudEventImpl> eventProcessor,
                                     RSocketBrokerHandlerRegistry handlerRegistry,
                                     ServiceMeshInspector serviceMeshInspector,
                                     @Null RSocket upstreamRSocket) {
    try {
        this.upstreamRSocket = upstreamRSocket;
        RSocketMimeType dataType = RSocketMimeType.valueOfType(setupPayload.dataMimeType());
        if (dataType != null) {
            this.defaultMessageMimeType = new MessageMimeTypeMetadata(dataType);
            this.defaultEncodingBytebuf = constructDefaultDataEncoding();
        }
        this.appMetadata = appMetadata;
        this.id = appMetadata.getId();
        this.uuid = appMetadata.getUuid();
        //app tags hashcode set
        this.appTagsHashCodeSet.add(("id=" + this.id).hashCode());
        this.appTagsHashCodeSet.add(("uuid=" + this.uuid).hashCode());
        if (appMetadata.getIp() != null && !appMetadata.getIp().isEmpty()) {
            this.appTagsHashCodeSet.add(("ip=" + this.appMetadata.getIp()).hashCode());
        }
        if (appMetadata.getMetadata() != null) {
            for (Map.Entry<String, String> entry : appMetadata.getMetadata().entrySet()) {
                this.appTagsHashCodeSet.add((entry.getKey() + "=" + entry.getValue()).hashCode());
            }
        }
        this.principal = principal;
        this.peerRsocket = peerRsocket;
        this.routingSelector = routingSelector;
        this.eventProcessor = eventProcessor;
        this.handlerRegistry = handlerRegistry;
        this.serviceMeshInspector = serviceMeshInspector;
        //publish services metadata
        if (compositeMetadata.contains(RSocketMimeType.ServiceRegistry)) {
            ServiceRegistryMetadata serviceRegistryMetadata = ServiceRegistryMetadata.from(compositeMetadata.getMetadata(RSocketMimeType.ServiceRegistry));
            if (serviceRegistryMetadata.getPublished() != null && !serviceRegistryMetadata.getPublished().isEmpty()) {
                setPeerServices(serviceRegistryMetadata.getPublished());
                registerPublishedServices();
            }
        }
        //new comboOnClose
        this.comboOnClose = Mono.first(super.onClose(), peerRsocket.onClose());
        this.comboOnClose.doOnTerminate(this::unRegisterPublishedServices).subscribeOn(Schedulers.parallel()).subscribe();
    } catch (Exception e) {
        log.error(RsocketErrorCode.message("RST-500400"), e);
    }
}
 
Example 36
Project: leetcode-editor   File: TimerBarWidget.java    License: Apache License 2.0 4 votes vote down vote up
@Nullable
public StatusBarWidget.WidgetPresentation getPresentation(@NotNull StatusBarWidget.PlatformType type) {
    return null;
}
 
Example 37
Project: idea-php-generics-plugin   File: PsalmValidatorConfigurationManager.java    License: MIT License 4 votes vote down vote up
public static PsalmValidatorConfigurationManager getInstance(@NotNull Project project) {
    return ServiceManager.getService(project, PsalmValidatorConfigurationManager.class);
}
 
Example 38
Project: idea-php-generics-plugin   File: CheckstyleQualityToolMessageProcessor.java    License: MIT License 4 votes vote down vote up
@Nullable
protected HighlightDisplayLevel severityToDisplayLevel(@NotNull QualityToolMessage.Severity severity) {
    return QualityToolMessage.Severity.WARNING.equals(severity) ? this.myWarningsHighlightLevel : null;
}
 
Example 39
Project: easy_javadoc   File: EasyJavadocConfigComponent.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void loadState(@NotNull EasyJavadocConfiguration state) {
    XmlSerializerUtil.copyBean(state, Objects.requireNonNull(getState()));
}
 
Example 40
Project: Pixiv-Shaft   File: RubySSLSocketFactory.java    License: MIT License 4 votes vote down vote up
@NotNull
public String[] getDefaultCipherSuites() {
    return new String[0];
}