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

The following examples show how to use com.google.common.base.Strings#isNullOrEmpty() . 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: YarnService.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
private ImmutableMap.Builder<String, String> buildContainerStatusEventMetadata(ContainerStatus containerStatus) {
  ImmutableMap.Builder<String, String> eventMetadataBuilder = new ImmutableMap.Builder<>();
  eventMetadataBuilder.put(GobblinYarnMetricTagNames.CONTAINER_ID, containerStatus.getContainerId().toString());
  eventMetadataBuilder.put(GobblinYarnEventConstants.EventMetadata.CONTAINER_STATUS_CONTAINER_STATE,
      containerStatus.getState().toString());
  if (ContainerExitStatus.INVALID != containerStatus.getExitStatus()) {
    eventMetadataBuilder.put(GobblinYarnEventConstants.EventMetadata.CONTAINER_STATUS_EXIT_STATUS,
        containerStatus.getExitStatus() + "");
  }
  if (!Strings.isNullOrEmpty(containerStatus.getDiagnostics())) {
    eventMetadataBuilder.put(GobblinYarnEventConstants.EventMetadata.CONTAINER_STATUS_EXIT_DIAGNOSTICS,
        containerStatus.getDiagnostics());
  }

  return eventMetadataBuilder;
}
 
Example 2
Source File: Tester.java    From oxd with Apache License 2.0 6 votes vote down vote up
public static String getAuthorization() {
    Preconditions.checkNotNull(SETUP_CLIENT);
    if (Strings.isNullOrEmpty(AUTHORIZATION)) {
        final GetClientTokenParams params = new GetClientTokenParams();
        params.setOpHost(OP_HOST);
        params.setScope(Lists.newArrayList("openid"));
        params.setClientId(Tester.getSetupClient().getClientId());
        params.setClientSecret(Tester.getSetupClient().getClientSecret());

        GetClientTokenResponse resp = Tester.newClient(HOST).getClientToken(params);
        assertNotNull(resp);
        assertTrue(!Strings.isNullOrEmpty(resp.getAccessToken()));

        AUTHORIZATION = "Bearer " + resp.getAccessToken();
    }
    return AUTHORIZATION;
}
 
Example 3
Source File: RedisConnectorConfig.java    From kafka-connect-redis with Apache License 2.0 6 votes vote down vote up
public List<RedisURI> redisURIs() {
  List<RedisURI> result = new ArrayList<>();

  for (HostAndPort host : this.hosts) {
    RedisURI.Builder builder = RedisURI.builder();
    builder.withHost(host.getHost());
    builder.withPort(host.getPort());
    builder.withDatabase(this.database);
    if (!Strings.isNullOrEmpty(this.password)) {
      builder.withPassword(this.password);
    }
    builder.withSsl(this.sslEnabled);
    result.add(builder.build());
  }

  return result;
}
 
Example 4
Source File: PathUtils.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Normalizes the given path eliminating repeated forward slashes.
 *
 * @return  normalized path
 */
public static final String normalize(final String path) {
  if (Strings.isNullOrEmpty(Preconditions.checkNotNull(path))) {
    return path;
  }

  final StringBuilder builder = new StringBuilder();
  char last = path.charAt(0);
  builder.append(last);
  for (int i=1; i<path.length(); i++) {
    char cur = path.charAt(i);
    if (last == '/' && cur == last) {
      continue;
    }
    builder.append(cur);
    last = cur;
  }
  return builder.toString();
}
 
Example 5
Source File: StreamResultsCommand.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    final StringBuilder parameters = new StringBuilder();
    parameters.append(super.toString());

    if (!Strings.isNullOrEmpty(queryId)) {
        parameters.append("\tQuery ID: " + queryId);
        parameters.append("\n");
    }

    return parameters.toString();
}
 
Example 6
Source File: SingularityExecutorTaskProcessBuilder.java    From Singularity with Apache License 2.0 5 votes vote down vote up
private String getCommand(ExecutorData executorData) {
  final StringBuilder bldr = new StringBuilder(
    Strings.isNullOrEmpty(executorData.getCmd()) ? "" : executorData.getCmd()
  );
  for (String extraCmdLineArg : executorData.getExtraCmdLineArgs()) {
    bldr.append(" ");
    bldr.append(extraCmdLineArg);
  }
  return bldr.toString();
}
 
