List of usage examples for com.google.common.base Strings emptyToNull
@Nullable public static String emptyToNull(@Nullable String string)
From source file:org.mayocat.multitenancy.DefaultTenantResolver.java
private String extractSlugFromHost(String host) { String rootDomain;/* w ww . ja v a 2 s . c o m*/ String siteName = siteSettings.getWebDomainName().or(siteSettings.getDomainName()); if (Strings.emptyToNull(siteName) == null) { InternetDomainName domainName = InternetDomainName.from(host); if (domainName.hasPublicSuffix()) { // Domain is under a valid TLD, extract the TLD + first child rootDomain = domainName.topPrivateDomain().name(); } else if (host.indexOf(".") > 0 && host.indexOf(".") < host.length()) { // Otherwise, best guess : strip everything before the first dot. rootDomain = host.substring(host.indexOf(".") + 1); } else { rootDomain = host; } } else { rootDomain = StringUtils.substringBefore(siteSettings.getDomainName(), ":"); } if (host.indexOf("." + rootDomain) > 0) { return host.substring(0, host.indexOf("." + rootDomain)); } else { return host; } }
From source file:com.reprezen.swagedit.json.references.JsonReferenceFactory.java
protected JsonReference doCreate(String value, Object source) { String notNull = Strings.nullToEmpty(value); URI uri;//from w ww . j av a 2 s. c o m try { uri = URI.create(notNull); } catch (NullPointerException | IllegalArgumentException e) { // try to encode illegal characters, e.g. curly braces try { uri = URI.create(URLUtils.encodeURL(notNull)); } catch (NullPointerException | IllegalArgumentException e2) { return new JsonReference(null, null, false, false, false, source); } } String fragment = uri.getFragment(); JsonPointer pointer = null; try { pointer = JsonPointer.compile(Strings.emptyToNull(fragment)); } catch (IllegalArgumentException e) { // let the pointer be null } uri = uri.normalize(); boolean absolute = uri.isAbsolute(); boolean local = !absolute && uri.getPath().isEmpty(); // should warn when using curly braces boolean warnings = notNull.contains("{") || uri.toString().contains("}"); return new JsonReference(uri, pointer, absolute, local, warnings, source); }
From source file:de.schildbach.pte.ZvvProvider.java
@Override protected Line parseLineAndType(final String lineAndType) { final Matcher m = P_NORMALIZE_LINE_AND_TYPE.matcher(lineAndType); if (m.matches()) { final String number = Strings.emptyToNull(m.group(1).replaceAll("\\s+", "")); final String type = Strings.emptyToNull(m.group(2)); if ("Bus".equals(type)) return newLine(Product.BUS, stripPrefix(number, "Bus"), null); if ("Bus-NF".equals(type)) return newLine(Product.BUS, stripPrefix(number, "Bus", "Bus-NF"), null, Line.Attr.WHEEL_CHAIR_ACCESS); if ("Tro".equals(type) || "Trolley".equals(type)) return newLine(Product.BUS, stripPrefix(number, "Tro"), null); if ("Tro-NF".equals(type)) return newLine(Product.BUS, stripPrefix(number, "Tro", "Tro-NF"), null, Line.Attr.WHEEL_CHAIR_ACCESS); if ("Trm".equals(type)) return newLine(Product.TRAM, stripPrefix(number, "Trm"), null); if ("Trm-NF".equals(type)) return newLine(Product.TRAM, stripPrefix(number, "Trm", "Trm-NF"), null, Line.Attr.WHEEL_CHAIR_ACCESS); if ("S18".equals(number)) return newLine(Product.SUBURBAN_TRAIN, "S18", null); if (number != null && P_NUMBER.matcher(number).matches()) return newLine(null, number, null); if (type != null) { final Product product = normalizeType(type); if (product != null) return newLine(product, number, null); }/*from www . j a v a 2 s.c o m*/ throw new IllegalStateException( "cannot normalize type " + type + " number " + number + " line#type " + lineAndType); } throw new IllegalStateException("cannot normalize line#type " + lineAndType); }
From source file:ratpack.server.internal.InferringPublicAddress.java
private HostAndPort getHostData(Request request) { Headers headers = request.getHeaders(); String hostPortString = Strings.emptyToNull(headers.get(HOST.toString())); return hostPortString != null ? HostAndPort.fromString(hostPortString) : null; }
From source file:org.n52.shetland.ogc.ows.extension.Extensions.java
private boolean check(String name, Extension<?> extension, Function<Extension<?>, String> extractor) { if (Strings.emptyToNull(name) == null || extension == null) { return false; }//from www.j a v a 2s . c o m return Optional.ofNullable(extractor.apply(extension)).map(s -> s.equalsIgnoreCase(name)) .orElseGet(() -> false); }
From source file:lu.list.itis.dkd.aig.process.OnDemandTextOntologyCreationProcess.java
/** * Constructor initializing all fields./*from w w w . j a v a 2 s .c om*/ * * @param parameters * A list of parameters keyed by the parameter name to draw all * fields values from. * @throws TemplateParseException * Thrown when one or more of the required parameter values was * missing or of an erroneous value. */ public OnDemandTextOntologyCreationProcess(final ArrayListMultimap<String, String> parameters) throws TemplateParseException, ResolutionException { super(parameters); checkArgument(parameters.containsKey(Externalization.DATASOURCE_KEY), "The datasource key provided for the process must be specified and non-emtpy!"); datasourceKey = Strings.emptyToNull(parameters.get(Externalization.DATASOURCE_KEY).get(0)); checkNotNull(datasourceKey, "The datasource key provided for the process must be specified and non-emtpy!"); URI datasource = outcomeVariablesByValueKey.get(datasourceKey); datasourceVariable = VariableBuilder.getVariableFromBlueprint(datasource); try { datasourceValue = datasourceVariable.getValueByIdentifier(datasourceKey); } catch (TemplateConsistencyException e) { throw new TemplateParseException( "Unable to get value: " + datasourceKey + " in: " + datasourceValue.getIdentifier(), e); } if (parameters.containsKey(Externalization.NUMBER_OF_DISTRACTORS)) { numberOfDistractors = Integer.parseInt(parameters.get(Externalization.NUMBER_OF_DISTRACTORS).get(0)); } if (parameters.containsKey(Externalization.FIRST_SENTENCE)) { skipFirstSentence = Boolean.parseBoolean(parameters.get(Externalization.FIRST_SENTENCE).get(0)); } if (parameters.containsKey(Externalization.USE_NGRAM_ARTICLE_CORRECTION)) { useNGramArticleCorrection = Boolean .parseBoolean(parameters.get(Externalization.USE_NGRAM_ARTICLE_CORRECTION).get(0)); } if (parameters.containsKey(Externalization.USE_GRAMMATICAL_DEPENDENCIES)) { useGrammaticalDependencies = Boolean .parseBoolean(parameters.get(Externalization.USE_GRAMMATICAL_DEPENDENCIES).get(0)); } if (parameters.containsKey(Externalization.SOUNDEX)) { useSoundex = Boolean.parseBoolean(parameters.get(Externalization.SOUNDEX).get(0)); } if (parameters.containsKey(Externalization.FEEDBACK)) { generateFeedback = Boolean.parseBoolean(parameters.get(Externalization.FEEDBACK).get(0)); } if (parameters.containsKey(Externalization.APPROACH)) { approach = Approach.valueOf(parameters.get(Externalization.APPROACH).get(0).toUpperCase()); } if (parameters.containsKey(Externalization.DIFFICULTY)) { difficulty = Difficulty.valueOf(parameters.get(Externalization.DIFFICULTY).get(0).toUpperCase()); } }
From source file:ru.org.linux.comment.CommentPrepareService.java
private PreparedComment prepareComment(MessageText messageText, User author, @Nullable String remark, @Nonnull Comment comment, CommentList comments, boolean secure, Template tmpl, Topic topic) throws UserNotFoundException { String processedMessage = prepareCommentText(messageText, !topicPermissionService.followAuthorLinks(author)); ReplyInfo replyInfo = null;/*from w w w . j a va2 s. co m*/ boolean deletable = false; boolean editable = false; if (comments != null) { if (comment.getReplyTo() != 0) { CommentNode replyNode = comments.getNode(comment.getReplyTo()); boolean replyDeleted = replyNode == null; if (replyDeleted) { // replyInfo = new ReplyInfo(comment.getReplyTo(), replyDeleted); } else { Comment reply = replyNode.getComment(); boolean samePage = false; if (tmpl != null) { int replyPage = comments.getCommentPage(reply, tmpl.getProf()); samePage = comments.getCommentPage(comment, tmpl.getProf()) == replyPage; } String replyAuthor = userDao.getUserCached(reply.getUserid()).getNick(); replyInfo = new ReplyInfo(reply.getId(), replyAuthor, Strings.emptyToNull(reply.getTitle().trim()), reply.getPostdate(), samePage, replyDeleted); } } boolean haveAnswers = comments.getNode(comment.getId()).isHaveAnswers(); if (tmpl != null && topic != null) { final User currentUser = tmpl.getCurrentUser(); deletable = topicPermissionService.isCommentDeletableNow(comment, currentUser, topic, haveAnswers); if (currentUser != null) { editable = topicPermissionService.isCommentEditableNow(comment, currentUser, haveAnswers, topic); } } } Userpic userpic = null; if (tmpl != null && tmpl.getProf().isShowPhotos()) { userpic = userService.getUserpic(author, tmpl.getProf().getAvatarMode(), false); } ApiUserRef ref = userService.ref(author, tmpl != null ? tmpl.getCurrentUser() : null); ApiDeleteInfo deleteInfo = loadDeleteInfo(comment); EditSummary editSummary = loadEditSummary(comment); String postIP = null; String userAgent = null; if (tmpl != null && tmpl.isModeratorSession()) { postIP = comment.getPostIP(); userAgent = userAgentDao.getUserAgentById(comment.getUserAgentId()); } return new PreparedComment(comment, ref, processedMessage, replyInfo, deletable, editable, remark, userpic, deleteInfo, editSummary, postIP, userAgent); }
From source file:org.robotframework.ide.eclipse.main.plugin.project.LibrariesAutoDiscoverer.java
@VisibleForTesting LibrariesAutoDiscoverer(final RobotProject robotProject, final List<? extends IResource> resources, final boolean showSummary, final String libraryNameToDiscover) { super(robotProject, resources, new LibrariesSourcesCollector(robotProject), new DryRunTargetsCollector()); this.showSummary = showSummary; this.libraryNameToDiscover = Optional.ofNullable(Strings.emptyToNull(libraryNameToDiscover)); this.dryRunLibraryImportCollector = new RobotDryRunLibraryImportCollector( robotProject.getStandardLibraries().keySet()); }
From source file:com.google.gerrit.server.project.CreateProject.java
@Override public Object apply(TopLevelResource resource, Input input) throws BadRequestException, UnprocessableEntityException, ProjectCreationFailedException, IOException { if (input == null) { input = new Input(); }/*from ww w .j ava 2 s.c o m*/ if (input.name != null && !name.equals(input.name)) { throw new BadRequestException("name must match URL"); } final CreateProjectArgs args = new CreateProjectArgs(); args.setProjectName(name); if (!Strings.isNullOrEmpty(input.parent)) { args.newParent = projectsCollection.get().parse(input.parent).getControl(); } args.createEmptyCommit = input.createEmptyCommit; args.permissionsOnly = input.permissionsOnly; args.projectDescription = Strings.emptyToNull(input.description); args.submitType = Objects.firstNonNull(input.submitType, SubmitType.MERGE_IF_NECESSARY); args.branch = input.branches; if (input.owners != null) { List<AccountGroup.UUID> ownerIds = Lists.newArrayListWithCapacity(input.owners.size()); for (String owner : input.owners) { ownerIds.add(groupsCollection.get().parse(owner).getGroupUUID()); } args.ownerIds = ownerIds; } args.contributorAgreements = Objects.firstNonNull(input.useContributorAgreements, InheritableBoolean.INHERIT); args.signedOffBy = Objects.firstNonNull(input.useSignedOffBy, InheritableBoolean.INHERIT); args.contentMerge = input.submitType == SubmitType.FAST_FORWARD_ONLY ? InheritableBoolean.FALSE : Objects.firstNonNull(input.useContentMerge, InheritableBoolean.INHERIT); args.changeIdRequired = Objects.firstNonNull(input.requireChangeId, InheritableBoolean.INHERIT); Project p = createProjectFactory.create(args).createProject(); return Response.created(json.format(p)); }
From source file:org.gbif.registry.ws.guice.StringTrimInterceptor.java
private void trimStringsOf(Object target, int level) { if (target != null && level <= MAX_RECURSION) { LOG.debug("Trimming class: {}", target.getClass()); WrapDynaBean wrapped = new WrapDynaBean(target); DynaClass dynaClass = wrapped.getDynaClass(); for (DynaProperty dynaProp : dynaClass.getDynaProperties()) { if (String.class.isAssignableFrom(dynaProp.getType())) { String prop = dynaProp.getName(); String orig = (String) wrapped.get(prop); if (orig != null) { String trimmed = Strings.emptyToNull(orig.trim()); if (!Objects.equal(orig, trimmed)) { LOG.debug("Overriding value of [{}] from [{}] to [{}]", prop, orig, trimmed); wrapped.set(prop, trimmed); }//w w w . j a va2 s . c om } } else { try { // trim everything in the registry model package (assume that Dataset resides in the correct package here) Object property = wrapped.get(dynaProp.getName()); if (property != null && Dataset.class.getPackage() == property.getClass().getPackage()) { trimStringsOf(property, level + 1); } } catch (IllegalArgumentException e) { // expected for non accessible properties } } } } }