com.google.common.base.Strings#emptyToNull ( )源码实例Demo

下面列出了com.google.common.base.Strings#emptyToNull ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@MojoProduces
@Named("releaseEnvVariables")
private Map<String, String> getReleaseEnvironmentVariables() {
  Map<String, String> env = Maps.newHashMap();
  if (!Strings.isNullOrEmpty(this.releaseEnvironmentVariables)) {
    Iterable<String> split = Splitter.on(',').split(this.releaseEnvironmentVariables);
    for (String token : split) {
      String date = Strings.emptyToNull(token.trim());
      if (date != null) {
        List<String> dataSplit = Splitter.on("=>").splitToList(date);
        String key = dataSplit.get(0);
        String value = dataSplit.get(1);
        env.put(key, value);
      }
    }
  }
  return env;
}
 
源代码2 项目: eclipse-cs   文件: ResolvablePropertiesDialog.java
/**
 * {@inheritDoc}
 */
@Override
protected void okPressed() {

  // check for properties without value - these must be fixed before
  // OK'ing
  for (ResolvableProperty prop : mResolvableProperties) {

    if (Strings.emptyToNull(prop.getValue()) == null) {
      this.setErrorMessage(NLS.bind(Messages.ResolvablePropertiesDialog_msgMissingPropertyValue,
              prop.getPropertyName()));
      return;
    }
  }

  mCheckConfig.getResolvableProperties().clear();
  mCheckConfig.getResolvableProperties().addAll(mResolvableProperties);
  super.okPressed();
}
 
源代码3 项目: glowroot   文件: AggregateDaoImpl.java
private ListenableFuture<?> rollupQueriesFromRows(RollupParams rollup, AggregateQuery query,
        Iterable<Row> rows) throws Exception {
    QueryCollector collector =
            new QueryCollector(rollup.maxQueryAggregatesPerTransactionAggregate());
    for (Row row : rows) {
        int i = 0;
        String queryType = checkNotNull(row.getString(i++));
        String truncatedText = checkNotNull(row.getString(i++));
        // full_query_text_sha1 cannot be null since it is used in clustering key
        String fullTextSha1 = Strings.emptyToNull(row.getString(i++));
        double totalDurationNanos = row.getDouble(i++);
        long executionCount = row.getLong(i++);
        boolean hasTotalRows = !row.isNull(i);
        long totalRows = row.getLong(i++);
        collector.mergeQuery(queryType, truncatedText, fullTextSha1, totalDurationNanos,
                executionCount, hasTotalRows, totalRows);
    }
    return insertQueries(collector.getSortedAndTruncatedQueries(), rollup.rollupLevel(),
            rollup.agentRollupId(), query.transactionType(), query.transactionName(),
            query.to(), rollup.adjustedTTL());
}
 
源代码4 项目: eclipse-cs   文件: InternalConfigurationEditor.java
/**
 * {@inheritDoc}
 */
@Override
public CheckConfigurationWorkingCopy getEditedWorkingCopy() throws CheckstylePluginException {
  mWorkingCopy.setName(mConfigName.getText());

  if (mWorkingCopy.getLocation() == null) {

    String location = "internal_config_" + System.currentTimeMillis() + ".xml"; //$NON-NLS-1$ //$NON-NLS-2$
    try {
      mWorkingCopy.setLocation(location);
    } catch (CheckstylePluginException e) {
      if (Strings.emptyToNull(location) != null && ensureFileExists(location)) {
        mWorkingCopy.setLocation(location);
      } else {
        throw e;
      }
    }
  }
  mWorkingCopy.setDescription(mDescription.getText());

  return mWorkingCopy;
}
 
