org.jetbrains.annotations.NotNull Java Examples

The following examples show how to use org.jetbrains.annotations.NotNull. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AliyunOssClient.java    From markdown-image-kit with 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 #2
Source File: ProjectSettingsPage.java    From markdown-image-kit with 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 #3
Source File: EOSFormatter.java    From eosio-java with 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 #4
Source File: EOSFormatter.java    From eosio-java with 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 #5
Source File: PsiUtils.java    From IntelliJDeodorant with 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 #6
Source File: AnnotationLightCodeInsightFixtureTestCase.java    From idea-php-generics-plugin with 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 #7
Source File: SentryEnvelopeItem.java    From sentry-android with 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 #8
Source File: HttpRequestUtils.java    From leetcode-editor with 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 #9
Source File: AccountMapperTest.java    From XS2A-Sandbox with 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 #10
Source File: LimitOrder.java    From invest-openapi-java-sdk with 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 #11
Source File: StreamingRequest.java    From invest-openapi-java-sdk with 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 #12
Source File: EnvelopeFileObserver.java    From sentry-android with 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 #13
Source File: CondaCliDetectableTest.java    From synopsys-detect with 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 #14
Source File: EnvelopeSender.java    From sentry-android with 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 #15
Source File: ParseSection.java    From schedge with 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 #16
Source File: MySmartHomeApp.java    From smart-home-java with 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 #17
Source File: RefactoringsApplier.java    From IntelliJDeodorant with 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 #18
Source File: LongValueParser.java    From synopsys-detect with 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 #19
Source File: MoveToOtherStorageAction.java    From markdown-image-kit with 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 #20
Source File: HttpTransport.java    From sentry-android with 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 #21
Source File: PhpTypeProviderUtil.java    From idea-php-generics-plugin with 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 #22
Source File: LifecycleWatcher.java    From sentry-android with 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 #23
Source File: RootChecker.java    From sentry-android with 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 #24
Source File: ItemTouchHelperCallback.java    From Android-Keyboard with 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 #25
Source File: WrongRetentionDetector.java    From dagger-reflect with 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 #26
Source File: HessianEncoder.java    From alibaba-rsocket-broker with 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 #27
Source File: AnnotationLightCodeInsightFixtureTestCase.java    From idea-php-generics-plugin with 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 #28
Source File: MarkdownUtils.java    From markdown-image-kit with 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 #29
Source File: CompletionNavigationProvider.java    From idea-php-generics-plugin with 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 #30
Source File: ValueParseException.java    From synopsys-detect with 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;
}