Example 7
Source File: AuthorizationValidator.java    From nakadi with MIT License 5 votes vote down vote up
private void checkAuthAttributesNoDuplicates(final Map<String, List<AuthorizationAttribute>> allAttributes)
        throws UnableProcessException {
    final String duplicatesErrMessage = allAttributes.entrySet().stream()
            .map(entry -> {
                final String property = entry.getKey();
                final List<AuthorizationAttribute> attrs = entry.getValue();

                final List<AuthorizationAttribute> duplicates = newArrayList(attrs);
                final Set<AuthorizationAttribute> uniqueAttrs = newHashSet(attrs);
                uniqueAttrs.forEach(duplicates::remove);

                if (!duplicates.isEmpty()) {
                    final String duplicatesStr = duplicates.stream()
                            .distinct()
                            .map(attr -> String.format("%s:%s", attr.getDataType(), attr.getValue()))
                            .collect(Collectors.joining(", "));
                    final String err = String.format(
                            "authorization property '%s' contains duplicated attribute(s): %s",
                            property, duplicatesStr);
                    return Optional.of(err);
                } else {
                    return Optional.<String>empty();
                }
            })
            .filter(Optional::isPresent)
            .map(Optional::get)
            .collect(Collectors.joining("; "));

    if (!Strings.isNullOrEmpty(duplicatesErrMessage)) {
        throw new UnableProcessException(duplicatesErrMessage);
    }
}
 
Example 8
Source File: FirebaseProjectManagementServiceImpl.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private String pollOperation(String projectId, String operationName)
    throws FirebaseProjectManagementException {
  String url = String.format("%s/v1/%s", FIREBASE_PROJECT_MANAGEMENT_URL, operationName);
  for (int currentAttempt = 0; currentAttempt < MAXIMUM_POLLING_ATTEMPTS; currentAttempt++) {
    long delayMillis = (long) (
        POLL_BASE_WAIT_TIME_MILLIS
            * Math.pow(POLL_EXPONENTIAL_BACKOFF_FACTOR, currentAttempt));
    sleepOrThrow(projectId, delayMillis);
    OperationResponse operationResponseInstance = new OperationResponse();
    httpHelper.makeGetRequest(url, operationResponseInstance, projectId, "Project ID");
    if (!operationResponseInstance.done) {
      continue;
    }
    // The Long Running Operation API guarantees that when done == true, exactly one of 'response'
    // or 'error' is set.
    if (operationResponseInstance.response == null
        || Strings.isNullOrEmpty(operationResponseInstance.response.appId)) {
      throw HttpHelper.createFirebaseProjectManagementException(
          projectId,
          "Project ID",
          "Unable to create App: internal server error.",
          /* cause= */ null);
    }
    return operationResponseInstance.response.appId;
  }
  throw HttpHelper.createFirebaseProjectManagementException(
      projectId,
      "Project ID",
      "Unable to create App: deadline exceeded.",
      /* cause= */ null);
}
 
Example 9
Source File: PhysicalPlanLoader.java    From PoseidonX with Apache License 2.0 5 votes vote down vote up
public static void unRegisterPhysicalPlanAlias(String alias)
{
    if (Strings.isNullOrEmpty(alias))
    {
        LOG.warn("Unable to unRegister alias to physic plan. alias is null.");
        return;
    }

    LOG.info("unRegister alias to physic plan.");
    if (ALIAS_MAPPING.containsKey(alias))
    {
        ALIAS_MAPPING.remove(alias);
    }
}
 
Example 10
Source File: AbstractJavaCodegen.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
private static String sanitizePackageName(String packageName) {
    packageName = packageName.trim(); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
    packageName = packageName.replaceAll("[^a-zA-Z0-9_\\.]", "_");
    if (Strings.isNullOrEmpty(packageName)) {
        return "invalidPackageName";
    }
    return packageName;
}
 
