Java Code Examples for com.google.common.base.Strings#emptyToNull()

The following examples show how to use com.google.common.base.Strings#emptyToNull() . 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: FirebaseProjectManagementServiceImpl.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
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);
    }
  };
}
 
Example 2
Source File: ResolvablePropertiesDialog.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@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();
}
 
Example 3
Source File: AggregateDaoImpl.java    From glowroot with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example 4
Source File: AsyncQueryMethodExtension.java    From guice-persist-orient with MIT License 6 votes vote down vote up
@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;
}
 
Example 5
Source File: InternalConfigurationEditor.java    From eclipse-cs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * {@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;
}
 
Example 6
Source File: ModelEditUtils.java    From zhcet-web with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 7
Source File: AbstractUnleashMojo.java    From unleash-maven-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example 8
Source File: TreatmentData.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@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);
}
 
Example 9
Source File: AWSEC2ComputeServiceDependenciesModule.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 10
Source File: IndexTypeExtension.java    From guice-persist-orient with MIT License 5 votes vote down vote up
@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);
}
 
Example 11
Source File: GatewayEditTextPreference.java    From openwebnet-android with MIT License 5 votes vote down vote up
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();
        });
}
 
Example 12
Source File: CentralDogmaBeanConfigBuilder.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
}
 
Example 13
Source File: AbstractLithiumDataInput.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: AnnotatedGroupDefinitionBuilder.java    From cuba with Apache License 2.0 5 votes vote down vote up
@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()));
    }
}
 
Example 15
Source File: CustomAuthenticationDetails.java    From zhcet-web with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 16
Source File: StringUtils.java    From zhcet-web with Apache License 2.0 4 votes vote down vote up
@Nullable
public static String capitalizeFirst(String string) {
    if (string == null) return null;
    return Strings.emptyToNull(WordUtils.capitalizeFully(string.trim()));
}
 
Example 17
Source File: IdXmlResourceValue.java    From bazel with Apache License 2.0 4 votes vote down vote up
public static IdXmlResourceValue from(Value proto, Visibility visibility) {
  String ref = proto.getItem().getRef().getName();
  return new IdXmlResourceValue(visibility, Strings.emptyToNull(ref));
}
 
Example 18
Source File: ArmeriaServerCall.java    From armeria with Apache License 2.0 4 votes vote down vote up
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());
}
 
Example 19
Source File: Ideas_2012_01_13.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@ExpectWarning("DMI_DOH")
public String testEmptyToNull() {
    return Strings.emptyToNull("uid");
}
 
Example 20
Source File: PathUtils.java    From dropwizard-guicey with MIT License 3 votes vote down vote up
/**
 * 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));
}