List of usage examples for org.apache.commons.lang StringUtils strip
public static String strip(String str)
Strips whitespace from the start and end of a String.
From source file:org.eclipse.skalli.model.ext.maven.internal.MavenPomParserImpl.java
private MavenPom parse(Document document) { MavenPom result = new MavenPom(); MavenModule self = parseMavenCoordinate(document, PROJECT); result.setSelf(self);/*from ww w . j a v a2 s. co m*/ if (elementExists(document, PARENT)) { MavenModule parent = parseMavenCoordinate(document, PARENT); result.setParent(parent); String relativePath = extractTextContent(document, PARENT, RELATIVE_PATH); result.setParentRelativePath(relativePath); } NodeList modules = document.getElementsByTagName(MODULE); for (int i = 0; i < modules.getLength(); ++i) { String text = StringUtils.strip(modules.item(i).getTextContent()); if (StringUtils.isNotBlank(text)) { result.getModuleTags().add(text); } } return result; }
From source file:org.eclipse.skalli.model.ext.maven.internal.MavenPomParserImpl.java
private String extractTextContent(Document document, String parentTagName, String tagName) { String textContent = null;/* w w w. j a v a 2s . c o m*/ NodeList parentNodes = document.getElementsByTagName(parentTagName); if (parentNodes.getLength() > 0) { Node parent = parentNodes.item(0); NodeList children = parent.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node node = children.item(i); if (tagName.equals(node.getNodeName())) { textContent = StringUtils.strip(node.getTextContent()); break; } } } return textContent; }
From source file:org.fhcrc.cpl.viewer.commandline.modules.SpreadsheetMergeCLM.java
/** * Read each line as a String, stopping at first whitespace * @param file//from ww w. ja v a 2 s .c om * @return * @throws ArgumentValidationException */ protected List<String> readOneStringPerLine(File file) throws ArgumentValidationException { List<String> result = new ArrayList<String>(); try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line = null; while ((line = br.readLine()) != null) { String protein = StringUtils.strip(line); //if there's more than one column in the file, take first protein = protein.replaceFirst("\\s.*", ""); result.add(protein); } } catch (Exception e) { throw new ArgumentValidationException("Failed to retrieve list from file " + file + ". Please make sure file contains only a list of identifiers, one per line"); } return result; }
From source file:org.fhcrc.cpl.viewer.ms2.commandline.PostProcessPepXMLCLM.java
/** * Read each line as a String, stopping at first whitespace * @param file//from www . ja v a 2s . co m * @return * @throws ArgumentValidationException */ protected List<String> readOneStringPerLine(File file) throws ArgumentValidationException { List<String> result = new ArrayList<String>(); try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line = null; while ((line = br.readLine()) != null) { if (line.startsWith("#")) continue; String protein = StringUtils.strip(line); //if there's more than one column in the file, take first protein = protein.replaceFirst("\\s.*", ""); result.add(protein); } } catch (Exception e) { throw new ArgumentValidationException("Failed to retrieve list from file " + file + ". Please make sure file contains only a list of identifiers, one per line"); } return result; }
From source file:org.gbif.harvest.digir.DigirHarvester.java
/** * Iterates over the nameRanges file, executing a search for each range. A * single search retrieves all records for the concept of interest that fall * in the specified range. If the concept were scientific name, for example, * the searches would collectively retrieve all the destination's records * for all scientific names contained in the resource of interest. This * information, collected as raw xml responses, is saved in the output * directory. The files written this way depend on the assumption * that at most one harvester will be targeting a given resource/name range * pair at a time.//from www . j a v a2 s . co m * * @param resource to query * @param destination of the DiGIR server to issue against * @param outputDirectory where files of interest are located * @param protocol name of harvester * @param maxSearchResponse maximum number of records returned in a response * @param targetCount target count of resource * * @throws HarvesterException thrown if method fails */ public void search(String resource, String destination, String outputDirectory, String protocol, String maxSearchResponse, int targetCount) throws HarvesterException { if (debug) { log.debug(">> search"); } // set the request response writer to the right directory searchWriter.setFileOutputDirectory(outputDirectory); // setup the NameRangeHandler for this search NameRangeHandler nameRangeHandler = new NameRangeHandler(outputDirectory, fileUtils); // get iterator over name ranges LineIterator nameRangeIter = nameRangeHandler.getNameRangeIterator(); // build the parameters required for the template into a map Map<String, String> templateParams = new HashMap<String, String>(); templateParams.put("resource", resource); templateParams.put("destination", destination); // gather the request content namespaces Properties mapping = new Properties(); String mappingFilePath = fileUtils.constructMappingFilePath(BASE_LOCATION, protocol, DigirHarvester.MAPPING_DIRECTORY_NAME, DigirHarvester.REQUEST_NAMESPACE_MAPPING_FILENAME); if (debug) { log.debug("Reading mappingFile from [" + mappingFilePath + "]"); } InputStream is = null; try { is = getClass().getResourceAsStream(mappingFilePath); if (is == null) { throw new HarvesterException( "Namespace mapping file not found, aborting search [" + mappingFilePath + "]"); } mapping.load(is); for (Object key : mapping.keySet()) { requestNamespaceMappings.put((String) key, mapping.getProperty((String) key)); } } catch (IOException e) { log.error("Problem loading request namespace mapping file", e); throw new HarvesterException(e.getMessage(), e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { log.error( "An error occurred closing input stream on " + mappingFilePath + ": " + e.getMessage(), e); } } } // set the default DwC request namespace String contentNamespace = DigirHarvester.DEFAULT_CONTENT_NAMESPACE; for (String property : requestNamespaceMappings.keySet()) { if (StringUtils.equalsIgnoreCase("full", property)) { contentNamespace = requestNamespaceMappings.get(property); } } if (debug) { log.debug("The request content namespace that will be used is [" + contentNamespace + "]"); } templateParams.put("contentNamespace", contentNamespace); // determine max search response size int maxResponseSize = -1; try { maxResponseSize = Integer.valueOf(maxSearchResponse); } catch (Exception e) { log.warn("Error reading maxResponseSize [" + maxSearchResponse + "], please check that it has been set properly by the provider", e); } if (maxResponseSize < Constants.MIN_QUERY_TERM_LENGTH || maxResponseSize > MAX_RESPONSE_SIZE) { maxResponseSize = MAX_RESPONSE_SIZE; log.info("Defaulting maximum number of search records returned in a single response [" + String.valueOf(MAX_RESPONSE_SIZE) + "]"); } else { log.info("The maximum number of search records returned in a single response has been set to [" + String.valueOf(MAX_RESPONSE_SIZE) + "]"); } // grab the gbif log message output file File gbifLogMessageFile = new File(outputDirectory, Constants.GBIF_LOG_MESSAGE_FILENAME + Constants.TEXT_FILENAME_EXTENSION); // created buffered writer BufferedWriter gbifLogMessageFileBW = null; try { gbifLogMessageFileBW = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(gbifLogMessageFile, true), "UTF8")); } catch (IOException e) { log.error("Couldn't open GBIF 'Harvesting' log event file", e); } // each line in the file is a name range int requestCount = 0; int sameRequestCount = 0; while (nameRangeIter.hasNext()) { // For each line, extract the lower and upper name ranges String line = nameRangeIter.nextLine(); String lower = StringUtils.strip(fileUtils.getDelimitedPart(line, "\t", 0)); String upper = StringUtils.strip(fileUtils.getDelimitedPart(line, "\t", 1)); if (StringUtils.isBlank(lower) || StringUtils.isBlank(upper)) { // something is wrong with that range - log and ignore log.warn("Found invalid name range lower [" + lower + "] and upper [" + upper + "] - ignoring and continuing with next range"); continue; } log.info("Start harvesting range [" + lower + " - " + upper + "]"); // add range parameters to templateParams templateParams.put("lower", lower); templateParams.put("upper", upper); Integer startAt = 0; Integer innerMaxResults = maxResponseSize; boolean finished = false; boolean fireSameSearch = false; Integer endOfErrorRange = null; while (!finished) { templateParams.put("startAt", startAt.toString()); templateParams.put("maxResults", innerMaxResults.toString()); boolean inError = false; try { finished = fireSearch(destination, templateParams, protocol, gbifLogMessageFileBW, requestCount); } catch (SAXParseException saxe) { log.info("SAX Parse exception in parsing search response starting from [" + startAt + "] with maxResults [" + innerMaxResults + "]", saxe); // the chances are good that this error is in only one of the records coming back // so we can try again and start narrowing the size of the response until we find // the one causing the problem. It also may have been a transient error, so just // retrying would be enough to fix it. In that case we watch for a startAt beyond // this error range and when that is hit, bump the search back up to maxResponseSize. if (innerMaxResults == 1) { // we've found exactly one record that is in error - log in detail and move on log.warn( "Search record in error - record num [" + startAt + "]" + "in range lower [" + lower + "] upper [" + upper + "] " + "from destination [" + destination + "]", saxe); // assume that most errors are bad chars in a single record, so now set max results back to full endOfErrorRange = null; innerMaxResults = maxResponseSize; startAt++; // start should never exceed targetCount (avoid endless looping - skip range) if (startAt > targetCount) { log.error("Inside retry loop: request parameter startAt exceeded targetCount: " + String.valueOf(targetCount) + " Skipping range lower [" + lower + "] upper [" + upper + "]"); break; } else { continue; } } else { inError = true; endOfErrorRange = startAt + innerMaxResults; } } catch (SAXException e) { // we don't know enough to recover, so write this range out as failed, and move on to next range nameRangeHandler.appendFailedRange(lower, upper); break; } catch (SocketException se) { // the connection was reset, so re-issue the exact same request. // We have already waited 3 minutes to give the provider software the chance to reset in fireSearch() sameRequestCount++; // only re-issue same request on SocketException 5 times if (sameRequestCount <= 4) { log.info("Re-issue same request (" + String.valueOf(sameRequestCount) + ")"); inError = true; fireSameSearch = true; } else { log.info("Exceeded max number of possible re-issue same request"); nameRangeHandler.appendFailedRange(lower, upper); break; } } // was the operation stopped? catch (OperationStoppedException e) { throw new HarvesterException(e.getMessage(), e); } // setup for the next pass if (!finished) { if (inError && !fireSameSearch) { innerMaxResults = Math.max(1, innerMaxResults / DIVISOR); } else if (inError && fireSameSearch) { // parameters stay the same } else { requestCount++; if (endOfErrorRange != null && (startAt > endOfErrorRange)) { if (debug) { log.debug("StartAt passed endOfErrorRange, resetting max results"); } innerMaxResults = maxResponseSize; endOfErrorRange = null; } startAt = startAt + innerMaxResults; } } else { // successful completion of range nameRangeHandler.registerSuccessfulRange(lower); } } } LineIterator.closeQuietly(nameRangeIter); // a successful search has been completed, so do name range cleanup (ie delete pendingNameRanges file) nameRangeHandler.close(); // close bufferedWriter on GBIF Log Event Message file if (gbifLogMessageFile != null) { // close bufferedWriter on GBIF Log Event Message file try { gbifLogMessageFileBW.close(); } catch (IOException e) { log.error("Could not close buffered writer for file [" + gbifLogMessageFile.getAbsolutePath() + "]", e); } } log.info("End search"); }
From source file:org.geoserver.taskmanager.tasks.CopyTableTaskTypeImpl.java
private static String getTableName(Connection conn, String tableName) throws SQLException { String name = StringUtils.strip(SqlUtil.notQualified(tableName)); if (conn.getMetaData().storesUpperCaseIdentifiers()) { name = name.toUpperCase();/* ww w . j a v a2 s .c o m*/ } else if (conn.getMetaData().storesUpperCaseIdentifiers()) { name = name.toLowerCase(); } return name; }
From source file:org.hippoecm.hst.demo.components.solrutil.SolrSearchParams.java
public SolrSearchParams(HstRequest request) { this.request = request; if (getPublicRequestParameter(request, "suggest") == null) { // default true showSuggest = false;// w ww . j ava2s .co m } else { showSuggest = (Boolean) ConvertUtils.convert(getPublicRequestParameter(request, "suggest"), Boolean.class); } if (getPublicRequestParameter(request, "spellcheck") == null) { // default true showSpellCheck = false; } else { showSpellCheck = (Boolean) ConvertUtils.convert(getPublicRequestParameter(request, "spellcheck"), Boolean.class); } if (getPublicRequestParameter(request, "highlight") == null) { // default true showHighlight = false; } else { showHighlight = (Boolean) ConvertUtils.convert(getPublicRequestParameter(request, "highlight"), Boolean.class); } if (getPublicRequestParameter(request, "score") == null) { // default true showScore = false; } else { showScore = (Boolean) ConvertUtils.convert(getPublicRequestParameter(request, "score"), Boolean.class); } query = StringUtils.strip(getPublicRequestParameter(request, "query")); if (StringUtils.isBlank(query)) { query = null; } if (getPublicRequestParameter(request, "operator") == null) { // default OR-ed operator = "and_ed"; } else { operator = getPublicRequestParameter(request, "operator"); } searchIn = getPublicRequestParameter(request, "searchin"); if (StringUtils.isBlank(searchIn)) { searchIn = "all"; } searchField = getPublicRequestParameter(request, "searchfield"); if (StringUtils.isBlank(searchField)) { searchField = "all"; } types = request.getParameterMap("").get("type"); if (types == null) { types = new String[] { "all" }; } includeSubtypes = (Boolean) ConvertUtils.convert(getPublicRequestParameter(request, "includeSubtypes"), Boolean.class); String fromDateString = getPublicRequestParameter(request, "fromdate"); if (StringUtils.isNotBlank(fromDateString)) { try { fromDate = formatter.parse(fromDateString); } catch (ParseException e) { log.warn("Skip invalid fromDate '{}'", fromDateString); } } String toDateString = getPublicRequestParameter(request, "todate"); if (StringUtils.isNotBlank(toDateString)) { try { toDate = formatter.parse(toDateString); } catch (ParseException e) { log.warn("Skip invalid toDate '{}'", toDateString); } } sort = getPublicRequestParameter(request, "sort"); if (StringUtils.isBlank(sort)) { sort = "score"; } sortOrder = getPublicRequestParameter(request, "order"); if (StringUtils.isBlank(sortOrder)) { sortOrder = "desc"; } }
From source file:org.jasig.portal.plugin.deployer.AbstractExtractingEarDeployer.java
/** * Creates a {@link WebModule} from a {@link Node} from the descriptor. The {@link #WEB_URI_NODE_NAME} * and {@link #CONTEXT_ROOT_NODE_NAME} child nodes are used to populate the respective properties on * the {@link WebModule}./*from w ww . j a v a 2s .c o m*/ * * @param webModuleNode The 'web' Node that has the information needed to create a WebModule. * @return A WebModule that represents the data contained in the passed Node. */ protected WebModule getWebModuleInfo(Node webModuleNode) { if (!"web".equals(this.getNodeName(webModuleNode))) { throw new IllegalArgumentException("webModuleNode must be a 'web' Node"); } String webUri = null; String contextRoot = null; //Iterate through the children looking for needed elements final NodeList childNodes = webModuleNode.getChildNodes(); for (int index = 0; index < childNodes.getLength() && (webUri == null || contextRoot == null); index++) { final Node node = childNodes.item(index); final String nodeName = this.getNodeName(node); if (WEB_URI_NODE_NAME.equals(nodeName)) { webUri = StringUtils.strip(node.getTextContent()); } else if (CONTEXT_ROOT_NODE_NAME.equals(nodeName)) { contextRoot = StringUtils.strip(node.getTextContent()); } } //Check that the node had all the right info if (webUri == null || contextRoot == null) { throw new IllegalArgumentException("Node '" + webModuleNode + "' did not contain the nessesary information to create a WebModule. webUri='" + webUri + "', contextRoot='" + contextRoot + "'"); } //Create the WebModule object final WebModule webModule = new WebModule(); webModule.setWebUri(webUri); webModule.setContextRoot(contextRoot); if (this.getLogger().isDebugEnabled()) { this.getLogger().debug("Found WebModule='" + webModule + "'"); } return webModule; }
From source file:org.jts.eclipse.conversion.cjsidl.ConversionUtil.java
/** * Adds comment markers to a JSIDL interpretation string * @param interp - a JSIDL interpretation string * @return - a string with comment markers *//*from ww w . j a v a 2 s . c o m*/ public static String JSIDLInterpToCJSIDLComment(String interp) { String result = ""; if (interp == null || interp.isEmpty()) { return null; } result += "##"; String returnString = ""; // get rid of some of the whitespace String strippedComment = StringUtils.strip(interp); // if the comments are too long, then break them up // on multiple lines. at the same time remove additional spaces. String[] tmpstr = strippedComment.split("[ \n\t]+"); for (String word : tmpstr) { // many whitespace characters are embedded in these strings // make sure we remove them. returnString += " " + StringUtils.strip(word); } result += returnString.trim() + "##"; return result; }
From source file:org.jts.protocolvalidator.Guard.java
/** * Retrieve a list of condition elements, since a condition can contain * any number of elements combined with logical operators. * @param msgData - message data instance name * @return - list of condition elements/*from w ww . j a v a2s.c om*/ */ public List<String> getConditionElement() { List<String> output = new ArrayList<String>(); String tmpcond = Util.formatConditionString(condition); // get rid of some of the whitespace // remove all logical operators, since we are concerned with just the elemenats. tmpcond = tmpcond.replace(" && ", " \t "); tmpcond = tmpcond.replace(" || ", " \t "); tmpcond = tmpcond.replaceAll("!", ""); // if the comments are too long, then break them up // on multiple lines. at the same time remove additional spaces. // The assumption is that these conditions don't normally contain tabs within the element. String[] tmpstr = tmpcond.split("[\t]+"); for (String element : tmpstr) { element = StringUtils.strip(element); element = StringUtils.deleteWhitespace(element); output.add(element); } return output; }