Example 11
Source File: UserUpdater.java    From osiam with MIT License 5 votes vote down vote up
private void updateDisplayName(User user, UserEntity userEntity, Set<String> attributes) {
    if (attributes.contains("displayName")) {
        userEntity.setDisplayName(null);
    }

    if (!Strings.isNullOrEmpty(user.getDisplayName())) {
        userEntity.setDisplayName(user.getDisplayName());
    }
}
 
Example 12
Source File: FriendNotesPlugin.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
@Subscribe
private void onMenuOptionClicked(MenuOptionClicked event)
{
	if (WidgetInfo.TO_GROUP(event.getParam1()) == WidgetInfo.FRIENDS_LIST.getGroupId())
	{
		if (Strings.isNullOrEmpty(event.getTarget()))
		{
			return;
		}

		// Handle clicks on "Add Note" or "Edit Note"
		if (event.getOption().equals(ADD_NOTE) || event.getOption().equals(EDIT_NOTE))
		{
			event.consume();

			//Friends have color tags
			final String sanitizedTarget = Text.toJagexName(Text.removeTags(event.getTarget()));
			final String note = getFriendNote(sanitizedTarget);

			// Open the new chatbox input dialog
			chatboxPanelManager.openTextInput(String.format(NOTE_PROMPT_FORMAT, sanitizedTarget, CHARACTER_LIMIT))
				.value(Strings.nullToEmpty(note))
				.onDone((content) ->
				{
					if (content == null)
					{
						return;
					}

					content = Text.removeTags(content).trim();
					log.debug("Set note for '{}': '{}'", sanitizedTarget, content);
					setFriendNote(sanitizedTarget, content);
				}).build();
		}
	}

}
 
Example 13
Source File: PeerConnClient.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Modify bandwith for the specified peer conn.
 *
 * @param request The request containing all options for releasing the peer conn;
 */
public void modifyBandwith(ModifyBandwidthRequest request) {
    checkNotNull(request, "request should not be null.");
    if (Strings.isNullOrEmpty(request.getClientToken())) {
        request.setClientToken(this.generateClientToken());
    }
    InternalRequest internalRequest = this.createRequest(
            request, HttpMethodName.PUT, PREFIX, request.getPeerConnId());
    internalRequest.addParameter("resize", null);
    internalRequest.addParameter("clientToken", request.getClientToken());
    fillPayload(internalRequest, request);
    this.invokeHttpClient(internalRequest, AbstractBceResponse.class);
}
 
Example 14
Source File: EipGroupClient.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Resize the bandwidth.
 *
 * @param request The request containing all options for binding the eips to specified eip group.
 */
public void resizeBandwidth(BandwidthInMbpsRequest request) {
    checkNotNull(request, "request should not be null.");
    if (Strings.isNullOrEmpty(request.getClientToken())) {
        request.setClientToken(this.generateClientToken());
    }
    InternalRequest internalRequest = this.createRequest(
            request, HttpMethodName.PUT, PREFIX, request.getId());
    internalRequest.addParameter("resize", null);
    internalRequest.addParameter("clientToken", request.getClientToken());
    fillPayload(internalRequest, request);
    this.invokeHttpClient(internalRequest, AbstractBceResponse.class);
}
 
Example 15
Source File: DynamicAttributesPanelLoader.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected void loadDataContainer(DynamicAttributesPanel resultComponent, Element element) {
    String containerId = element.attributeValue("dataContainer");
    if (Strings.isNullOrEmpty(containerId)) {
        throw new GuiDevelopmentException("DynamicAttributesPanel element doesn't have 'dataContainer' attribute",
                context, "DynamicAttributesPanel ID", element.attributeValue("id"));
    }
    FrameOwner frameOwner = getComponentContext().getFrame().getFrameOwner();
    ScreenData screenData = UiControllerUtils.getScreenData(frameOwner);
    InstanceContainer container = screenData.getContainer(containerId);
    //noinspection unchecked
    resultComponent.setInstanceContainer(container);
}
 
