org.jetbrains.annotations.Nullable Java Examples

The following examples show how to use org.jetbrains.annotations.Nullable. 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: LoadBalancedRSocket.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
public void onRSocketClosed(String rsocketUri, RSocket rsocket, @Nullable Throwable cause) {
    //in last rsocket uris or not
    if (this.lastRSocketUris.contains(rsocketUri)) {
        this.unHealthyUriSet.add(rsocketUri);
        if (activeSockets.containsKey(rsocketUri)) {
            activeSockets.remove(rsocketUri);
            this.randomSelector = new RandomSelector<>(this.serviceId, new ArrayList<>(activeSockets.values()));
            log.error(RsocketErrorCode.message("RST-500407", rsocketUri));
            tryToReconnect(rsocketUri, cause);
        }
        if (!rsocket.isDisposed()) {
            try {
                rsocket.dispose();
            } catch (Exception ignore) {

            }
        }
    }
}
 
Example #2
Source File: SentryClient.java    From sentry-android with MIT License 6 votes vote down vote up
private @Nullable SentryEvent executeBeforeSend(
    @NotNull SentryEvent event, final @Nullable Object hint) {
  final SentryOptions.BeforeSendCallback beforeSend = options.getBeforeSend();
  if (beforeSend != null) {
    try {
      event = beforeSend.execute(event, hint);
    } catch (Exception e) {
      options
          .getLogger()
          .log(
              SentryLevel.ERROR,
              "The BeforeSend callback threw an exception. It will be added as breadcrumb and continue.",
              e);

      Breadcrumb breadcrumb = new Breadcrumb();
      breadcrumb.setMessage("BeforeSend callback failed.");
      breadcrumb.setCategory("SentryClient");
      breadcrumb.setLevel(SentryLevel.ERROR);
      breadcrumb.setData("sentry:message", e.getMessage());
      event.addBreadcrumb(breadcrumb);
    }
  }
  return event;
}
 
Example #3
Source File: AuthenticationServiceJwtImpl.java    From alibaba-rsocket-broker with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public RSocketAppPrincipal auth(String type, String credentials) {
    int tokenHashCode = credentials.hashCode();
    RSocketAppPrincipal principal = jwtVerifyCache.getIfPresent(tokenHashCode);
    for (JWTVerifier verifier : verifiers) {
        try {
            principal = new JwtPrincipal(verifier.verify(credentials), credentials);
            jwtVerifyCache.put(tokenHashCode, principal);
            break;
        } catch (JWTVerificationException ignore) {

        }
    }
    return principal;
}
 
Example #4
Source File: Session.java    From sentry-android with MIT License 6 votes vote down vote up
/**
 * Ends a session and update its values
 *
 * @param timestamp the timestamp or null
 */
public void end(final @Nullable Date timestamp) {
  synchronized (sessionLock) {
    init = null;

    // at this state it might be Crashed already, so we don't check for it.
    if (status == State.Ok) {
      status = State.Exited;
    }

    if (timestamp != null) {
      this.timestamp = timestamp;
    } else {
      this.timestamp = DateUtils.getCurrentDateTime();
    }

    duration = calculateDurationTime(this.timestamp);
    sequence = getSequenceTimestamp(this.timestamp);
  }
}
 
Example #5
Source File: ComponentInvocationHandler.java    From dagger-reflect with Apache License 2.0 6 votes vote down vote up
@Override
public @Nullable Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  if (method.getDeclaringClass() == Object.class) {
    return method.invoke(this, args);
  }

  MethodInvocationHandler handler = handlers.get(method);
  if (handler == null) {
    handler = createMethodInvocationHandler(method, scope);
    MethodInvocationHandler replaced = handlers.putIfAbsent(method, handler);
    if (replaced != null) {
      handler = replaced;
    }
  }
  return handler.invoke(args);
}
 
