List of usage examples for com.google.common.base Strings emptyToNull
@Nullable public static String emptyToNull(@Nullable String string)
From source file:org.dcache.alarms.server.LogEntryServerWrapper.java
public void setSmtpHost(String smtpHost) { this.smtpHost = Strings.emptyToNull(smtpHost); }
From source file:org.apache.ambari.server.controller.internal.ProvisionClusterRequest.java
private Map<String, Credential> parseCredentials(Map<String, Object> properties) throws InvalidTopologyTemplateException { HashMap<String, Credential> credentialHashMap = new HashMap<>(); Set<Map<String, String>> credentialsSet = (Set<Map<String, String>>) properties .get(ClusterResourceProvider.CREDENTIALS_PROPERTY_ID); if (credentialsSet != null) { for (Map<String, String> credentialMap : credentialsSet) { String alias = Strings.emptyToNull(credentialMap.get("alias")); if (alias == null) { throw new InvalidTopologyTemplateException("credential.alias property is missing."); }/* w w w . j a va2 s . c o m*/ String principal = Strings.emptyToNull(credentialMap.get("principal")); if (principal == null) { throw new InvalidTopologyTemplateException("credential.principal property is missing."); } String key = Strings.emptyToNull(credentialMap.get("key")); if (key == null) { throw new InvalidTopologyTemplateException("credential.key is missing."); } String typeString = Strings.emptyToNull(credentialMap.get("type")); if (typeString == null) { throw new InvalidTopologyTemplateException("credential.type is missing."); } CredentialStoreType type = Enums.getIfPresent(CredentialStoreType.class, typeString.toUpperCase()) .orNull(); if (type == null) { throw new InvalidTopologyTemplateException("credential.type is invalid."); } credentialHashMap.put(alias, new Credential(alias, principal, key, type)); } } return credentialHashMap; }
From source file:com.google.api.codegen.config.GapicMethodConfig.java
/** * Creates an instance of GapicMethodConfig based on MethodConfigProto, linking it up with the * provided method. On errors, null will be returned, and diagnostics are reported to the diag * collector./*from w ww . ja v a2s . co m*/ */ @Nullable static GapicMethodConfig createMethodConfig(DiagCollector diagCollector, TargetLanguage language, MethodConfigProto methodConfigProto, Method method, ResourceNameMessageConfigs messageConfigs, ImmutableMap<String, ResourceNameConfig> resourceNameConfigs, ImmutableSet<String> retryCodesConfigNames, ImmutableSet<String> retryParamsConfigNames) { boolean error = false; ProtoMethodModel methodModel = new ProtoMethodModel(method); PageStreamingConfig pageStreaming = null; if (!PageStreamingConfigProto.getDefaultInstance().equals(methodConfigProto.getPageStreaming())) { pageStreaming = PageStreamingConfig.createPageStreaming(diagCollector, messageConfigs, resourceNameConfigs, methodConfigProto, methodModel); if (pageStreaming == null) { error = true; } } GrpcStreamingConfig grpcStreaming = null; if (isGrpcStreamingMethod(methodModel)) { if (PageStreamingConfigProto.getDefaultInstance().equals(methodConfigProto.getGrpcStreaming())) { grpcStreaming = GrpcStreamingConfig.createGrpcStreaming(diagCollector, method); } else { grpcStreaming = GrpcStreamingConfig.createGrpcStreaming(diagCollector, methodConfigProto.getGrpcStreaming(), method); if (grpcStreaming == null) { error = true; } } } ImmutableList<FlatteningConfig> flattening = null; if (!FlatteningConfigProto.getDefaultInstance().equals(methodConfigProto.getFlattening())) { flattening = createFlattening(diagCollector, messageConfigs, resourceNameConfigs, methodConfigProto, methodModel); if (flattening == null) { error = true; } } BatchingConfig batching = null; if (!BatchingConfigProto.getDefaultInstance().equals(methodConfigProto.getBatching())) { batching = BatchingConfig.createBatching(diagCollector, methodConfigProto.getBatching(), methodModel); if (batching == null) { error = true; } } String retryCodesName = methodConfigProto.getRetryCodesName(); if (!retryCodesName.isEmpty() && !retryCodesConfigNames.contains(retryCodesName)) { diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL, "Retry codes config used but not defined: '%s' (in method %s)", retryCodesName, methodModel.getFullName())); error = true; } String retryParamsName = methodConfigProto.getRetryParamsName(); if (!retryParamsConfigNames.isEmpty() && !retryParamsConfigNames.contains(retryParamsName)) { diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL, "Retry parameters config used but not defined: %s (in method %s)", retryParamsName, methodModel.getFullName())); error = true; } Duration timeout = Duration.ofMillis(methodConfigProto.getTimeoutMillis()); if (timeout.toMillis() <= 0) { diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL, "Default timeout not found or has invalid value (in method %s)", methodModel.getFullName())); error = true; } boolean hasRequestObjectMethod = methodConfigProto.getRequestObjectMethod(); if (hasRequestObjectMethod && method.getRequestStreaming()) { diagCollector.addDiag(Diag.error(SimpleLocation.TOPLEVEL, "request_object_method incompatible with streaming method %s", method.getFullName())); error = true; } ImmutableMap<String, String> fieldNamePatterns = ImmutableMap .copyOf(methodConfigProto.getFieldNamePatterns()); ResourceNameTreatment defaultResourceNameTreatment = methodConfigProto.getResourceNameTreatment(); if (defaultResourceNameTreatment == null || defaultResourceNameTreatment.equals(ResourceNameTreatment.UNSET_TREATMENT)) { defaultResourceNameTreatment = ResourceNameTreatment.NONE; } Iterable<FieldConfig> requiredFieldConfigs = createFieldNameConfigs(diagCollector, messageConfigs, defaultResourceNameTreatment, fieldNamePatterns, resourceNameConfigs, getRequiredFields(diagCollector, methodModel, methodConfigProto.getRequiredFieldsList())); Iterable<FieldConfig> optionalFieldConfigs = createFieldNameConfigs(diagCollector, messageConfigs, defaultResourceNameTreatment, fieldNamePatterns, resourceNameConfigs, getOptionalFields(methodModel, methodConfigProto.getRequiredFieldsList())); List<String> sampleCodeInitFields = new ArrayList<>(); sampleCodeInitFields.addAll(methodConfigProto.getSampleCodeInitFieldsList()); SampleSpec sampleSpec = new SampleSpec(methodConfigProto); String rerouteToGrpcInterface = Strings.emptyToNull(methodConfigProto.getRerouteToGrpcInterface()); VisibilityConfig visibility = VisibilityConfig.PUBLIC; ReleaseLevel releaseLevel = ReleaseLevel.GA; for (SurfaceTreatmentProto treatment : methodConfigProto.getSurfaceTreatmentsList()) { if (!treatment.getIncludeLanguagesList().contains(language.toString().toLowerCase())) { continue; } if (treatment.getVisibility() != VisibilityProto.UNSET_VISIBILITY) { visibility = VisibilityConfig.fromProto(treatment.getVisibility()); } if (treatment.getReleaseLevel() != ReleaseLevel.UNSET_RELEASE_LEVEL) { releaseLevel = treatment.getReleaseLevel(); } } LongRunningConfig longRunningConfig = null; if (!LongRunningConfigProto.getDefaultInstance().equals(methodConfigProto.getLongRunning())) { longRunningConfig = LongRunningConfig.createLongRunningConfig(method.getModel(), diagCollector, methodConfigProto.getLongRunning()); if (longRunningConfig == null) { error = true; } } List<String> headerRequestParams = ImmutableList.copyOf(methodConfigProto.getHeaderRequestParamsList()); if (error) { return null; } else { return new AutoValue_GapicMethodConfig(methodModel, pageStreaming, grpcStreaming, flattening, retryCodesName, retryParamsName, timeout, requiredFieldConfigs, optionalFieldConfigs, defaultResourceNameTreatment, batching, hasRequestObjectMethod, fieldNamePatterns, sampleCodeInitFields, sampleSpec, rerouteToGrpcInterface, visibility, releaseLevel, longRunningConfig, headerRequestParams); } }
From source file:li.klass.fhem.ui.service.importExport.ImportExportUIService.java
public void selectPasswordWith(Activity activity, final OnBackupPasswordSelected passwordSelectedListener, int description) { @SuppressLint("InflateParams") final View layout = activity.getLayoutInflater().inflate(R.layout.import_export_password_dialog, null); ((TextView) layout.findViewById(R.id.description)).setText(description); new AlertDialog.Builder(activity).setView(layout).setCancelable(true) .setPositiveButton(R.string.okButton, new DialogInterface.OnClickListener() { @Override//from w w w .j a va 2 s .com public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); EditText editText = (EditText) layout.findViewById(R.id.password); passwordSelectedListener .backupPasswordSelected(Strings.emptyToNull(editText.getText().toString())); } }).show(); }
From source file:org.apache.jackrabbit.oak.security.user.UserInitializer.java
@Override public void initialize(NodeBuilder builder, String workspaceName) { // squeeze node state before it is passed to store (OAK-2411) NodeState base = ModifiedNodeState.squeeze(builder.getNodeState()); MemoryNodeStore store = new MemoryNodeStore(base); Root root = RootFactory.createSystemRoot(store, EmptyHook.INSTANCE, workspaceName, securityProvider, new QueryEngineSettings(), new CompositeQueryIndexProvider(new PropertyIndexProvider(), new NodeTypeIndexProvider())); UserConfiguration userConfiguration = securityProvider.getConfiguration(UserConfiguration.class); UserManager userManager = userConfiguration.getUserManager(root, NamePathMapper.DEFAULT); String errorMsg = "Failed to initialize user content."; try {//www .j a v a2 s .co m NodeUtil rootTree = checkNotNull(new NodeUtil(root.getTree("/"))); NodeUtil index = rootTree.getOrAddChild(IndexConstants.INDEX_DEFINITIONS_NAME, JcrConstants.NT_UNSTRUCTURED); if (!index.hasChild("authorizableId")) { NodeUtil authorizableId = IndexUtils.createIndexDefinition(index, "authorizableId", true, new String[] { REP_AUTHORIZABLE_ID }, new String[] { NT_REP_AUTHORIZABLE }); authorizableId.setString("info", "Oak index used by the user management " + "to enforce uniqueness of rep:authorizableId property values."); } if (!index.hasChild("principalName")) { NodeUtil principalName = IndexUtils.createIndexDefinition(index, "principalName", true, new String[] { REP_PRINCIPAL_NAME }, new String[] { NT_REP_AUTHORIZABLE }); principalName.setString("info", "Oak index used by the user management " + "to enforce uniqueness of rep:principalName property values, " + "and to quickly search a principal by name if it was constructed manually."); } if (!index.hasChild("repMembers")) { NodeUtil members = IndexUtils.createIndexDefinition(index, "repMembers", false, new String[] { REP_MEMBERS }, new String[] { NT_REP_MEMBER_REFERENCES }); members.setString("info", "Oak index used by the user management to lookup group membership."); } ConfigurationParameters params = userConfiguration.getParameters(); String adminId = params.getConfigValue(PARAM_ADMIN_ID, DEFAULT_ADMIN_ID); if (userManager.getAuthorizable(adminId) == null) { boolean omitPw = params.getConfigValue(PARAM_OMIT_ADMIN_PW, false); userManager.createUser(adminId, (omitPw) ? null : adminId); } String anonymousId = Strings .emptyToNull(params.getConfigValue(PARAM_ANONYMOUS_ID, DEFAULT_ANONYMOUS_ID, String.class)); if (anonymousId != null && userManager.getAuthorizable(anonymousId) == null) { userManager.createUser(anonymousId, null); } if (root.hasPendingChanges()) { root.commit(); } } catch (RepositoryException e) { log.error(errorMsg, e); throw new RuntimeException(e); } catch (CommitFailedException e) { log.error(errorMsg, e); throw new RuntimeException(e); } NodeState target = store.getRoot(); target.compareAgainstBaseState(base, new ApplyDiff(builder)); }
From source file:com.enonic.cms.core.portal.datasource.executor.DataSourceExecutorImpl.java
private void doExecuteDataSource(final DataSourceResultBuilder result, final DataSourceElement element, final DatasourceExecutionTrace trace) { final DataSourceRequestFactory factory = new DataSourceRequestFactory(this.expressionFunctionsExecutor, this.context); final DataSourceRequest request = factory.createRequest(element); final Document doc = doExecuteDataSource(request, trace); final String groupName = Strings.emptyToNull(element.getResultElement()); final Element resultElement = (Element) doc.getRootElement().clone(); result.addElementToGroup(groupName, resultElement); }
From source file:fathom.rest.route.CORSFilter.java
@Override public void handle(Context context) { // A valid CORS request *always* contains an Origin header // A same-origin request may or may not contain an Origin, it depends on the browser final String origin = Strings.emptyToNull(context.getHeader(HEADER_ORIGIN)); final String preflightMethod = Strings.emptyToNull(context.getHeader(HEADER_REQUEST_METHOD)); if (HttpMethod.OPTIONS.equals(context.getRequestMethod()) && preflightMethod != null) { // Preflight request Set<String> preflightHeaders = null; String headers = Strings.emptyToNull(context.getHeader(HEADER_REQUEST_HEADERS)); if (headers != null) { preflightHeaders = Util.splitToSet(headers.toLowerCase(), ","); preflightHeaders.remove("accept"); preflightHeaders.remove("accept-language"); preflightHeaders.remove("content-language"); preflightHeaders.remove("content-type"); }//from w w w . j a v a 2s . c o m if (isValidRequest(context, origin, preflightMethod, preflightHeaders)) { // Valid Preflight request setHeader(context, HEADER_ALLOW_ORIGIN, Optional.fromNullable(origin).or(allowOrigin)); setHeader(context, HEADER_ALLOW_METHODS, allowMethods); setHeader(context, HEADER_ALLOW_HEADERS, allowHeaders); setHeader(context, HEADER_ALLOW_CREDENTIALS, allowCredentials); setHeader(context, HEADER_MAX_AGE, maxAge); // Set OK & break the chain context.status(200).getResponse().commit(); } else { // Invalid Preflight request, set the error status & break the chain context.status(corsErrorStatus).getResponse().commit(); } } else { // Standard request String method = context.getRequestMethod(); if (isValidRequest(context, origin, method, null)) { // valid CORS request setHeader(context, HEADER_ALLOW_ORIGIN, Optional.fromNullable(origin).or(allowOrigin)); setHeader(context, HEADER_ALLOW_CREDENTIALS, allowCredentials); setHeader(context, HEADER_EXPOSE_HEADERS, exposeHeaders); // next handler in chain context.next(); } else { // invalid CORS request, set the error status & break the chain context.status(corsErrorStatus).getResponse().commit(); } } }
From source file:org.jboss.hal.dmr.ModelNodeHelper.java
/** Moves an attribute to another destination. Both source and destination can be a paths. */ public static void move(ModelNode modelNode, String source, String destination) { if (modelNode != null && Strings.emptyToNull(source) != null && Strings.emptyToNull(destination) != null) { ModelNode value = null;/*from w w w.ja va 2 s . c om*/ ModelNode context = modelNode; List<String> sourceNames = Splitter.on('/').omitEmptyStrings().trimResults().splitToList(source); if (!sourceNames.isEmpty()) { for (Iterator<String> iterator = sourceNames.iterator(); iterator.hasNext();) { String name = iterator.next(); String safeName = decodeValue(name); if (context.hasDefined(safeName)) { if (iterator.hasNext()) { context = context.get(safeName); } else { value = context.remove(safeName); break; } } } } if (value != null) { context = modelNode; List<String> destinationNames = Splitter.on('/').omitEmptyStrings().trimResults() .splitToList(destination); for (Iterator<String> iterator = destinationNames.iterator(); iterator.hasNext();) { String name = iterator.next(); String safeName = decodeValue(name); if (iterator.hasNext()) { context = context.get(safeName); } else { context.get(safeName).set(value); break; } } } } }
From source file:org.obm.icalendar.ical4jwrapper.ICalendarEvent.java
public String uid() { Uid uid = vEvent.getUid(); if (uid != null) { return Strings.emptyToNull(uid.getValue()); } return null; }
From source file:org.gbif.pubindex.service.impl.ArticleIndexerImpl.java
@VisibleForTesting protected String extractText(Article article, InputStream in) { String text = null;//from ww w .j ava 2 s. co m try { InputSource is = new InputSource(in); text = Strings.emptyToNull(ArticleExtractor.INSTANCE.getText(is)); if (text != null) { // remove null character found sometimes in xml/html // this causes postgres to choke! text = REMOVE_NULL.matcher(text).replaceAll(""); } } catch (BoilerpipeProcessingException e) { LOG.warn("Cannot extract text with boilerpipe: {}", e.getMessage()); article.setError("Cannot extract text with boilerpipe: " + e.getMessage()); // TODO: try with TIKA to extract from pdfs etc... } catch (Exception e) { LOG.warn("Cannot extract text: {}", e.getMessage()); article.setError("Cannot extract text: " + e.getMessage()); } return text; }