Example 16
Source File: UriTemplateServerProxyTransformer.java    From codenvy with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public ServerImpl transform(ServerImpl server) {
  final String serverAddress = server.getAddress();
  final int colonIndex = serverAddress.indexOf(':');
  final String serverHost = serverAddress.substring(0, colonIndex);
  final String serverPort = serverAddress.substring(colonIndex + 1);
  String serverPath = "";
  if (server.getProperties() != null && server.getProperties().getPath() != null) {
    serverPath = server.getProperties().getPath();
  }
  if (serverPath.startsWith("/")) {
    serverPath = serverPath.substring(1);
  }

  // In case of external address property set, we should replace codenvy.host by this external
  // address.
  // for example on macOS, codenvy.host is defaulted to 192.168.65.2 which is not reachable from
  // host machine while
  // it needs to use localhost (external address).
  final String externalAddress;
  if (!Strings.isNullOrEmpty(cheDockerIpExternal)) {
    externalAddress = cheDockerIpExternal;
  } else {
    externalAddress = codenvyHost;
  }

  try {
    // external URI/address will be used by the browser clients (redirect calls through
    // externalAddress or codenvyHost if not set)
    URI serverUriExternal =
        new URI(
            format(
                serverUrlTemplate,
                server.getRef(),
                serverHost,
                serverPort,
                serverPath,
                externalAddress));
    String updatedExternalServerAddress =
        serverUriExternal.getHost()
            + (serverUriExternal.getPort() == -1 ? "" : ":" + serverUriExternal.getPort());

    // internal URI/address will be used by workspace agents internals (we redirect calls to
    // codenvyHost)
    URI serverUriInternal =
        new URI(
            format(
                serverUrlTemplate,
                server.getRef(),
                serverHost,
                serverPort,
                serverPath,
                codenvyHost));
    String updatedInternalServerAddress =
        serverUriInternal.getHost()
            + (serverUriInternal.getPort() == -1 ? "" : ":" + serverUriInternal.getPort());

    // return a new updated server object with correct external and internal addresses.
    return new ServerImpl(
        server.getRef(),
        serverUriExternal.getScheme(),
        updatedExternalServerAddress,
        serverUriExternal.toString(),
        new ServerPropertiesImpl(
            serverUriExternal.getPath(),
            updatedInternalServerAddress,
            serverUriInternal.toString()));
  } catch (URISyntaxException e) {
    LOG.error(
        format(
            "Server uri created from template taken from configuration is invalid. Template:%s. Origin server:%s",
            serverUrlTemplate, server),
        e);
    return server;
  }
}
 
Example 17
Source File: RegisterResponseMapper.java    From oxd with Apache License 2.0 4 votes vote down vote up
public static boolean isJsonStringEqual(String oxdParam, String oxAuthparam) throws IOException {
    return Strings.isNullOrEmpty(oxdParam) ? Strings.isNullOrEmpty(oxAuthparam) : Jackson2.createJsonMapperWithoutEmptyAttributes().readTree(oxdParam).equals(Jackson2.createJsonMapperWithoutEmptyAttributes().readTree(oxAuthparam));
}
 
Example 18
Source File: AuthInterceptor.java    From pravega with Apache License 2.0 4 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {

    Context context = Context.current();

    // The authorization header has the credentials (e.g., username and password for Basic Authentication).
    // The form of the header is: <Method> <Token> (CustomMethod static-token, or Basic XYZ...., for example)
    String credentials = headers.get(Metadata.Key.of(AuthConstants.AUTHORIZATION, Metadata.ASCII_STRING_MARSHALLER));

    if (!Strings.isNullOrEmpty(credentials)) {
        String[] parts = credentials.split("\\s+", 2);
        if (parts.length == 2) {
            String method = parts[0];
            String token = parts[1];
            if (!Strings.isNullOrEmpty(method)) {
                if (method.equals(handler.getHandlerName())) {
                    log.debug("Handler [{}] successfully matched auth method [{}]", handler, method);
                    Principal principal;
                    try {
                        if ((principal = handler.authenticate(token)) == null) {
                            log.warn("Handler for method [{}] returned a null Principal upon authentication for the"
                                    + "given token", method);
                            call.close(Status.fromCode(Status.Code.UNAUTHENTICATED), headers);
                            return null;
                        }
                    } catch (AuthException e) {
                        log.warn("Authentication failed", e);
                        call.close(Status.fromCode(Status.Code.UNAUTHENTICATED), headers);
                        return null;
                    }
                    // Creates a new Context with the given key/value pairs.
                    context = context.withValues(PRINCIPAL_OBJECT_KEY, principal, AUTH_INTERCEPTOR_OBJECT_KEY, this);
                }
            } else {
                log.debug("Credentials are present, but method [{}] is null or empty", method);
            }
        }
    }

    // reaching this point means that the handler wasn't applicable to this request.
    return Contexts.interceptCall(context, call, headers, next);
}
 