Example #6
Source File: DefaultAndroidEventProcessor.java    From sentry-android with MIT License 6 votes vote down vote up
/**
 * Get the device's current kernel version, as a string. Attempts to read /proc/version, and falls
 * back to the 'os.version' System Property.
 *
 * @return the device's current kernel version, as a string
 */
@SuppressWarnings("DefaultCharset")
private @Nullable String getKernelVersion() {
  // its possible to try to execute 'uname' and parse it or also another unix commands or even
  // looking for well known root installed apps
  String errorMsg = "Exception while attempting to read kernel information";
  String defaultVersion = System.getProperty("os.version");

  File file = new File("/proc/version");
  if (!file.canRead()) {
    return defaultVersion;
  }
  try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    return br.readLine();
  } catch (IOException e) {
    logger.log(SentryLevel.ERROR, errorMsg, e);
  }

  return defaultVersion;
}
 
Example #7
Source File: EnvelopeFileObserver.java    From sentry-android with MIT License 6 votes vote down vote up
@Override
public void onEvent(int eventType, @Nullable String relativePath) {
  if (relativePath == null || eventType != FileObserver.CLOSE_WRITE) {
    return;
  }

  logger.log(
      SentryLevel.DEBUG,
      "onEvent fired for EnvelopeFileObserver with event type %d on path: %s for file %s.",
      eventType,
      this.rootPath,
      relativePath);

  // TODO: Only some event types should be pass through?

  final CachedEnvelopeHint hint = new CachedEnvelopeHint(flushTimeoutMillis, logger);
  envelopeSender.processEnvelopeFile(this.rootPath + File.separator + relativePath, hint);
}
 
Example #8
Source File: EasyJavadocConfigComponent.java    From easy_javadoc with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public EasyJavadocConfiguration getState() {
    if (configuration == null) {
        configuration = new EasyJavadocConfiguration();
        configuration.setAuthor(System.getProperty("user.name"));
        configuration.setDateFormat(DEFAULT_DATE_FORMAT);
        configuration.setSimpleFieldDoc(true);
        configuration.setWordMap(new TreeMap<>());
        configuration.setTranslator("有道翻译");

        TemplateConfig config = new TemplateConfig();
        config.setIsDefault(true);
        config.setTemplate(StringUtils.EMPTY);
        config.setCustomMap(new TreeMap<>());
        configuration.setClassTemplateConfig(config);
        configuration.setMethodTemplateConfig(config);
        configuration.setFieldTemplateConfig(config);
    }
    return configuration;
}
 
Example #9
Source File: GenericsUtil.java    From idea-php-generics-plugin with MIT License 6 votes vote down vote up
@Nullable
private static Integer getCurrentParameterIndex(PsiElement parameter) {
    PsiElement parameterList = parameter.getContext();
    if(!(parameterList instanceof ParameterList)) {
        return null;
    }

    PsiElement[] parameters = ((ParameterList) parameterList).getParameters();

    int i;
    for(i = 0; i < parameters.length; i = i + 1) {
        if(parameters[i].equals(parameter)) {
            return i;
        }
    }

    return null;
}
 
Example #10
Source File: CommandExecutor.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
private static DataContext createDataContext(Command command, URI context,
                                                    Application workbench) {

    return new DataContext() {
        @Nullable
        @Override
        public Object getData(@NotNull String dataId) {
            if (LSP_COMMAND_PARAMETER_TYPE_ID.equals(dataId)) {
                return command;
            } else if (LSP_PATH_PARAMETER_TYPE_ID.equals(dataId)) {
                return context;
            }
            return null;
        }
    };
}
 
Example #11
Source File: ImageUtils.java    From markdown-image-kit with MIT License 6 votes vote down vote up
/**
 * Gets file type.
 *
 * @param is the is
 * @return the file type
 * @throws IOException the io exception
 */