@Override
public CommandMethodDescriptor createDescriptor(final DescriptorContext context, final AsyncQuery annotation) {
    final CommandMethodDescriptor descriptor = new CommandMethodDescriptor();
    descriptor.command = Strings.emptyToNull(annotation.value());
    final boolean blocking = annotation.blocking();
    descriptor.extDescriptors.put(EXT_BLOCKING, blocking);
    checkReturnType(context.method.getReturnType(), blocking);

    analyzeElVars(descriptor, context);
    analyzeParameters(descriptor, context);

    check(descriptor.extDescriptors.get(ListenParamExtension.KEY) != null,
            "Required @%s parameter of type %s or %s not defined", Listen.class.getSimpleName(),
            OCommandResultListener.class.getSimpleName(), AsyncQueryListener.class.getSimpleName());
    return descriptor;
}
 
private CallableOperation<AndroidAppMetadata, FirebaseProjectManagementException> getAndroidAppOp(
    final String appId) {
  return new CallableOperation<AndroidAppMetadata, FirebaseProjectManagementException>() {
    @Override
    protected AndroidAppMetadata execute() throws FirebaseProjectManagementException {
      String url = String.format(
          "%s/v1beta1/projects/-/androidApps/%s", FIREBASE_PROJECT_MANAGEMENT_URL, appId);
      AndroidAppResponse parsedResponse = new AndroidAppResponse();
      httpHelper.makeGetRequest(url, parsedResponse, appId, "App ID");
      return new AndroidAppMetadata(
          parsedResponse.name,
          parsedResponse.appId,
          Strings.emptyToNull(parsedResponse.displayName),
          parsedResponse.projectId,
          parsedResponse.packageName);
    }
  };
}
 
源代码7 项目: zhcet-web   文件: ModelEditUtils.java
/**
 * Checks user with duplicate or valid email and throws appropriate exceptions
 * Returns email to be set on user after sanitizing it
 * @param userSupplier Provides user to be saved
 * @param newEmail Provides new email to be set
 * @param duplicateChecker Checks if any other user with same email exists
 * @return Email to be set
 */
public static String verifyNewEmail(
        Supplier<User> userSupplier,
        Supplier<String> newEmail,
        BiPredicate<User, String> duplicateChecker) {
    User user = userSupplier.get();

    // Sanitize the email from user input
    String email = Strings.emptyToNull(newEmail.get().trim().toLowerCase());
    String previousEmail = user.getEmail();

    // Update email address if not null and changed
    if (email != null && !email.equals(previousEmail)) {
        if (!Utils.isValidEmail(email))
            throw new InvalidEmailException(email);
        if (duplicateChecker.test(user, email))
            throw new DuplicateException("User", "email", email);

        // New email means we should remove the flag denoting the email
        // has been verified
        user.setEmailVerified(false);
    }

    return email;
}
 
源代码8 项目: cuba   文件: AnnotatedGroupDefinitionBuilder.java
@Override
public void processAnnotation(ConstraintsAnnotationContext context) {
    JpqlConstraint constraint = (JpqlConstraint) context.getAnnotation();
    Class<? extends Entity> targetClass = !Entity.class.equals(constraint.target()) ? constraint.target() : resolveTargetClass(context.getMethod());
    if (!Entity.class.equals(targetClass)) {
        String where = Strings.emptyToNull(constraint.value());
        if (where == null) {
            where = Strings.emptyToNull(constraint.where());
        }
        context.getConstraintsBuilder().withJpql(targetClass, where, Strings.emptyToNull(constraint.join()));
    }
}
 
源代码9 项目: yangtools   文件: AbstractLithiumDataInput.java
final QName defaultReadQName() throws IOException {
    // Read in the same sequence of writing
    String localName = readCodedString();
    String namespace = readCodedString();
    String revision = Strings.emptyToNull(readCodedString());

    return QNameFactory.create(localName, namespace, revision);
}
 
/**
 * Creates a new builder from the properties of a {@link CentralDogmaBean} annotation.
 */
public CentralDogmaBeanConfigBuilder(CentralDogmaBean config) {
    project = Strings.emptyToNull(config.project());
    repository = Strings.emptyToNull(config.repository());
    path = Strings.emptyToNull(config.path());
    jsonPath = Strings.emptyToNull(config.jsonPath());
}
 