Example 19
Source File: BinanceOrderPlacement.java    From java-binance-api with MIT License 4 votes vote down vote up
public String getAsQuery() throws BinanceApiException {
    StringBuffer sb = new StringBuffer();
    Escaper esc = UrlEscapers.urlFormParameterEscaper();
    if (symbol == null) {
        throw new BinanceApiException("Order Symbol is not set");
    }
    sb.append("&symbol=").append(symbol.toString());
    if (side == null) {
        throw new BinanceApiException("Order side is not set");
    }
    sb.append("&side=").append(side.toString());
    if (type == null) {
        throw new BinanceApiException("Order type is not set");
    }
    sb.append("&type=").append(type.toString());
    if (quantity == null || quantity.compareTo(BigDecimal.ZERO) <= 0) {
        throw new BinanceApiException("Order quantity should be bigger than zero");
    }
    sb.append("&quantity=").append(quantity.toString());

    if (type == BinanceOrderType.MARKET) {
        // price should be skipped for a market order, we are accepting market price
        // so should timeInForce
    } else {
        if (timeInForce == null) {
            throw new BinanceApiException("Order timeInForce is not set");
        }
        sb.append("&timeInForce=").append(timeInForce.toString());
        if (price == null || price.compareTo(BigDecimal.ZERO) <= 0) {
            throw new BinanceApiException("Order price should be bigger than zero");
        }
        sb.append("&price=").append(price.toString());
    }

    if (!Strings.isNullOrEmpty(newClientOrderId)) {
        sb.append("&newClientOrderId=").append(esc.escape(newClientOrderId));
    }
    if (stopPrice != null) {
        sb.append("&stopPrice=").append(stopPrice.toString());
    }
    if (icebergQty != null) {
        sb.append("&icebergQty=").append(icebergQty.toString());
    }
    return sb.toString().substring(1); // skipping the first &
}
 
Example 20
Source File: XmlHelper.java    From oodt with Apache License 2.0 4 votes vote down vote up
public static List<String> getMetadataValues(Element elem, Metadata metadata)
	throws PGEException {
	List<String> values = Lists.newArrayList();

	// Read val attr.
	String value = elem.getAttribute(VAL_ATTR);

	// Check if val tag was not specified see if value was given as element
	// text.
	if (Strings.isNullOrEmpty(value)) {
		value = elem.getTextContent();
	}

	// If value was found.
	if (!Strings.isNullOrEmpty(value)) {

		// Is multi-value so split up value.
		if (isMultiValue(elem, metadata)) {
			for (String v : Splitter.on(",").split(value)) {

				// Check for envReplace and perform met replacement on value
				// if set.
				if (isEnvReplaceNoRecur(elem, metadata)) {
					values.add(fillIn(v, metadata, false));
				} else if (isEnvReplace(elem, metadata)) {
					values.add(fillIn(v, metadata));
				}
			}

			// Is scalar
		} else {

			// Check for envReplace and perform met replacement on value if
			// set.
			if (isEnvReplaceNoRecur(elem, metadata)) {
				value = fillIn(value, metadata, false);
			} else if (isEnvReplace(elem, metadata)) {
				value = fillIn(value, metadata);
			}
			values.add(value);
		}

	}
	return values;
}