@Nullable
public static FileType getFileType(InputStream is) throws IOException {
    byte[] src = new byte[28];
    is.read(src, 0, 28);
    StringBuilder stringBuilder = new StringBuilder();
    for (byte b : src) {
        int v = b & 0xFF;
        String hv = Integer.toHexString(v).toUpperCase();
        if (hv.length() < 2) {
            stringBuilder.append(0);
        }
        stringBuilder.append(hv);
    }
    FileType[] fileTypes = FileType.values();
    for (FileType fileType : fileTypes) {
        if (stringBuilder.toString().startsWith(fileType.getValue())) {
            return fileType;
        }
    }
    return null;
}
 
Example #12
Source File: RSocketCompositeMetadata.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Nullable
public BinaryRoutingMetadata getBinaryRoutingMetadata() {
    if (binaryRoutingMetadata == null && metadataStore.containsKey(RSocketMimeType.BinaryRouting.getType())) {
        ByteBuf content = metadataStore.get(RSocketMimeType.BinaryRouting.getType());
        this.binaryRoutingMetadata = BinaryRoutingMetadata.from(content);
    }
    return this.binaryRoutingMetadata;
}
 
Example #13
Source File: AsyncConnection.java    From sentry-android with MIT License 5 votes vote down vote up
/**
 * It marks the hints when sending has failed, so it's not necessary to wait the timeout
 *
 * @param hint the Hint
 * @param retry if event should be retried or not
 */
private static void markHintWhenSendingFailed(final @Nullable Object hint, final boolean retry) {
  if (hint instanceof SubmissionResult) {
    ((SubmissionResult) hint).setResult(false);
  }
  if (hint instanceof Retryable) {
    ((Retryable) hint).setRetry(retry);
  }
}
 
Example #14
Source File: RequestBuilder.java    From leetcode-editor with Apache License 2.0 5 votes vote down vote up
public <T> T connect(@NotNull HttpRequests.RequestProcessor<T> processor, T errorValue, @Nullable Logger logger) {
    try {
        return connect(processor);
    }
    catch (Throwable e) {
        if (logger != null) {
            logger.warn(e);
        }
        return errorValue;
    }
}
 
Example #15
Source File: PoetryLockParser.java    From synopsys-detect with Apache License 2.0 5 votes vote down vote up
private List<String> extractFromDependencyList(@Nullable TomlTable dependencyList) {
    List<String> dependencies = new ArrayList<>();
    if (dependencyList == null) {
        return dependencies;
    }
    for (List<String> key : dependencyList.keyPathSet()) {
        dependencies.add(key.get(0));
    }
    return dependencies;
}
 
Example #16
Source File: PluginSettingPage.java    From ycy-intellij-plugin with GNU General Public License v3.0 5 votes vote down vote up
/**
 * IDEA 初始化设置页面时,会调用此方法
 *
 * @return 由 {@code UI Designer} 生成的 {@link PluginSettingForm} 页面
 */
@Nullable
@Override
public JComponent createComponent() {
    if (this.form == null) {
        this.form = new PluginSettingForm();
    }
    return this.form.getPluginSettingPanel();
}
 
Example #17
Source File: ObjectEncodingHandlerHessianImpl.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
@NotNull
public ByteBuf encodingResult(@Nullable Object result) throws EncodingException {
    if (result == null) {
        return EMPTY_BUFFER;
    }
    return encode(result);
}
 
Example #18
Source File: TransactionProcessor.java    From eosio-java with MIT License 5 votes vote down vote up
/**
 * Sign the transaction by passing {@link EosioTransactionSignatureRequest} to signature
 * provider
 * <p>
 * Check sign() flow in "Complete Workflow" document for more detail
 *
 * @return success or not
 * @throws TransactionSignError thrown if there are any exceptions during the following:
 *      <br>
 *          - Creating signature. Cause: {@link TransactionCreateSignatureRequestError}
 *      <br>
 *          - Signing. Cause: {@link TransactionGetSignatureError} or {@link SignatureProviderError}
 */
