List of usage examples for org.apache.commons.lang3 StringUtils substringBeforeLast
public static String substringBeforeLast(final String str, final String separator)
Gets the substring before the last occurrence of a separator.
From source file:com.gargoylesoftware.htmlunit.util.DebuggingWebConnection.java
/** * Computes the best file to save the response to the given URL. * @param url the requested URL//from w w w.j av a2s. c om * @param extension the preferred extension * @return the file to create * @throws IOException if a problem occurs creating the file */ private File createFile(final URL url, final String extension) throws IOException { String name = url.getPath().replaceFirst("/$", "").replaceAll(".*/", ""); name = StringUtils.substringBefore(name, "?"); // remove query name = StringUtils.substringBefore(name, ";"); // remove additional info name = StringUtils.substring(name, 0, 30); // avoid exceptions due to too long file names name = com.gargoylesoftware.htmlunit.util.StringUtils.sanitizeForFileName(name); if (!name.endsWith(extension)) { name += extension; } int counter = 0; while (true) { final String fileName; if (counter != 0) { fileName = StringUtils.substringBeforeLast(name, ".") + "_" + counter + "." + StringUtils.substringAfterLast(name, "."); } else { fileName = name; } final File f = new File(reportFolder_, fileName); if (f.createNewFile()) { return f; } counter++; } }
From source file:de.blizzy.documentr.access.UserStore.java
/** Returns all known role names. */ public List<String> listRoles() throws IOException { ILockedRepository repo = null;//from w w w .ja v a2 s . c o m try { repo = globalRepositoryManager.getProjectCentralRepository(REPOSITORY_NAME, false); File workingDir = RepositoryUtil.getWorkingDir(repo.r()); FileFilter filter = new FileFilter() { @Override public boolean accept(File file) { return file.isFile() && file.getName().endsWith(ROLE_SUFFIX); } }; List<File> files = Lists.newArrayList(workingDir.listFiles(filter)); Function<File, String> function = new Function<File, String>() { @Override public String apply(File file) { return StringUtils.substringBeforeLast(file.getName(), ROLE_SUFFIX); } }; List<String> users = Lists.newArrayList(Lists.transform(files, function)); Collections.sort(users); return users; } finally { Closeables.closeQuietly(repo); } }
From source file:de.jcup.egradle.sdk.builder.action.javadoc.ReplaceJavaDocPartsAction.java
License:asdf
private String replaceCommentInLine(String text) { if (text.indexOf("//") == -1) { return text; }/*from w ww . j a v a 2 s . c om*/ String before = StringUtils.substringBefore(text, "//"); int lastindexOpening = before.lastIndexOf('<'); int lastindexClosing = before.lastIndexOf('>'); if (lastindexOpening > lastindexClosing) { /* * e.g. a "< // comment" or a "<><//comment" which will be ignored */ return text; } String after = StringUtils.substringAfter(text, "//"); StringBuilder sb = new StringBuilder(); sb.append(before); sb.append("<em class='comment'>//"); if (after.endsWith("\n")) { sb.append(StringUtils.substringBeforeLast(after, "\n")); sb.append("</em>\n"); } else { sb.append(after); sb.append("</em>"); } return sb.toString(); }
From source file:com.thinkbiganalytics.metadata.jpa.support.GenericQueryDslFilter.java
private static UUID convertToUUID(Object value) { if (value instanceof UUID) { return (UUID) value; } else if (value instanceof String) { String stringValue = (String) value; if (((String) value).endsWith("%")) { stringValue = StringUtils.substringBeforeLast(stringValue, "%"); }//from w w w .j a v a 2s . c om try { UUID uuid = UUID.fromString(stringValue); return uuid; } catch (IllegalArgumentException e) { //unable to convert to uuid } } return null; }
From source file:com.neatresults.mgnltweaks.json.JsonBuilder.java
/** * Executes configured chain of operations and produces the json output. *///www. j a v a 2s . c o m public String print() { ObjectWriter ow = mapper.writer(); if (!inline) { ow = ow.withDefaultPrettyPrinter(); } if (wrapForI18n) { node = new I18nNodeWrapper(node); } try { // total depth is that of starting node + set total by user totalDepth += node.getDepth(); String json; if (childrenOnly) { Collection<EntryableContentMap> childNodes = new LinkedList<EntryableContentMap>(); NodeIterator nodes = this.node.getNodes(); asNodeStream(nodes).filter(this::isSearchInNodeType).map(this::cloneWith) .forEach(builder -> childNodes.add(new EntryableContentMap(builder))); json = ow.writeValueAsString(childNodes); } else if (!allowOnlyNodeTypes.equals(".*")) { Collection<EntryableContentMap> childNodes = new LinkedList<EntryableContentMap>(); NodeIterator nodes = this.node.getNodes(); asNodeStream(nodes).filter(this::isSearchInNodeType) .forEach(new PredicateSplitterConsumer<Node>(this::isOfAllowedDepthAndType, allowedNode -> childNodes.add(new EntryableContentMap(this.cloneWith(allowedNode))), allowedParent -> childNodes .addAll(this.getAllowedChildNodesContentMapsOf(allowedParent, 1)))); json = ow.writeValueAsString(childNodes); } else { EntryableContentMap map = new EntryableContentMap(this); List<String> garbage = map.entrySet().stream() .filter(entry -> entry.getValue() instanceof EntryableContentMap) .filter(entry -> ((EntryableContentMap) entry.getValue()).entrySet().isEmpty()) .map(entry -> entry.getKey()).collect(Collectors.toList()); garbage.stream().forEach(key -> map.remove(key)); json = ow.writeValueAsString(map); } if (StringUtils.isNotEmpty(preexisingJson)) { String trimmedJson = preexisingJson.trim(); if (trimmedJson.endsWith("}")) { json = "[" + preexisingJson + "," + json + "]"; } else if (trimmedJson.endsWith("]")) { json = StringUtils.substringBeforeLast(preexisingJson, "]") + (trimmedJson.equals("[]") ? "" : ",") + json + "]"; } } if (escapeBackslash) { json = ESCAPES.matcher(json).replaceAll("\\\\\\\\"); } return json; } catch (JsonProcessingException | RepositoryException e) { log.debug("Failed to generate JSON string", e); } return "{ }"; }
From source file:com.norconex.commons.lang.url.URLNormalizer.java
/** * <p>Removes directory index files. They are often not needed in URLs.</p> * <code>http://www.example.com/a/index.html → * http://www.example.com/a/</code> * <p>Index files must be the last URL path segment to be considered. * The following are considered index files:</p> * <ul>/* ww w .j av a2s .co m*/ * <li>index.html</li> * <li>index.htm</li> * <li>index.shtml</li> * <li>index.php</li> * <li>default.html</li> * <li>default.htm</li> * <li>home.html</li> * <li>home.htm</li> * <li>index.php5</li> * <li>index.php4</li> * <li>index.php3</li> * <li>index.cgi</li> * <li>placeholder.html</li> * <li>default.asp</li> * </ul> * <p><b>Please Note:</b> There are no guarantees a URL without its * index files will be semantically equivalent, or even be valid.</p> * @return this instance */ public URLNormalizer removeDirectoryIndex() { String path = toURI(url).getPath(); if (PATTERN_PATH_LAST_SEGMENT.matcher(path).matches()) { url = StringUtils.replaceOnce(url, path, StringUtils.substringBeforeLast(path, "/") + "/"); } return this; }
From source file:com.clickha.nifi.processors.FetchFileTransferV2.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { FlowFile flowFile = session.get();/* w w w . ja v a2 s.c om*/ if (flowFile == null) { return; } final StopWatch stopWatch = new StopWatch(true); final String host = context.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue(); final int port = context.getProperty(UNDEFAULTED_PORT).evaluateAttributeExpressions(flowFile).asInteger(); final String filename = context.getProperty(REMOTE_FILENAME).evaluateAttributeExpressions(flowFile) .getValue(); // Try to get a FileTransfer object from our cache. BlockingQueue<FileTransferIdleWrapper> transferQueue; synchronized (fileTransferMap) { final Tuple<String, Integer> tuple = new Tuple<>(host, port); transferQueue = fileTransferMap.get(tuple); if (transferQueue == null) { transferQueue = new LinkedBlockingQueue<>(); fileTransferMap.put(tuple, transferQueue); } // periodically close idle connections if (System.currentTimeMillis() - lastClearTime > IDLE_CONNECTION_MILLIS) { closeConnections(false); lastClearTime = System.currentTimeMillis(); } } // we have a queue of FileTransfer Objects. Get one from the queue or create a new one. FileTransferV2 transfer; FileTransferIdleWrapper transferWrapper = transferQueue.poll(); if (transferWrapper == null) { transfer = createFileTransfer(context); } else { transfer = transferWrapper.getFileTransfer(); } // Pull data from remote system. final InputStream in; try { in = transfer.getInputStream(filename, flowFile); flowFile = session.write(flowFile, new OutputStreamCallback() { @Override public void process(final OutputStream out) throws IOException { StreamUtils.copy(in, out); transfer.flush(); } }); transferQueue.offer(new FileTransferIdleWrapper(transfer, System.nanoTime())); } catch (final FileNotFoundException e) { getLogger().error( "Failed to fetch content for {} from filename {} on remote host {} because the file could not be found on the remote system; routing to {}", new Object[] { flowFile, filename, host, REL_NOT_FOUND.getName() }); session.transfer(session.penalize(flowFile), REL_NOT_FOUND); session.getProvenanceReporter().route(flowFile, REL_NOT_FOUND); return; } catch (final PermissionDeniedException e) { getLogger().error( "Failed to fetch content for {} from filename {} on remote host {} due to insufficient permissions; routing to {}", new Object[] { flowFile, filename, host, REL_PERMISSION_DENIED.getName() }); session.transfer(session.penalize(flowFile), REL_PERMISSION_DENIED); session.getProvenanceReporter().route(flowFile, REL_PERMISSION_DENIED); return; } catch (final ProcessException | IOException e) { try { transfer.close(); } catch (final IOException e1) { getLogger().warn("Failed to close connection to {}:{} due to {}", new Object[] { host, port, e.toString() }, e); } getLogger().error( "Failed to fetch content for {} from filename {} on remote host {}:{} due to {}; routing to comms.failure", new Object[] { flowFile, filename, host, port, e.toString() }, e); session.transfer(session.penalize(flowFile), REL_COMMS_FAILURE); return; } // Add FlowFile attributes final String protocolName = transfer.getProtocolName(); final Map<String, String> attributes = new HashMap<>(); attributes.put(protocolName + ".remote.host", host); attributes.put(protocolName + ".remote.port", String.valueOf(port)); attributes.put(protocolName + ".remote.filename", filename); if (filename.contains("/")) { final String path = StringUtils.substringBeforeLast(filename, "/"); final String filenameOnly = StringUtils.substringAfterLast(filename, "/"); attributes.put(CoreAttributes.PATH.key(), path); attributes.put(CoreAttributes.FILENAME.key(), filenameOnly); } else { attributes.put(CoreAttributes.FILENAME.key(), filename); } flowFile = session.putAllAttributes(flowFile, attributes); // emit provenance event and transfer FlowFile session.getProvenanceReporter().fetch(flowFile, protocolName + "://" + host + ":" + port + "/" + filename, stopWatch.getElapsed(TimeUnit.MILLISECONDS)); session.transfer(flowFile, REL_SUCCESS); // it is critical that we commit the session before moving/deleting the remote file. Otherwise, we could have a situation where // we ingest the data, delete/move the remote file, and then NiFi dies/is shut down before the session is committed. This would // result in data loss! If we commit the session first, we are safe. session.commit(); final String completionStrategy = context.getProperty(COMPLETION_STRATEGY).getValue(); if (COMPLETION_DELETE.getValue().equalsIgnoreCase(completionStrategy)) { try { transfer.deleteFile(null, filename); } catch (final FileNotFoundException e) { // file doesn't exist -- effectively the same as removing it. Move on. } catch (final IOException ioe) { getLogger().warn( "Successfully fetched the content for {} from {}:{}{} but failed to remove the remote file due to {}", new Object[] { flowFile, host, port, filename, ioe }, ioe); } } else if (COMPLETION_MOVE.getValue().equalsIgnoreCase(completionStrategy)) { String targetDir = context.getProperty(MOVE_DESTINATION_DIR).evaluateAttributeExpressions(flowFile) .getValue(); if (!targetDir.endsWith("/")) { targetDir = targetDir + "/"; } final String simpleFilename = StringUtils.substringAfterLast(filename, "/"); final String target = targetDir + simpleFilename; try { transfer.rename(filename, target); } catch (final IOException ioe) { getLogger().warn( "Successfully fetched the content for {} from {}:{}{} but failed to rename the remote file due to {}", new Object[] { flowFile, host, port, filename, ioe }, ioe); } } }
From source file:io.wcm.handler.richtext.impl.RichTextRewriteContentHandlerImpl.java
/** * Support legacy data structures where link metadata is stored as JSON fragment in rel attribute. * @param pResourceProps Valuemap to write link metadata to * @param element Link element/*from w w w. j a v a 2s . co m*/ */ private void getAnchorLegacyMetadataFromRel(ValueMap pResourceProps, Element element) { // Check href attribute - do not change elements with no href or links to anchor names String href = element.getAttributeValue("href"); String linkWindowTarget = element.getAttributeValue("target"); if (href == null || href.startsWith("#")) { return; } // get link metadata from rel element JSONObject metadata = null; String metadataString = element.getAttributeValue("rel"); if (StringUtils.isNotEmpty(metadataString)) { try { metadata = new JSONObject(metadataString); } catch (JSONException ex) { RichTextHandlerImpl.log.debug("Invalid link metadata: " + metadataString, ex); } } if (metadata == null) { metadata = new JSONObject(); } // transform link metadata to virtual JCR resource with JCR properties JSONArray metadataPropertyNames = metadata.names(); if (metadataPropertyNames != null) { for (int i = 0; i < metadataPropertyNames.length(); i++) { String metadataPropertyName = metadataPropertyNames.optString(i); // check if value is array JSONArray valueArray = metadata.optJSONArray(metadataPropertyName); if (valueArray != null) { // store array values List<String> values = new ArrayList<String>(); for (int j = 0; j < valueArray.length(); j++) { values.add(valueArray.optString(j)); } pResourceProps.put(metadataPropertyName, values.toArray(new String[values.size()])); } else { // store simple value Object value = metadata.opt(metadataPropertyName); if (value != null) { pResourceProps.put(metadataPropertyName, value); } } } } // detect link type LinkType linkType = null; String linkTypeString = pResourceProps.get(LinkNameConstants.PN_LINK_TYPE, String.class); for (Class<? extends LinkType> candidateClass : linkHandlerConfig.getLinkTypes()) { LinkType candidate = AdaptTo.notNull(adaptable, candidateClass); if (StringUtils.isNotEmpty(linkTypeString)) { if (StringUtils.equals(linkTypeString, candidate.getId())) { linkType = candidate; break; } } else if (candidate.accepts(href)) { linkType = candidate; break; } } if (linkType == null) { // skip further processing if link type was not detected return; } // workaround: strip off ".html" extension if it was added automatically by the RTE if (linkType instanceof InternalLinkType || linkType instanceof MediaLinkType) { String htmlSuffix = "." + FileExtension.HTML; if (StringUtils.endsWith(href, htmlSuffix)) { href = StringUtils.substringBeforeLast(href, htmlSuffix); } } // store link reference (property depending on link type) pResourceProps.put(linkType.getPrimaryLinkRefProperty(), href); pResourceProps.put(LinkNameConstants.PN_LINK_WINDOW_TARGET, linkWindowTarget); }
From source file:com.adobe.acs.commons.mcp.impl.processes.asset.AssetIngestor.java
protected CheckedConsumer<ResourceResolver> importAsset(final Source source, ActionManager actionManager) { return (ResourceResolver r) -> { createFolderNode(source.getElement().getParent(), r); actionManager.setCurrentItem(source.getElement().getItemName()); HierarchialElement el = source.getElement(); String path = source.getElement().getNodePath(); if (null != el && el.isFile() && el.getName().contains(".") && !preserveFileName) { String baseName = StringUtils.substringBeforeLast(el.getName(), "."); String extension = StringUtils.substringAfterLast(el.getName(), "."); path = (el.getParent() == null ? el.getJcrBasePath() : el.getParent().getNodePath()) + "/" + JcrUtil.createValidName(baseName, JcrUtil.HYPHEN_LABEL_CHAR_MAPPING, "-") + "." + JcrUtil.createValidName(extension, JcrUtil.HYPHEN_LABEL_CHAR_MAPPING, "-"); }//w ww. j a v a2 s. co m handleExistingAsset(source, path, r); }; }
From source file:com.clarkparsia.empire.annotation.RdfGenerator.java
@SuppressWarnings("unchecked") private static <T> Class<T> determineClass(Class<T> theOrigClass, T theObj, DataSource theSource, boolean instanceClass) throws InvalidRdfException, DataSourceException { Class aResult = theOrigClass; final SupportsRdfId aTmpSupportsRdfId = asSupportsRdfId(theObj); // ExtGraph aGraph = new ExtGraph(DataSourceUtil.describe(theSource, theObj)); // ======================================== start speedup PATCH ================================================== // get class from uri without quering db // final Collection<Value> aTypes = DataSourceUtil.getValues(theSource, EmpireUtil.asResource(EmpireUtil.asSupportsRdfId(theObj)), RDF.TYPE); String rdfId = EmpireUtil.asSupportsRdfId(theObj).getRdfId().toString(); final Collection<Value> aTypes = Collections .singletonList(new URIImpl(StringUtils.substringBeforeLast(rdfId, ":"))); // ======================================== end speedup PATCH ======================================== // right now, our best match is the original class (we will refine later) // final Resource aTmpRes = EmpireUtil.asResource(aTmpSupportsRdfId); // iterate for all rdf:type triples in the data // There may be multiple rdf:type triples, which can then translate onto multiple candidate Java classes // some of the Java classes may belong to the same class hierarchy, whereas others can have no common // super class (other than java.lang.Object) for (Value aValue : aTypes) { if (!(aValue instanceof URI)) { // there is no URI in the object position of rdf:type // ignore that data continue; }//from ww w.j a va 2s. c om URI aType = (URI) aValue; for (Class aCandidateClass : TYPE_TO_CLASS.get(aType)) { if (aCandidateClass.equals(aResult)) { // it is mapped to the same Java class, that we have; ignore continue; } // at this point we found an rdf:type triple that resolves to a different Java class than we have // we are only going to accept this candidate class if it is a subclass of the current Java class // (doing otherwise, may cause class cast exceptions) if (aResult.isAssignableFrom(aCandidateClass)) { aResult = aCandidateClass; } } } try { if (instanceClass) { if (aResult.isInterface() || Modifier.isAbstract(aResult.getModifiers()) || !EmpireGenerated.class.isAssignableFrom(aResult)) { aResult = com.clarkparsia.empire.codegen.InstanceGenerator.generateInstanceClass(aResult); } } } catch (Exception e) { throw new InvalidRdfException("Cannot generate a class for a bean", e); } return aResult; }