List of usage examples for org.apache.commons.lang StringUtils substringAfterLast
public static String substringAfterLast(String str, String separator)
Gets the substring after the last occurrence of a separator.
From source file:info.magnolia.module.admininterface.AdminTreeMVCHandler.java
public void deleteNode(String path) throws Exception { String parentPath = StringUtils.substringBeforeLast(path, "/"); //$NON-NLS-1$ String label = StringUtils.substringAfterLast(path, "/"); //$NON-NLS-1$ deleteNode(parentPath, label);/*from w w w .j a v a2s . co m*/ }
From source file:com.homeadvisor.kafdrop.service.CuratorKafkaMonitor.java
public TopicVO parseZkTopic(ChildData input) { try {//w w w . ja v a 2 s .c om final TopicVO topic = new TopicVO(StringUtils.substringAfterLast(input.getPath(), "/")); final TopicRegistrationVO topicRegistration = objectMapper.reader(TopicRegistrationVO.class) .readValue(input.getData()); topic.setConfig(Optional .ofNullable( topicConfigPathCache.getCurrentData(ZkUtils.TopicConfigPath() + "/" + topic.getName())) .map(this::readTopicConfig).orElse(Collections.emptyMap())); for (Map.Entry<Integer, List<Integer>> entry : topicRegistration.getReplicas().entrySet()) { final int partitionId = entry.getKey(); final List<Integer> partitionBrokerIds = entry.getValue(); final TopicPartitionVO partition = new TopicPartitionVO(partitionId); final TopicPartitionStateVO partitionState = partitionState(topic.getName(), partition.getId()); partitionBrokerIds.stream().map(brokerId -> { TopicPartitionVO.PartitionReplica replica = new TopicPartitionVO.PartitionReplica(); replica.setId(brokerId); replica.setInService(partitionState.getIsr().contains(brokerId)); replica.setLeader(brokerId == partitionState.getLeader()); return replica; }).forEach(partition::addReplica); topic.addPartition(partition); } // todo: get partition sizes here as single bulk request? return topic; } catch (IOException e) { throw Throwables.propagate(e); } }
From source file:eionet.cr.web.action.HarvestSourceActionBean.java
/** * @throws DAOException//w ww. j a v a 2s . c o m */ @ValidationMethod(on = { "export" }) public void validateSaveEvent() throws DAOException { // the below validation is relevant only when exported to HOMESPACE if (exportType == null || ExportType.FILE.toString().equals(exportType)) { return; } // for all the above POST events, user must be authorized if (getUser() == null) { addGlobalValidationError("User not logged in!"); return; } // no folder selected if (StringUtils.isBlank(folder)) { addGlobalValidationError("Folder not selected!"); return; } // Check if file already exists // If datasetName not provided, then extract it from source url if (StringUtils.isBlank(datasetName)) { datasetName = StringUtils.substringAfterLast(harvestSource.getUrl(), "/"); } if (!overwriteDataset && !StringUtils.isBlank(datasetName) && !StringUtils.isBlank(folder)) { String datasetUri = folder + "/" + StringUtils.replace(datasetName, " ", "%20"); boolean exists = DAOFactory.get().getDao(FolderDAO.class).fileOrFolderExists(datasetUri); if (exists) { addGlobalValidationError( "File named \"" + datasetName + "\" already exists in folder \"" + folder + "\"!"); } } folders = FolderUtil.getUserAccessibleFolders(getUser()); // if any validation errors were set above, make sure the right resolution is returned if (hasValidationErrors()) { Resolution resolution = new ForwardResolution("/pages/export.jsp"); getContext().setSourcePageResolution(resolution); } }
From source file:com.contrastsecurity.ide.eclipse.ui.internal.model.RecommendationTab.java
private void insertTextBlock(Composite composite, String text) { if (text != null && !text.isEmpty()) { String[] links = StringUtils.substringsBetween(text, Constants.OPEN_TAG_LINK, Constants.CLOSE_TAG_LINK); if (links != null && links.length > 0) { String[] textBlocks = StringUtils.substringsBetween(text, Constants.CLOSE_TAG_LINK, Constants.OPEN_TAG_LINK); String textBlockFirst = StringUtils.substringBefore(text, Constants.OPEN_TAG_LINK); String textBlockLast = StringUtils.substringAfterLast(text, Constants.CLOSE_TAG_LINK); createStyledTextBlock(composite, parseMustache(textBlockFirst)); for (int i = 0; i < links.length; i++) { int indexOfDelimiter = links[i].indexOf(Constants.LINK_DELIM); String formattedLink = "<a href=\"" + links[i].substring(0, indexOfDelimiter) + "\">" + links[i].substring(indexOfDelimiter + Constants.LINK_DELIM.length()) + "</a>"; createLink(composite, formattedLink); if (textBlocks != null && textBlocks.length > 0 && i < links.length - 1) { createStyledTextBlock(composite, parseMustache(textBlocks[i])); }//from www . j a v a 2 s. c om } createStyledTextBlock(composite, parseMustache(textBlockLast)); } else { createStyledTextBlock(composite, parseMustache(text)); } } }
From source file:com.rsmart.kuali.kfs.sys.batch.service.impl.BatchFeedHelperServiceImpl.java
/** * @see com.rsmart.kuali.kfs.sys.batch.service.BatchFeedHelperService#loadDocumentAttachments(org.kuali.kfs.kns.document.Document, * java.util.List, java.lang.String, java.lang.String, org.kuali.kfs.kns.util.ErrorMap) *///from ww w . j av a 2 s .c o m public void loadDocumentAttachments(Document document, List<Attachment> attachments, String attachmentsPath, String attachmentType, MessageMap errorMap) { for (Attachment attachment : attachments) { Note note = new Note(); note.setNoteText( kualiConfigurationService.getPropertyValueAsString(KFSKeyConstants.IMAGE_ATTACHMENT_NOTE_TEXT)); note.setRemoteObjectIdentifier(document.getObjectId()); note.setAuthorUniversalIdentifier(getSystemUser().getPrincipalId()); note.setNoteTypeCode(KFSConstants.NoteTypeEnum.BUSINESS_OBJECT_NOTE_TYPE.getCode()); note.setNotePostedTimestampToCurrent(); // attempt to load file String fileName = attachmentsPath + "/" + attachment.getAttachmentFileName(); File attachmentFile = new File(fileName); if (!attachmentFile.exists()) { errorMap.putError(KFSConstants.GLOBAL_ERRORS, KFSKeyConstants.ERROR_BATCH_FEED_ATTACHMENT, new String[] { attachment.getAttachmentFileName(), attachmentsPath }); continue; } try { FileInputStream fileInputStream = new FileInputStream(fileName); Integer fileSize = Integer.parseInt(Long.toString(attachmentFile.length())); String mimeTypeCode = attachment.getAttachmentMimeTypeCode(); String fileExtension = "." + StringUtils.substringAfterLast(fileName, "."); if (StringUtils.isNotBlank(fileExtension) && mimeTypeProperties.containsKey(fileExtension)) { if (StringUtils.isBlank(mimeTypeCode)) { mimeTypeCode = mimeTypeProperties.getProperty(fileExtension); } } else { errorMap.putError(KFSConstants.GLOBAL_ERRORS, KFSKeyConstants.ERROR_BATCH_FEED_ATTACHMENT_TYPE, new String[] { fileName, fileExtension }); } Attachment noteAttachment = attachmentService.createAttachment(document.getDocumentHeader(), fileName, mimeTypeCode, fileSize, fileInputStream, attachmentType); note.addAttachment(noteAttachment); document.addNote(note); } catch (FileNotFoundException e) { errorMap.putError(KFSConstants.GLOBAL_ERRORS, KFSKeyConstants.ERROR_BATCH_FEED_ATTACHMENT, new String[] { attachment.getAttachmentFileName(), attachmentsPath }); continue; } catch (IOException e1) { throw new RuntimeException("Unable to create attachment for image: " + fileName, e1); } } }
From source file:info.magnolia.module.admininterface.SaveHandlerImpl.java
/** * Update the links in a string returned by a rich text editor. If there are links to temporary files created due * the fckeditor upload mechanism those filese are written to the node. * @param node node saving to. used to save the files and fileinfod to * @param name the name of the field. used to make a subnode for the files * @param valueStr the value containing the links * @return the cleaned value/*from w w w. jav a 2 s. c om*/ * @throws AccessDeniedException * @throws RepositoryException * @throws PathNotFoundException */ private String updateLinks(Content node, String name, String valueStr) throws AccessDeniedException, RepositoryException, PathNotFoundException { // process the images and uploaded files HierarchyManager hm = MgnlContext.getHierarchyManager(this.getRepository()); Pattern imagePattern = Pattern.compile("(<(a|img)[^>]+(href|src)[ ]*=[ ]*\")([^\"]*)(\"[^>]*>)"); Pattern uuidPattern = Pattern.compile(MgnlContext.getContextPath() + "/tmp/fckeditor/([^/]*)/[^\"]*"); Content filesNode = ContentUtil.getOrCreateContent(node, name + "_files", ItemType.CONTENTNODE); String pageName = StringUtils.substringAfterLast(this.getPath(), "/"); // adapt img urls Matcher srcMatcher = imagePattern.matcher(valueStr); StringBuffer res = new StringBuffer(); while (srcMatcher.find()) { String src = srcMatcher.group(4); // the editor creates relative links after moving an absolute path: ../../../ replace them src = StringUtils.replace(src, "../../../", MgnlContext.getContextPath() + "/"); String link = src; // process the tmporary uploaded files Matcher uuidMatcher = uuidPattern.matcher(src); if (uuidMatcher.find()) { String uuid = uuidMatcher.group(1); Document doc = FCKEditorTmpFiles.getDocument(uuid); String fileNodeName = Path.getUniqueLabel(hm, filesNode.getHandle(), "file"); SaveHandlerImpl.saveDocument(filesNode, doc, fileNodeName, "", ""); String subpath = StringUtils.removeStart(filesNode.getHandle(), this.getPath() + "/"); link = pageName + "/" + subpath + "/" + fileNodeName + "/" + doc.getFileNameWithExtension(); doc.delete(); try { FileUtils.deleteDirectory(new java.io.File(Path.getTempDirectory() + "/fckeditor/" + uuid)); } catch (IOException e) { log.error("can't delete tmp file [" + Path.getTempDirectory() + "/fckeditor/" + uuid + "]"); } } // make internal links relative else if (src.startsWith(MgnlContext.getContextPath())) { link = pageName + StringUtils.removeStart(src, MgnlContext.getContextPath() + this.getPath()); } // internal uuid links have a leading $ link = StringUtils.replace(link, "$", "\\$"); srcMatcher.appendReplacement(res, "$1" + link + "$5"); //$NON-NLS-1$ } srcMatcher.appendTail(res); valueStr = res.toString(); return valueStr; }
From source file:eionet.cr.staging.exp.ExportRunner.java
/** * @param vf/*from w w w . j a v a 2s .com*/ */ private void prepareValues(ValueFactory vf) { setPredicateURIs(vf); setHiddenPropertiesValues(vf); objectTypeURI = vf.createURI(queryConf.getObjectTypeUri()); rdfTypeURI = vf.createURI(Predicates.RDF_TYPE); indicatorPredicateURI = vf.createURI(Predicates.DAS_INDICATOR); String indicatorUri = queryConf.getIndicatorUri(); if (StringUtils.isNotBlank(indicatorUri)) { indicatorValueURI = vf.createURI(indicatorUri); } String datasetUri = queryConf.getDatasetUri(); datasetIdentifier = StringUtils.substringAfterLast(datasetUri, "/"); if (StringUtils.isBlank(datasetIdentifier)) { throw new IllegalArgumentException("Unable to extract identifier from this dataset URI: " + datasetUri); } datasetPredicateURI = vf.createURI(Predicates.DATACUBE_DATA_SET); datasetValueURI = vf.createURI(datasetUri); graphURI = vf.createURI(StringUtils.replace(datasetUri, "/dataset/", "/data/")); }
From source file:de.awtools.basic.file.AWToolsFileUtils.java
/** * Entfernt aus einem Dateibezeichner alle Pfadangaben. * /*w ww.ja v a2s. co m*/ * @param fileName Der zu untersuchende Dateibezeichner. * @return Liefert den Dateibezeichner ohne Pfadangaben. */ public static String getFileName(final String fileName) { String tmp = AWToolsFileUtils.normalizePath(fileName); if (StringUtils.contains(tmp, "/")) { return StringUtils.substringAfterLast(tmp, "/"); } else { return tmp; } }
From source file:com.evolveum.midpoint.web.page.admin.resources.ResourceDetailsTabPanel.java
private InfoBoxPanel createLastAvailabilityStatusInfo(ResourceType resource) { String messageKey = "PageResource.resource.availabilityUnknown"; String backgroundColor = "bg-gray"; String icon = "fa-question"; OperationalStateType operationalState = resource.getOperationalState(); if (operationalState != null) { AvailabilityStatusType lastAvailabilityStatus = operationalState.getLastAvailabilityStatus(); if (lastAvailabilityStatus != null) { if (lastAvailabilityStatus == AvailabilityStatusType.UP) { messageKey = "PageResource.resource.up"; backgroundColor = "bg-green"; icon = "fa-power-off"; } else if (lastAvailabilityStatus == AvailabilityStatusType.DOWN) { backgroundColor = "bg-red"; messageKey = "PageResource.resource.down"; icon = "fa-ban"; } else if (lastAvailabilityStatus == AvailabilityStatusType.BROKEN) { backgroundColor = "bg-yellow"; messageKey = "PageResource.resource.broken"; icon = "fa-warning"; }//from ww w . j av a 2 s . com } } InfoBoxType infoBoxType = new InfoBoxType(backgroundColor, icon, parentPage.getString(messageKey)); ConnectorType connectorType = resource.getConnector(); if (connectorType == null) { // Connector not found. Probably bad connectorRef reference. infoBoxType.setNumber("--"); infoBoxType.setDescription("--"); } else { String connectorName = StringUtils.substringAfterLast( WebComponentUtil.getEffectiveName(connectorType, ConnectorType.F_CONNECTOR_TYPE), "."); String connectorVersion = connectorType.getConnectorVersion(); infoBoxType.setNumber(connectorName); infoBoxType.setDescription(connectorVersion); } Model<InfoBoxType> boxModel = new Model<>(infoBoxType); InfoBoxPanel lastAvailabilityStatus = new InfoBoxPanel(ID_LAST_AVAILABILITY_STATUS, boxModel); lastAvailabilityStatus.setOutputMarkupId(true); return lastAvailabilityStatus; }
From source file:info.magnolia.cms.filters.RangeSupportFilter.java
private HttpServletResponse wrapResponse(final HttpServletRequest request, final HttpServletResponse response) { return new HttpServletResponseWrapper(response) { /** default length is max. We hope that the underlying code will set proper content length as a header before we proceed serving some bytes. */ private int length = Integer.MAX_VALUE; private final Map<String, Object> headers = new HashMap<String, Object>(); private String eTag; private List<RangeInfo> ranges; private RangeInfo full; private ServletOutputStream stream; private PrintWriter writer; @Override/*from w w w .jav a2 s . co m*/ public void addDateHeader(String name, long date) { super.addDateHeader(name, date); this.headers.put(name, date); if ("Last-Modified".equalsIgnoreCase(name)) { lastModTime = date; } } @Override public void setDateHeader(String name, long date) { super.setDateHeader(name, date); this.headers.put(name, date); if ("Last-Modified".equalsIgnoreCase(name)) { lastModTime = date; } } @Override public void addHeader(String name, String value) { if ("Content-Disposition".equalsIgnoreCase(name) && log.isDebugEnabled()) { log.warn("content disposition enforced by underlying filter/servlet"); } super.addHeader(name, value); this.headers.put(name, value); } @Override public void setHeader(String name, String value) { if ("Content-Disposition".equalsIgnoreCase(name) && log.isDebugEnabled()) { log.warn("content disposition enforced by underlying filter/servlet"); } super.setHeader(name, value); this.headers.put(name, value); } @Override public void addIntHeader(String name, int value) { super.addIntHeader(name, value); this.headers.put(name, value); } @Override public void setIntHeader(String name, int value) { super.setIntHeader(name, value); this.headers.put(name, value); } @Override public void setContentLength(int len) { this.length = len; // do not propagate length up. We might not be able to change it once it is set. We will set it ourselves once we are ready to serve bytes. } @Override public ServletOutputStream getOutputStream() throws IOException { // make sure we set stream only once. Multiple calls to this method are allowed. if (this.stream == null) { ServletOutputStream stream = super.getOutputStream(); // wrap the response to filter out everything except desired range this.stream = addRangeSupportWrapper(request, response, stream); if (!isServeContent || this.stream == null) { // swallow output on head requests this.stream = new ServletOutputStream() { @Override public void write(int b) throws IOException { // do nothing, we do not write any output now } }; } } return stream; } private ServletOutputStream addRangeSupportWrapper(final HttpServletRequest request, final HttpServletResponse response, ServletOutputStream stream) throws IOException { if (!processContent(request, response)) { // we might have to return null stream instead as the previous method already called res.sendError(); return null; } if (headers.containsKey("Content-Range")) { // doesn't work for tomcat as it accesses underlying stream under our hands!!! log.debug("Range request was handled by underlying filter/servlet."); return stream; } if (ranges == null || ranges.isEmpty()) { // no op, serve all as usual log.debug("Didn't find any range to speak of. Serving all content as usual."); if (length != Integer.MAX_VALUE) { // set real length when we know it response.setContentLength(length); } } else if (ranges.size() == 1) { RangeInfo range = ranges.get(0); log.debug("Serving range [{}].", range); // setting 206 header is essential for some clients. The would abort if response is set to 200 response.setStatus(SC_PARTIAL_CONTENT); stream = new RangedOutputStream(stream, range); } else { log.error("Requested multiple ranges [{}].", ranges.size()); // TODO: add support for multiple ranges (sent as multipart request), for now just send error back response.setHeader("Content-Range", "bytes */" + length); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); // again we might have to return null stream after calling sendError() as the original stream might no longer be valid } return stream; } @Override public PrintWriter getWriter() throws IOException { if (!wrapWriter) { return super.getWriter(); } if (this.writer == null) { this.writer = new PrintWriter(new OutputStreamWriter(getOutputStream())); } return writer; } private boolean processContent(HttpServletRequest request, HttpServletResponse response) throws IOException { log.debug("Serving binary on uri {} was last modified at {}", new Object[] { request.getRequestURI(), lastModTime }); if (!isRequestValid(request, response)) { log.debug("Skipping request {} since it doesn't require body", new Object[] { request.getRequestURI() }); return false; } if (!processRange(request)) { log.debug("Could not process range of request {}", new Object[] { request.getRequestURI() }); return false; } return true; } private boolean processRange(HttpServletRequest request) throws IOException { full = new RangeInfo(0, length - 1, length); ranges = new ArrayList<RangeInfo>(); String range = request.getHeader("Range"); // Valid range header format is "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return false; } // If-Range header must match ETag or be greater then LastModified. If not, then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModTime) { ranges.add(full); } } catch (IllegalArgumentException ignore) { // happens when if-range contains something else then date ranges.add(full); } } // in case there were no invalid If-Range headers, then look at requested byte ranges. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { int start = intSubstring(StringUtils.substringBefore(part, "-")); int end = intSubstring(StringUtils.substringAfter(part, "-")); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Is range valid? if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return false; } // Add range. ranges.add(new RangeInfo(start, end, length)); } } response.setHeader("ETag", eTag); if (ranges.size() == 1) { RangeInfo r = ranges.get(0); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.totalLengthOfServedBinary); length = r.lengthOfRange; } return true; } private int intSubstring(String value) { return value.length() > 0 ? Integer.parseInt(value) : -1; } @Override public void flushBuffer() throws IOException { if (writer != null) { writer.flush(); } if (stream != null) { stream.flush(); } super.flushBuffer(); } private boolean isRequestValid(HttpServletRequest request, HttpServletResponse response) throws IOException { String fileName = StringUtils.substringAfterLast(request.getRequestURI(), "/"); eTag = fileName + "_" + length + "_" + lastModTime; // If-None-Match header should contain "*" or ETag. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setHeader("ETag", eTag); // Required in 304. log.debug("Returning {} on header If-None-Match", HttpServletResponse.SC_NOT_MODIFIED); response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return false; } // If-Modified-Since header must be greater than LastModified. ignore if If-None-Match header exists long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModTime) { response.setHeader("ETag", eTag); // Required in 304. // 304 response should contain Date header unless running on timeless server (see 304 response docu) response.addDateHeader("Date", lastModTime); log.debug("Returning {} on header If-Modified-Since", HttpServletResponse.SC_NOT_MODIFIED); response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return false; } // If-Match header should contain "*" or ETag. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { log.debug("Returning {} on header If-Match", HttpServletResponse.SC_PRECONDITION_FAILED); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } // If-Unmodified-Since header must be greater than LastModified. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModTime) { log.debug("Returning {} on header If-Unmodified-Since", HttpServletResponse.SC_PRECONDITION_FAILED); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } log.debug("Passed all precondition checkes for request {}", request.getRequestURI()); return true; } }; }