public boolean sign() throws TransactionSignError {
    EosioTransactionSignatureRequest eosioTransactionSignatureRequest;
    try {
        eosioTransactionSignatureRequest = this.createSignatureRequest();
    } catch (TransactionCreateSignatureRequestError transactionCreateSignatureRequestError) {
        throw new TransactionSignError(
                ErrorConstants.TRANSACTION_PROCESSOR_SIGN_CREATE_SIGN_REQUEST_ERROR,
                transactionCreateSignatureRequestError);
    }

    EosioTransactionSignatureResponse eosioTransactionSignatureResponse;
    try {
        eosioTransactionSignatureResponse = this.getSignature(eosioTransactionSignatureRequest);
        if (eosioTransactionSignatureResponse.getError() != null) {
            throw eosioTransactionSignatureResponse.getError();
        }
    } catch (TransactionGetSignatureError transactionGetSignatureError) {
        throw new TransactionSignError(transactionGetSignatureError);
    } catch (@Nullable SignatureProviderError signatureProviderError) {
        throw new TransactionSignError(
                ErrorConstants.TRANSACTION_PROCESSOR_SIGN_SIGNATURE_RESPONSE_ERROR,
                signatureProviderError);
    }

    return true;
}
 
Example #19
Source File: SentryOptions.java    From sentry-android with MIT License 5 votes vote down vote up
/**
 * Returns the sessions path if cacheDirPath is set
 *
 * @return the sessions path or null if not set
 */
public @Nullable String getSessionsPath() {
  if (cacheDirPath == null || cacheDirPath.isEmpty()) {
    return null;
  }
  return cacheDirPath + File.separator + "sessions";
}
 
Example #20
Source File: PrepareForCodeGen.java    From Box with Apache License 2.0 5 votes vote down vote up
@Nullable
private ConstructorInsn searchConstructorCall(MethodNode mth) {
	for (BlockNode block : mth.getBasicBlocks()) {
		for (InsnNode insn : block.getInstructions()) {
			InsnType insnType = insn.getType();
			if (insnType == InsnType.CONSTRUCTOR) {
				ConstructorInsn constrInsn = (ConstructorInsn) insn;
				if (constrInsn.isSuper() || constrInsn.isThis()) {
					return constrInsn;
				}
			}
		}
	}
	return null;
}
 
Example #21
Source File: Reflection.java    From dagger-reflect with Apache License 2.0 5 votes vote down vote up
/**
 * Try to create an instance of {@code cls} using a default constructor. Returns null if no
 * default constructor found.
 */
@SuppressWarnings("unchecked") // Casts implied by cls generic type.
static <T> @Nullable T maybeInstantiate(Class<T> cls) {
  for (Constructor<?> constructor : cls.getDeclaredConstructors()) {
    if (constructor.getParameterTypes().length == 0) {
      return (T) tryInstantiate(constructor);
    }
  }
  return null;
}
 
Example #22
Source File: ComponentScopeBuilder.java    From dagger-reflect with Apache License 2.0 5 votes vote down vote up
static ComponentScopeBuilder create(
    Class<?>[] moduleClasses,
    Class<?>[] dependencyClasses,
    Set<Annotation> scopeAnnotations,
    @Nullable Scope parent) {
  Map<Class<?>, Object> moduleInstances = new LinkedHashMap<>();
  Set<Class<?>> subcomponentClasses = new LinkedHashSet<>();

  Deque<Class<?>> moduleClassQueue = new ArrayDeque<>();
  Collections.addAll(moduleClassQueue, moduleClasses);
  while (!moduleClassQueue.isEmpty()) {
    Class<?> moduleClass = moduleClassQueue.removeFirst();
    Module module = requireAnnotation(moduleClass, Module.class);

    Collections.addAll(moduleClassQueue, module.includes());
    Collections.addAll(subcomponentClasses, module.subcomponents());

    // Start with all modules bound to null. Any remaining nulls will be assumed stateless.
    moduleInstances.put(moduleClass, null);
  }

  Map<Class<?>, Object> dependencyInstances = new LinkedHashMap<>();
  for (Class<?> dependencyClass : dependencyClasses) {
    // Start with all dependencies as null. Any remaining nulls at creation time is an error.
    dependencyInstances.put(dependencyClass, null);
  }

  return new ComponentScopeBuilder(
      moduleInstances, dependencyInstances, subcomponentClasses, scopeAnnotations, parent);
}
 