private void addGateway(Dialog dialog) {
    String host = utilityService.sanitizedText(mEditTextHost);
    Integer port = Integer.parseInt(utilityService.sanitizedText(mEditTextPort));
    String password = Strings.emptyToNull(utilityService.sanitizedText(mEditTextPassword));

    gatewayService.add(GatewayModel.newGateway(host, port, password))
        .subscribe(uuid -> {
            log.debug("NEW gateway: {}", uuid);
            dialog.dismiss();
        });
}
 
源代码12 项目: guice-persist-orient   文件: IndexTypeExtension.java
@Override
public void afterRegistration(final ODatabaseObject db, final SchemeDescriptor descriptor,
                              final CompositeIndex annotation) {
    // single field index definition intentionally allowed (no check)
    final String name = Strings.emptyToNull(annotation.name().trim());
    Preconditions.checkArgument(name != null, "Index name required");
    final String model = descriptor.schemeClass;
    final OClass clazz = db.getMetadata().getSchema().getClass(model);
    final OIndex<?> classIndex = clazz.getClassIndex(name);
    final OClass.INDEX_TYPE type = annotation.type();
    final String[] fields = annotation.fields();
    if (!descriptor.initialRegistration && classIndex != null) {
        final IndexValidationSupport support = new IndexValidationSupport(classIndex, logger);

        support.checkFieldsCompatible(fields);

        final boolean correct = support
                .isIndexSigns(classIndex.getDefinition().isNullValuesIgnored())
                .matchRequiredSigns(type, annotation.ignoreNullValues());
        if (!correct) {
            support.dropIndex(db);
        } else {
            // index ok
            return;
        }
    }
    final ODocument metadata = new ODocument()
            .field("ignoreNullValues", annotation.ignoreNullValues());
    clazz.createIndex(name, type.name(), null, metadata, fields);
    logger.info("Index '{}' ({} [{}]) {} created", name, model, Joiner.on(',').join(fields), type);
}
 
@Provides
@Singleton
@ImageQuery
protected Map<String, String> imageQuery(ValueOfConfigurationKeyOrNull config) {
   String amiQuery = Strings.emptyToNull(config.apply(PROPERTY_EC2_AMI_QUERY));
   String owners = config.apply(PROPERTY_EC2_AMI_OWNERS);
   if ("".equals(owners)) {
      amiQuery = null;
   } else if (owners != null) {
      StringBuilder query = new StringBuilder();
      if ("*".equals(owners))
         query.append("state=available;image-type=machine");
      else
         query.append("owner-id=").append(owners).append(";state=available;image-type=machine");
      Logger.getAnonymousLogger().warning(
            String.format("Property %s is deprecated, please use new syntax: %s=%s", PROPERTY_EC2_AMI_OWNERS,
                  PROPERTY_EC2_AMI_QUERY, query.toString()));
      amiQuery = query.toString();
   }
   Builder<String, String> builder = ImmutableMap.<String, String> builder();
   if (amiQuery != null)
      builder.put(PROPERTY_EC2_AMI_QUERY, amiQuery);
   String ccQuery = Strings.emptyToNull(config.apply(PROPERTY_EC2_CC_AMI_QUERY));
   if (ccQuery != null)
      builder.put(PROPERTY_EC2_CC_AMI_QUERY, ccQuery);
   return builder.build();
}
 
源代码14 项目: hmftools   文件: TreatmentData.java
@Nullable
@Value.Derived
default String concatenatedMechanism() {
    List<CuratedDrug> drugs = sortedDrugs();

    String value = drugs.stream().map(CuratedDrug::mechanism).collect(Collectors.joining(SEPARATOR));
    return Strings.emptyToNull(value);
}
 
源代码15 项目: zhcet-web   文件: CustomAuthenticationDetails.java
public CustomAuthenticationDetails(HttpServletRequest request) {
    super(request);
    this.remoteAddress = Utils.getClientIP(request);
    String totpCode = request.getParameter("totp");

    if (totpCode != null) {
        totpCode = Strings.emptyToNull(totpCode.replace(" ", ""));
    }
    this.totpCode = totpCode;
}
 
