List of usage examples for org.apache.commons.lang3 StringUtils trimToNull
public static String trimToNull(final String str)
Removes control characters (char <= 32) from both ends of this String returning null if the String is empty ("") after the trim or if it is null .
From source file:com.omertron.slackbot.listeners.BoardGameListener.java
/** * Get the collection for a user// w w w .ja v a2 s . c o m * * @param session * @param msgChannel * @param params */ private void commandCollection(SlackSession session, SlackChannel msgChannel, String params) { LOG.info("Getting collection information, params: '{}'", params); // Split the parameters out (if multiple) String username; String ids; Matcher m = PAT_COLL_PARAM.matcher(params); if (m.matches()) { username = m.group(1); ids = StringUtils.trimToNull(m.group(2)); } else { username = params; ids = null; } LOG.info(" Username: '{}'", username); if (ids != null) { LOG.info(" ID(s): '{}'", ids); } CollectionItemWrapper result; try { List<IncludeExclude> includes = new ArrayList<>(); List<IncludeExclude> excludes = new ArrayList<>(); if (ids == null) { // Just get the username's owned collection includes.add(IncludeExclude.OWN); } else { // Get the individual ID items includes.add(IncludeExclude.STATS); } LOG.info("Getting collection information for '{}' with IDs '{}' & includes '{}'", username, ids, includes); result = BGG.getCollectionInfo(username, ids, includes, excludes, false); } catch (BggException ex) { LOG.warn("Failed to get collection for user '{}'", username, ex); session.sendMessage(msgChannel, "Failed to get collection for user " + username); return; } if (result.getTotalItems() == 0) { String message = "No information found for username '" + username + "'"; if (ids != null) { message += " with IDs '" + ids + "'"; } session.sendMessage(msgChannel, message); return; } else { LOG.info("Found {} collection items for {}", result.getTotalItems(), username); } List<SlackAttachment> collList; if (ids == null) { LOG.info("Creating simple collection"); collList = createSimpleCollection(session, msgChannel, result.getItems(), username); } else { LOG.info("Creating detailed collection"); collList = createDetailedCollection(session, msgChannel, result.getItems(), username); } SlackPreparedMessage spm = new SlackPreparedMessage.Builder().withUnfurl(false).addAttachments(collList) .build(); session.sendMessage(msgChannel, spm); }
From source file:com.intuit.karate.Script.java
public static AssertionResult matchNamed(MatchType matchType, String name, String path, String expected, ScriptContext context) {//www. ja va 2 s. co m name = StringUtils.trim(name); if (isJsonPath(name) || isXmlPath(name)) { // short-cut for operating on response path = name; name = ScriptValueMap.VAR_RESPONSE; } path = StringUtils.trimToNull(path); if (path == null) { Pair<String, String> pair = parseVariableAndPath(name); name = pair.getLeft(); path = pair.getRight(); } expected = StringUtils.trim(expected); if ("header".equals(name)) { // convenience shortcut for asserting against response header return matchNamed(matchType, ScriptValueMap.VAR_RESPONSE_HEADERS, "$['" + path + "'][0]", expected, context); } else { ScriptValue actual = context.vars.get(name); switch (actual.getType()) { case STRING: case INPUT_STREAM: return matchString(matchType, actual, expected, path, context); case XML: if ("$".equals(path)) { path = "/"; // whole document, also edge case where variable name was 'response' } if (!isJsonPath(path)) { return matchXmlPath(matchType, actual, path, expected, context); } // break; // fall through to JSON. yes, dot notation can be used on XML !! default: return matchJsonPath(matchType, actual, path, expected, context); } } }
From source file:net.centro.rtb.monitoringcenter.MonitoringCenterServlet.java
private void writeAsJson(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws IOException { boolean prettyPrint = Boolean.TRUE.toString() .equalsIgnoreCase(StringUtils.trimToNull(httpServletRequest.getParameter("prettyPrint"))); httpServletResponse.setContentType(CONTENT_TYPE_APPLICATION_JSON); try (OutputStream output = httpServletResponse.getOutputStream()) { if (prettyPrint) { objectMapper.writerWithDefaultPrettyPrinter().writeValue(output, object); } else {//from w w w .ja v a2 s . c o m objectMapper.writeValue(output, object); } } }
From source file:com.norconex.collector.http.url.impl.GenericLinkExtractor.java
@Override public void loadFromXML(Reader in) { XMLConfiguration xml = ConfigurationUtil.newXMLConfiguration(in); setMaxURLLength(xml.getInt("[@maxURLLength]", getMaxURLLength())); setIgnoreNofollow(xml.getBoolean("[@ignoreNofollow]", isIgnoreNofollow())); setKeepReferrerData(xml.getBoolean("[@keepReferrerData]", isKeepReferrerData())); if (xml.getBoolean("[@keepFragment]", false)) { LOG.warn("'keepFragment' on GenericLinkExtractor was removed. " + "Instead, URL normalization now always takes place by " + "default unless disabled, and removeFragment is part of " + "the default normalization rules."); }//from w w w .java 2 s. co m // Content Types ContentType[] cts = ContentType .valuesOf(StringUtils.split(StringUtils.trimToNull(xml.getString("contentTypes")), ", ")); if (!ArrayUtils.isEmpty(cts)) { setContentTypes(cts); } // tag & attributes List<HierarchicalConfiguration> tagNodes = xml.configurationsAt("tags.tag"); if (!tagNodes.isEmpty()) { clearLinkTags(); for (HierarchicalConfiguration tagNode : tagNodes) { String name = tagNode.getString("[@name]", null); String attr = tagNode.getString("[@attribute]", null); if (StringUtils.isNotBlank(name)) { addLinkTag(name, attr); } } } }
From source file:hoot.services.models.osm.Changeset.java
/** * Creates a simple OSM changeset create XML document * * @param description an optional changeset description * @return a changeset XML document/*www . j a va2 s. com*/ * @throws ParserConfigurationException * @throws IOException * @throws SAXException */ public static Document getChangesetCreateDoc(final String description) throws SAXException, IOException, ParserConfigurationException { String changesetDocStr = "<osm>" + "<changeset version=\"0.3\" generator=\"hoot-services\">"; if (StringUtils.trimToNull(description) != null) { changesetDocStr += "<tag k=\"description\" v=\"" + description + "\"/>"; } changesetDocStr += "</changeset>" + "</osm>"; return XmlDocumentBuilder.parse(changesetDocStr); }
From source file:com.hubrick.vertx.s3.client.S3Client.java
/** * Initialize the multipart upload. After that continue either with the automated {@link MultipartUploadWriteStream} * if you don't need response headers for each part or manually handle the part uploads using the methods {@link #continueMultipartUpload} * * @param bucket The bucket * @param key The key of the final file * @param initMultipartUploadRequest The request * @param handler Success handler * @param exceptionHandler Exception handler *//* w w w . j a v a2 s. c o m*/ public void initMultipartUpload(String bucket, String key, InitMultipartUploadRequest initMultipartUploadRequest, Handler<Response<InitMultipartUploadResponseHeaders, MultipartUploadWriteStream>> handler, Handler<Throwable> exceptionHandler) { checkNotNull(StringUtils.trimToNull(bucket), "bucket must not be null"); checkNotNull(StringUtils.trimToNull(key), "key must not be null"); checkNotNull(initMultipartUploadRequest, "initMultipartUploadRequest must not be null"); checkNotNull(handler, "handler must not be null"); checkNotNull(exceptionHandler, "exceptionHandler must not be null"); final S3ClientRequest request = createInitMultipartUploadRequest(bucket, key, initMultipartUploadRequest, new XmlBodyResponseHandler<InitMultipartUploadResponseHeaders, InitMultipartUploadResponse>( "initMultipartUpload", jaxbUnmarshaller, new InitMultipartUploadResponseHeadersMapper(), response -> { handler.handle(new ResponseWithBody(response.getHeader(), new MultipartUploadWriteStream(this, response.getData(), exceptionHandler))); }, exceptionHandler)); request.exceptionHandler(exceptionHandler); request.end(); }
From source file:alpine.Config.java
/** * Attempts to retrieve the key via environment variable. Property names are * always upper case with periods replaced with underscores. * * alpine.worker.threads/* www. ja va2 s . c o m*/ * becomes * ALPINE_WORKER_THREADS * * @param key the key to retrieve from environment * @return the value of the key (if set), null otherwise. * @since 1.4.3 */ private String getPropertyFromEnvironment(Key key) { final String envVariable = key.getPropertyName().toUpperCase().replace(".", "_"); try { return StringUtils.trimToNull(System.getenv(envVariable)); } catch (SecurityException e) { LOGGER.warn("A security exception prevented access to the environment variable. Using defaults."); } catch (NullPointerException e) { // Do nothing. The key was not specified in an environment variable. Continue along. } return null; }
From source file:com.epam.catgenome.manager.reference.ReferenceManager.java
/** * Validates and parses the given to make sure that all mandatory properties, * describing genome data, are provided. * <p>// w ww . j a v a 2s . c o m * The default values will be assigned in cases when it is possible to do. E.g., to treat omitted * custom name for a genome it's possible to use an original name of corresponded file without * extension. * * @param path {@code File} Path to fasta file * @param name {@code String} Alternative name */ private String parse(final String path, final String name) { Assert.notNull(path, getMessage(MessageCode.RESOURCE_NOT_FOUND)); // checks that an original file name is provided, because it is used as a name // for a genome if custom name isn't specified String fileName = StringUtils.trimToNull(FilenameUtils.getName(path)); Assert.notNull(fileName, getMessage(MessageCode.MANDATORY_FILE_NAME)); // checks that file is in one of supported formats boolean supported = false; final Collection<String> formats = FastaUtils.getFastaExtensions(); for (final String ext : formats) { if (fileName.endsWith(ext)) { supported = true; fileName = Utils.removeFileExtension(fileName, ext); break; } } if (!supported) { throw new IllegalArgumentException( getMessage("error.reference.illegal.file.type", StringUtils.join(formats, ", "))); } // if no custom name is provided for a genome, then a file name without extension should be // used by default return StringUtils.defaultString(StringUtils.trimToNull(name), fileName); }
From source file:co.touchlab.squeaky.processor.AnnotationProcessor.java
private MethodSpec foreignConfigs(List<ForeignCollectionHolder> fieldTypeGens, TypeSpec.Builder configBuilder) { TypeName listOfFieldConfigs = ParameterizedTypeName.get(List.class, ForeignCollectionInfo.class); TypeName arrayListOfFieldConfigs = ParameterizedTypeName.get(ArrayList.class, ForeignCollectionInfo.class); MethodSpec.Builder fieldConfigsMethodBuilder = MethodSpec.methodBuilder("getForeignConfigs") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) // .addException(SQLException.class) .returns(ForeignCollectionInfo[].class) .addStatement("$T list = new $T()", listOfFieldConfigs, arrayListOfFieldConfigs); fieldConfigsMethodBuilder.addStatement("$T config = null", ForeignCollectionInfo.class); for (ForeignCollectionHolder config : fieldTypeGens) { CodeBlock.Builder builder = CodeBlock.builder(); builder.addStatement("config = new $T(" + "$L, " + "$L, " + "$S, " + "$S, " + "$S, " + "$L.class)", ForeignCollectionInfo.class, config.foreignCollectionField.eager(), config.foreignCollectionField.maxEagerLevel(), StringUtils.trimToNull(config.foreignCollectionField.orderBy()), StringUtils.trimToNull(config.foreignCollectionField.foreignFieldName()), StringUtils.trimToNull(config.variableName), config.foreignTypeName); fieldConfigsMethodBuilder.addCode(builder.build()); fieldConfigsMethodBuilder.addStatement("list.add(config)"); }//from w w w . jav a 2 s. com fieldConfigsMethodBuilder.addStatement("return list.toArray(new ForeignCollectionInfo[list.size()])"); MethodSpec fieldConfigsMethod = fieldConfigsMethodBuilder.build(); configBuilder.addMethod(fieldConfigsMethod); return fieldConfigsMethod; }
From source file:com.oncore.calorders.core.utils.FormatHelper.java
/** * This method trims the formatting strings from a phone number. It is null * safe and the result can be null./*from w w w .java 2 s . c o m*/ * * @param phoneNumber The phone number to trim * @return The phone number after being trimmed */ public static String trimPhoneNumberToNull(String phoneNumber) { return StringUtils.replaceEach(StringUtils.trimToNull(phoneNumber), PHONE_NUMBER_FORMATTING_ARRAY, PHONE_NUMBER_REPLACE_ARRAY); }