Example #23
Source File: RenameVisitor.java    From Box with Apache License 2.0 5 votes vote down vote up
@Nullable
private static String getRootPkg(String pkg) {
	if (pkg.isEmpty()) {
		return null;
	}
	int dotPos = pkg.indexOf('.');
	if (dotPos < 0) {
		return pkg;
	}
	return pkg.substring(0, dotPos);
}
 
Example #24
Source File: RegisterArg.java    From Box with Apache License 2.0 5 votes vote down vote up
@Nullable
public ArgType getImmutableType() {
	if (contains(AFlag.IMMUTABLE_TYPE)) {
		return type;
	}
	if (sVar != null) {
		return sVar.getImmutableType();
	}
	return null;
}
 
Example #25
Source File: ReactiveAdapterRxJava2.java    From alibaba-rsocket-broker with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Flux<T> toFlux(@Nullable Object source) {
    if (source instanceof Observable) {
        return (Flux<T>) RxJava2Adapter.observableToFlux((Observable) source, BackpressureStrategy.BUFFER);
    } else if (source instanceof Flowable) {
        return (Flux<T>) RxJava2Adapter.flowableToFlux((Flowable) source);
    } else if (source == null) {
        return Flux.empty();
    } else {
        return (Flux<T>) Flux.just(source);
    }

}
 
Example #26
Source File: DefaultAndroidEventProcessor.java    From sentry-android with MIT License 5 votes vote down vote up
@SuppressWarnings("ObsoleteSdkInt")
private @Nullable String getDeviceName() {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    return Settings.Global.getString(context.getContentResolver(), "device_name");
  } else {
    return null;
  }
}
 
Example #27
Source File: RunManager.java    From synopsys-detect with Apache License 2.0 5 votes vote down vote up
private AggregateOptions determineAggregationStrategy(@Nullable final String aggregateName, final AggregateMode aggregateMode, final UniversalToolsResult universalToolsResult) {
    if (StringUtils.isNotBlank(aggregateName)) {
        if (universalToolsResult.anyFailed()) {
            return AggregateOptions.aggregateButSkipEmpty(aggregateName, aggregateMode);
        } else {
            return AggregateOptions.aggregateAndAlwaysUpload(aggregateName, aggregateMode);
        }
    } else {
        return AggregateOptions.doNotAggregate();
    }
}
 
Example #28
Source File: LinkedProvidesBinding.java    From dagger-reflect with Apache License 2.0 5 votes vote down vote up
@Override
public @Nullable T get() {
  Object[] arguments = new Object[dependencies.length];
  for (int i = 0; i < arguments.length; i++) {
    arguments[i] = dependencies[i].get();
  }
  // The binding is associated with the return type of method as key.
  @SuppressWarnings("unchecked")
  T value = (T) tryInvoke(instance, method, arguments);
  return value;
}
 
Example #29
Source File: RSocketEncodingFacadeImpl.java    From alibaba-rsocket-broker with 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 #30
Source File: LanguageDetector.java    From jstarcraft-nlp with Apache License 2.0 5 votes vote down vote up
/**
 * @return null if there are no "features" in the text (just noise).
 */
@Nullable
private double[] detectBlock(CharSequence text) {
    if (text.length() <= shortTextAlgorithm) {
        Map<String, Integer> ngrams = ngramExtractor.extractCountedGrams(text);
        if (ngrams.isEmpty())
            return null;
        return detectBlockShortText(ngrams);
    } else {
        List<String> strings = ngramExtractor.extractGrams(text);
        if (strings.isEmpty())
            return null;
        return detectBlockLongText(strings);
    }
}