源代码16 项目: spotbugs   文件: Ideas_2012_01_13.java
@ExpectWarning("DMI_DOH")
public String testEmptyToNull() {
    return Strings.emptyToNull("uid");
}
 
源代码17 项目: armeria   文件: ArmeriaServerCall.java
ArmeriaServerCall(HttpHeaders clientHeaders,
                  MethodDescriptor<I, O> method,
                  CompressorRegistry compressorRegistry,
                  DecompressorRegistry decompressorRegistry,
                  HttpResponseWriter res,
                  int maxInboundMessageSizeBytes,
                  int maxOutboundMessageSizeBytes,
                  ServiceRequestContext ctx,
                  SerializationFormat serializationFormat,
                  @Nullable GrpcJsonMarshaller jsonMarshaller,
                  boolean unsafeWrapRequestBuffers,
                  boolean useBlockingTaskExecutor,
                  ResponseHeaders defaultHeaders) {
    requireNonNull(clientHeaders, "clientHeaders");
    this.method = requireNonNull(method, "method");
    this.ctx = requireNonNull(ctx, "ctx");
    this.serializationFormat = requireNonNull(serializationFormat, "serializationFormat");
    this.defaultHeaders = requireNonNull(defaultHeaders, "defaultHeaders");
    messageReader = new HttpStreamReader(
            requireNonNull(decompressorRegistry, "decompressorRegistry"),
            new ArmeriaMessageDeframer(
                    this,
                    maxInboundMessageSizeBytes,
                    ctx.alloc())
                    .decompressor(clientDecompressor(clientHeaders, decompressorRegistry)),
            this);
    messageFramer = new ArmeriaMessageFramer(ctx.alloc(), maxOutboundMessageSizeBytes);
    this.res = requireNonNull(res, "res");
    this.compressorRegistry = requireNonNull(compressorRegistry, "compressorRegistry");
    clientAcceptEncoding =
            Strings.emptyToNull(clientHeaders.get(GrpcHeaderNames.GRPC_ACCEPT_ENCODING));
    marshaller = new GrpcMessageMarshaller<>(ctx.alloc(), serializationFormat, method, jsonMarshaller,
                                             unsafeWrapRequestBuffers);
    this.unsafeWrapRequestBuffers = unsafeWrapRequestBuffers;
    blockingExecutor = useBlockingTaskExecutor ?
                       MoreExecutors.newSequentialExecutor(ctx.blockingTaskExecutor()) : null;

    res.whenComplete().handleAsync((unused, t) -> {
        if (!closeCalled) {
            // Closed by client, not by server.
            cancelled = true;
            try (SafeCloseable ignore = ctx.push()) {
                close(Status.CANCELLED, new Metadata());
            }
        }
        return null;
    }, ctx.eventLoop());
}
 
源代码18 项目: bazel   文件: IdXmlResourceValue.java
public static IdXmlResourceValue from(Value proto, Visibility visibility) {
  String ref = proto.getItem().getRef().getName();
  return new IdXmlResourceValue(visibility, Strings.emptyToNull(ref));
}
 
源代码19 项目: zhcet-web   文件: StringUtils.java
@Nullable
public static String capitalizeFirst(String string) {
    if (string == null) return null;
    return Strings.emptyToNull(WordUtils.capitalizeFully(string.trim()));
}
 
源代码20 项目: dropwizard-guicey   文件: PathUtils.java
/**
 * Combine parts into correct path avoiding duplicate slashes and replacing backward slashes. Null and empty
 * parts are ignored. No leading or trailing slash appended.
 * <p>
 * May contain base url as first part, e.g. "http://localhost/" and double slash there would not be replaced.
 *
 * @param parts path parts
 * @return combined path from supplied parts
 */
public static String path(final String... parts) {
    for (int i = 0; i < parts.length; i++) {
        // important because if first (or last) provided chank is "" then resulted path will unexpectedly
        // start / end with slash
        parts[i] = Strings.emptyToNull(parts[i]);
    }
    return normalize(Joiner.on(SLASH).skipNulls().join(parts));
}