List of usage examples for org.apache.commons.lang3 StringUtils substringAfterLast
public static String substringAfterLast(final String str, final String separator)
Gets the substring after the last occurrence of a separator.
From source file:com.thinkbiganalytics.nifi.rest.model.flow.NifiFlowProcessor.java
/** * Assign a flow identifier to the processor. Flow ids are an attempt to assign a id relative the the location of the processor in the graph as it is walked so different instances of the same * flow/template can relate given processors to each other * * @param flowId the id representing its placement in the graph * @return the assigned numeric id//w w w . j av a 2 s. c o m */ public Integer assignFlowIds(Integer flowId) { flowId++; setFlowId(flowId + "__" + StringUtils.substringAfterLast(this.type, ".")); Set<String> printed = new HashSet<>(); printed.add(this.getId()); for (NifiFlowProcessor child : getSortedDestinations()) { if (StringUtils.isBlank(child.getFlowId()) && !child.containsDestination(this) && !child.containsDestination(child) && !child.equals(this) && !printed.contains(child.getId())) { flowId = child.assignFlowIds(flowId); printed.add(child.getId()); } } return flowId; }
From source file:com.utdallas.s3lab.smvhunter.monkey.MonkeyMe.java
/** * /* w ww. ja v a2 s.com*/ * @throws IOException */ private static void readFromSmartInputText() throws IOException { Iterator<String> lineIter = FileUtils.lineIterator(new File(smartInputLocation)); while (lineIter.hasNext()) { String line = lineIter.next(); String[] info = line.split(";"); String methName = info[0]; //name of the method String inputName = StringUtils.substringAfterLast(info[1], "name: "); String inputId = StringUtils.substringAfterLast(info[2], "id: "); String inputType = StringUtils.substringAfterLast(info[3], "type: "); String inputVar = StringUtils.substringAfterLast(info[4], "variations: "); String inputFlag = StringUtils.substringAfterLast(info[5], "flags: "); if (resultFromSmartInputGeneration.containsKey(methName)) { List<SmartInputBean> list = resultFromSmartInputGeneration.get(methName); list.add(new SmartInputBean(inputName, inputId, inputType, inputVar, inputFlag)); } else { List<SmartInputBean> list = new ArrayList<SmartInputBean>(); list.add(new SmartInputBean(inputName, inputId, inputType, inputVar, inputFlag)); resultFromSmartInputGeneration.put(methName, list); } } }
From source file:info.magnolia.ui.form.field.upload.AbstractUploadField.java
/** * Drop zone Handler.//from w w w . ja v a 2s. c o m */ @Override public void drop(DragAndDropEvent event) { final DragAndDropWrapper.WrapperTransferable transferable = (WrapperTransferable) event.getTransferable(); final Html5File[] files = transferable.getFiles(); if (files == null) { return; } // start polling immediately on drop startPolling(); for (final Html5File html5File : files) { html5File.setStreamVariable(new StreamVariable() { private String name; private String mime; @Override public OutputStream getOutputStream() { return getValue().receiveUpload(name, mime); } @Override public boolean listenProgress() { return true; } @Override public void onProgress(StreamingProgressEvent event) { updateProgress(event.getBytesReceived(), event.getContentLength()); } @Override public void streamingStarted(StreamingStartEvent event) { setDragAndDropUploadInterrupted(false); name = event.getFileName(); mime = event.getMimeType(); if (StringUtils.isEmpty(mime)) { String extension = StringUtils.substringAfterLast(name, "."); mime = MIMEMapping.getMIMEType(extension); if (StringUtils.isEmpty(mime)) { log.warn("Couldn't find mimeType in MIMEMappings for file extension: {}", extension); } } StartedEvent startEvent = new StartedEvent(upload, name, mime, event.getContentLength()); uploadStarted(startEvent); } @Override public void streamingFinished(StreamingEndEvent event) { FinishedEvent uploadEvent = new FinishedEvent(upload, event.getFileName(), event.getMimeType(), event.getContentLength()); uploadFinished(uploadEvent); } @Override public void streamingFailed(StreamingErrorEvent event) { FailedEvent failedEvent = new FailedEvent(upload, event.getFileName(), event.getMimeType(), event.getContentLength()); uploadFailed(failedEvent); setDragAndDropUploadInterrupted(false); } @Override public synchronized boolean isInterrupted() { return isDragAndDropUploadInterrupted(); } }); } }
From source file:com.xpn.xwiki.web.UploadAction.java
/** * Extract the corresponding attachment name for a given file field. It can either be specified in a separate form * input field, or it is extracted from the original filename. * //from w w w . j av a 2s.c om * @param fieldName the target file field * @param fileupload the {@link FileUploadPlugin} holding the form data * @param context the current request context * @return a valid attachment name * @throws XWikiException if the form data cannot be accessed, or if the specified filename is invalid */ protected String getFileName(String fieldName, FileUploadPlugin fileupload, XWikiContext context) throws XWikiException { String filenameField = FILENAME_FIELD_NAME + fieldName.substring(FILE_FIELD_NAME.length()); String filename = null; // Try to use the name provided by the user filename = fileupload.getFileItemAsString(filenameField, context); if (!StringUtils.isBlank(filename)) { // TODO These should be supported, the URL should just contain escapes. if (filename.indexOf("/") != -1 || filename.indexOf("\\") != -1 || filename.indexOf(";") != -1) { throw new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_INVALID_CHARS, "Invalid filename: " + filename); } } if (StringUtils.isBlank(filename)) { // Try to get the actual filename on the client String fname = fileupload.getFileName(fieldName, context); if (StringUtils.indexOf(fname, "/") >= 0) { fname = StringUtils.substringAfterLast(fname, "/"); } if (StringUtils.indexOf(fname, "\\") >= 0) { fname = StringUtils.substringAfterLast(fname, "\\"); } filename = fname; } // Sometimes spaces are replaced with '+' by the browser. filename = filename.replaceAll("\\+", " "); if (StringUtils.isBlank(filename)) { // The file field was left empty, ignore this return null; } // Issues fixed by the clearName : // 1) Attaching images with a name containing special characters generates bugs // (image are not displayed), XWIKI-2090. // 2) Attached files that we can't delete or link in the Wiki pages, XWIKI-2087. filename = context.getWiki().clearName(filename, false, true, context); return filename; }
From source file:com.gargoylesoftware.htmlunit.javascript.DebugFrameImpl.java
/** * Returns the name of this frame's source. * * @return the name of this frame's source *//*from www .jav a 2s. co m*/ private String getSourceName(final Context cx) { String source = (String) cx.getThreadLocal(KEY_LAST_SOURCE); if (source == null) { return "unknown"; } // only the file name is interesting the rest of the url is mostly noise source = StringUtils.substringAfterLast(source, "/"); // embedded scripts have something like "foo.html from (3, 10) to (10, 13)" source = StringUtils.substringBefore(source, " "); return source; }
From source file:com.netflix.genie.web.services.loadbalancers.script.ScriptLoadBalancer.java
/** * Check if the script file needs to be refreshed. *//*from w w w. j a v a 2 s .com*/ public void refresh() { log.debug("Refreshing"); final long updateStart = System.nanoTime(); final Set<Tag> tags = Sets.newHashSet(); try { this.isUpdating.set(true); // Update the script timeout this.timeoutLength.set(this.environment.getProperty(ScriptLoadBalancerProperties.TIMEOUT_PROPERTY, Long.class, DEFAULT_TIMEOUT_LENGTH)); final String scriptFileSourceValue = this.environment .getProperty(ScriptLoadBalancerProperties.SCRIPT_FILE_SOURCE_PROPERTY); if (StringUtils.isBlank(scriptFileSourceValue)) { throw new IllegalStateException("Invalid empty value for script source file property: " + ScriptLoadBalancerProperties.SCRIPT_FILE_SOURCE_PROPERTY); } final String scriptFileSource = new URI(scriptFileSourceValue).toString(); final String scriptFileDestinationValue = this.environment .getProperty(ScriptLoadBalancerProperties.SCRIPT_FILE_DESTINATION_PROPERTY); if (StringUtils.isBlank(scriptFileDestinationValue)) { throw new IllegalStateException("Invalid empty value for script destination directory property: " + ScriptLoadBalancerProperties.SCRIPT_FILE_DESTINATION_PROPERTY); } final Path scriptDestinationDirectory = Paths.get(new URI(scriptFileDestinationValue)); // Check the validity of the destination directory if (!Files.exists(scriptDestinationDirectory)) { Files.createDirectories(scriptDestinationDirectory); } else if (!Files.isDirectory(scriptDestinationDirectory)) { throw new IllegalStateException("The script destination directory " + scriptDestinationDirectory + " exists but is not a directory"); } final String fileName = StringUtils.substringAfterLast(scriptFileSource, SLASH); if (StringUtils.isBlank(fileName)) { throw new IllegalStateException("No file name found from " + scriptFileSource); } final String scriptExtension = StringUtils.substringAfterLast(fileName, PERIOD); if (StringUtils.isBlank(scriptExtension)) { throw new IllegalStateException("No file extension available in " + fileName); } final Path scriptDestinationPath = scriptDestinationDirectory.resolve(fileName); // Download and cache the file (if it's not already there) this.fileTransferService.getFile(scriptFileSource, scriptDestinationPath.toUri().toString()); final ScriptEngine engine = this.scriptEngineManager.getEngineByExtension(scriptExtension); // We want a compilable engine so we can cache the script if (!(engine instanceof Compilable)) { throw new IllegalArgumentException("Script engine must be of type " + Compilable.class.getName()); } final Compilable compilable = (Compilable) engine; try (InputStream fis = Files.newInputStream(scriptDestinationPath); InputStreamReader reader = new InputStreamReader(fis, UTF_8)) { log.debug("Compiling {}", scriptFileSource); this.script.set(compilable.compile(reader)); } tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, STATUS_TAG_OK)); this.isConfigured.set(true); } catch (final GenieException | IOException | ScriptException | RuntimeException | URISyntaxException e) { tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, STATUS_TAG_FAILED)); tags.add(Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, e.getClass().getName())); log.error("Refreshing the load balancing script for ScriptLoadBalancer failed due to {}", e.getMessage(), e); this.isConfigured.set(false); } finally { this.isUpdating.set(false); this.registry.timer(UPDATE_TIMER_NAME, tags).record(System.nanoTime() - updateStart, TimeUnit.NANOSECONDS); log.debug("Refresh completed"); } }
From source file:de.blizzy.backup.database.Database.java
public void initialize() { try {/*www. ja v a 2 s.c o m*/ int sha256Length = DigestUtils.sha256Hex(StringUtils.EMPTY).length(); factory.query("CREATE TABLE IF NOT EXISTS backups (" + //$NON-NLS-1$ "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, " + //$NON-NLS-1$ "run_time DATETIME NOT NULL, " + //$NON-NLS-1$ "num_entries INT NULL" + //$NON-NLS-1$ ")") //$NON-NLS-1$ .execute(); int sampleBackupPathLength = Utils.createSampleBackupFilePath().length(); factory.query("CREATE TABLE IF NOT EXISTS files (" + //$NON-NLS-1$ "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, " + //$NON-NLS-1$ "backup_path VARCHAR(" + sampleBackupPathLength + ") NOT NULL, " + //$NON-NLS-1$ //$NON-NLS-2$ "checksum VARCHAR(" + sha256Length + ") NOT NULL, " + //$NON-NLS-1$ //$NON-NLS-2$ "length BIGINT NOT NULL, " + //$NON-NLS-1$ "compression TINYINT NOT NULL" + //$NON-NLS-1$ ")") //$NON-NLS-1$ .execute(); factory.query("CREATE INDEX IF NOT EXISTS idx_old_files ON files " + //$NON-NLS-1$ "(checksum, length)") //$NON-NLS-1$ .execute(); factory.query("CREATE TABLE IF NOT EXISTS entries (" + //$NON-NLS-1$ "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, " + //$NON-NLS-1$ "parent_id INT NULL, " + //$NON-NLS-1$ "backup_id INT NOT NULL, " + //$NON-NLS-1$ "type TINYINT NOT NULL, " + //$NON-NLS-1$ "creation_time DATETIME NULL, " + //$NON-NLS-1$ "modification_time DATETIME NULL, " + //$NON-NLS-1$ "hidden BOOLEAN NOT NULL, " + //$NON-NLS-1$ "name VARCHAR(1024) NOT NULL, " + //$NON-NLS-1$ "name_lower VARCHAR(1024) NOT NULL, " + //$NON-NLS-1$ "file_id INT NULL" + //$NON-NLS-1$ ")") //$NON-NLS-1$ .execute(); factory.query("CREATE INDEX IF NOT EXISTS idx_entries_files ON entries " + //$NON-NLS-1$ "(file_id)") //$NON-NLS-1$ .execute(); factory.query("CREATE INDEX IF NOT EXISTS idx_folder_entries ON entries " + //$NON-NLS-1$ "(backup_id, parent_id)") //$NON-NLS-1$ .execute(); factory.query("DROP INDEX IF EXISTS idx_entries_names") //$NON-NLS-1$ .execute(); factory.query("CREATE INDEX IF NOT EXISTS idx_entries_names2 ON entries " + //$NON-NLS-1$ "(name, backup_id, parent_id)") //$NON-NLS-1$ .execute(); if (!isTableColumnExistent("FILES", "COMPRESSION")) { //$NON-NLS-1$ //$NON-NLS-2$ factory.query( "ALTER TABLE files ADD compression TINYINT NULL DEFAULT " + Compression.GZIP.getValue()) //$NON-NLS-1$ .execute(); factory.update(Tables.FILES) .set(Tables.FILES.COMPRESSION, Byte.valueOf((byte) Compression.GZIP.getValue())).execute(); factory.query("ALTER TABLE files ALTER COLUMN compression TINYINT NOT NULL") //$NON-NLS-1$ .execute(); } if (getTableColumnSize("FILES", "CHECKSUM") != sha256Length) { //$NON-NLS-1$ //$NON-NLS-2$ factory.query("ALTER TABLE files ALTER COLUMN " + //$NON-NLS-1$ "checksum VARCHAR(" + sha256Length + ") NOT NULL") //$NON-NLS-1$ //$NON-NLS-2$ .execute(); } if (!isTableColumnExistent("ENTRIES", "NAME_LOWER")) { //$NON-NLS-1$ //$NON-NLS-2$ factory.query("ALTER TABLE entries ADD name_lower VARCHAR(1024) NULL") //$NON-NLS-1$ .execute(); factory.update(Tables.ENTRIES).set(Tables.ENTRIES.NAME_LOWER, Tables.ENTRIES.NAME.lower()) .execute(); factory.query("ALTER TABLE entries ALTER COLUMN name_lower VARCHAR(1024) NOT NULL") //$NON-NLS-1$ .execute(); } factory.query("CREATE INDEX IF NOT EXISTS idx_entries_search ON entries " + //$NON-NLS-1$ "(backup_id, name_lower)") //$NON-NLS-1$ .execute(); if (getTableColumnSize("FILES", "BACKUP_PATH") != sampleBackupPathLength) { //$NON-NLS-1$ //$NON-NLS-2$ Cursor<Record> cursor = null; try { cursor = factory.select(Tables.FILES.ID, Tables.FILES.BACKUP_PATH).from(Tables.FILES) .fetchLazy(); while (cursor.hasNext()) { Record record = cursor.fetchOne(); String backupPath = record.getValue(Tables.FILES.BACKUP_PATH); String backupFileName = StringUtils.substringAfterLast(backupPath, "/"); //$NON-NLS-1$ if (backupFileName.indexOf('-') > 0) { Integer id = record.getValue(Tables.FILES.ID); File backupFile = Utils.toBackupFile(backupPath, outputFolder); File folder = backupFile.getParentFile(); int maxIdx = Utils.getMaxBackupFileIndex(folder); int newIdx = maxIdx + 1; String newBackupFileName = Utils.toBackupFileName(newIdx); File newBackupFile = new File(folder, newBackupFileName); FileUtils.moveFile(backupFile, newBackupFile); String newBackupPath = StringUtils.substringBeforeLast(backupPath, "/") + "/" //$NON-NLS-1$//$NON-NLS-2$ + newBackupFileName; factory.update(Tables.FILES).set(Tables.FILES.BACKUP_PATH, newBackupPath) .where(Tables.FILES.ID.equal(id)).execute(); } } factory.query("ALTER TABLE files ALTER COLUMN backup_path VARCHAR(" + sampleBackupPathLength //$NON-NLS-1$ + ") NOT NULL") //$NON-NLS-1$ .execute(); } finally { closeQuietly(cursor); } } factory.query("ANALYZE") //$NON-NLS-1$ .execute(); } catch (SQLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.norconex.commons.lang.url.URLNormalizer.java
/** * <p>Adds a trailing slash (/) to a URL ending with a directory. A URL is * considered to end with a directory if the last path segment, * before fragment (#) or query string (?), does not contain a dot, * typically representing an extension.</p> * // w w w . j ava 2 s . c om * <p><b>Please Note:</b> URLs do not always denote a directory structure * and many URLs can qualify to this method without truly representing a * directory. Adding a trailing slash to these URLs could potentially break * its semantic equivalence.</p> * <code>http://www.example.com/alice → * http://www.example.com/alice/</code> * @return this instance */ public URLNormalizer addTrailingSlash() { String name = StringUtils.substringAfterLast(url, "/"); if (!name.contains(".") && !StringUtils.endsWith(name, "/")) { url = url + "/"; } return this; }
From source file:com.netflix.spinnaker.clouddriver.ecs.services.EcsCloudMetricService.java
private Set<String> putScalingPolicies(AWSApplicationAutoScaling autoScalingClient, List<String> actionArns, String serviceName, String resourceId, String type, String suffix) { if (actionArns.isEmpty()) { return Collections.emptySet(); }//from w w w .java 2 s. c o m Set<ScalingPolicy> scalingPolicies = new HashSet<>(); String nextToken = null; do { DescribeScalingPoliciesRequest request = new DescribeScalingPoliciesRequest().withPolicyNames( actionArns.stream().map(arn -> StringUtils.substringAfterLast(arn, ":policyName/")) .collect(Collectors.toSet())) .withServiceNamespace(ServiceNamespace.Ecs); if (nextToken != null) { request.setNextToken(nextToken); } DescribeScalingPoliciesResult result = autoScalingClient.describeScalingPolicies(request); scalingPolicies.addAll(result.getScalingPolicies()); nextToken = result.getNextToken(); } while (nextToken != null && nextToken.length() != 0); Set<String> policyArns = new HashSet<>(); for (ScalingPolicy scalingPolicy : scalingPolicies) { String newPolicyName = serviceName + "-" + type + "-" + suffix; ScalingPolicy clone = scalingPolicy.clone(); clone.setPolicyName(newPolicyName); clone.setResourceId(resourceId); PutScalingPolicyResult result = autoScalingClient.putScalingPolicy(buildPutScalingPolicyRequest(clone)); policyArns.add(result.getPolicyARN()); } return policyArns; }
From source file:com.inkubator.hrm.web.ImageBioDataStreamerController.java
public StreamedContent getAttachmentFile() throws IOException { FacesContext context = FacesUtil.getFacesContext(); String id = context.getExternalContext().getRequestParameterMap().get("permitId"); if (context.getRenderResponse() || id == null) { return new DefaultStreamedContent(); } else {/*from w ww . ja v a 2 s .c o m*/ InputStream is = null; try { PermitImplementation permitImplementation = permitImplementationService .getEntiyByPK(Long.parseLong(id)); String path = permitImplementation.getUploadPath(); if (StringUtils.isEmpty(path)) { path = facesIO.getPathUpload() + "no_image.png"; } is = facesIO.getInputStreamFromURL(path); return new DefaultStreamedContent(is, null, StringUtils.substringAfterLast(path, "/")); } catch (Exception ex) { LOGGER.error(ex, ex); return new DefaultStreamedContent(); } } }