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:org.jahia.modules.wiki.WikiURLInterceptor.java
public Value beforeSetValue(JCRNodeWrapper node, String name, ExtendedPropertyDefinition definition, Value originalValue) throws ValueFormatException, VersionException, LockException, ConstraintViolationException, RepositoryException { String content = originalValue.getString(); final Map<String, Long> refs = new HashMap<String, Long>(); if (logger.isDebugEnabled()) { logger.debug("Intercept setValue for " + node.getPath() + "/" + name); }/*from w w w . j a v a 2s. c o m*/ if (node.isNodeType(JAHIAMIX_REFERENCES_IN_FIELD)) { NodeIterator ni = node.getNodes(JAHIA_REFERENCE_IN_FIELD_PREFIX); while (ni.hasNext()) { JCRNodeWrapper ref = (JCRNodeWrapper) ni.next(); if (name.equals(ref.getProperty("j:fieldName").getString()) && ref.hasProperty("j:reference")) { refs.put(ref.getProperty("j:reference").getString(), Long.valueOf(StringUtils.substringAfterLast(ref.getName(), "_"))); } } } Map<String, Long> newRefs = new HashMap<String, Long>(); String result = content; try { ComponentManager componentManager = WikiRenderer.getComponentManager(); Parser parser = componentManager.lookup(Parser.class, inputSyntax); XDOM xdom = parser.parse(new StringReader(content)); List<ImageBlock> l = xdom.getChildrenByType(ImageBlock.class, true); for (ImageBlock imageBlock : l) { final String url = imageBlock.getImage().getName(); if (url.startsWith(Jahia.getContextPath() + "/files/")) { String newUrl = replaceRefsByPlaceholders(url, newRefs, refs, node.getSession().getWorkspace().getName()); imageBlock.getParent().replaceChild(new ImageBlock(new URLImage(newUrl), imageBlock.isFreeStandingURI(), imageBlock.getParameters()), imageBlock); } } // new BlockRenderer(); BlockRenderer br = (BlockRenderer) componentManager.lookup(BlockRenderer.class, inputSyntax); DefaultWikiPrinter p = new DefaultWikiPrinter(); br.render(xdom.getRoot(), p); result = p.toString(); } catch (RuntimeException e) { logger.error("Error before setting value", e); } catch (ComponentLookupException e) { logger.error("Error before setting value", e); } catch (ParseException e) { logger.error("Error before setting value", e); } if (!newRefs.equals(refs)) { if (!newRefs.isEmpty() && !node.isNodeType(JAHIAMIX_REFERENCES_IN_FIELD)) { node.addMixin(JAHIAMIX_REFERENCES_IN_FIELD); } if (logger.isDebugEnabled()) { logger.debug("New references : " + newRefs); } NodeIterator ni = node.getNodes(JAHIA_REFERENCE_IN_FIELD_PREFIX); while (ni.hasNext()) { JCRNodeWrapper ref = (JCRNodeWrapper) ni.next(); if (name.equals(ref.getProperty("j:fieldName").getString()) && !newRefs.containsKey(ref.getProperty("j:reference").getString())) { ref.remove(); } } for (Map.Entry<String, Long> entry : newRefs.entrySet()) { if (!refs.containsKey(entry.getKey())) { JCRNodeWrapper ref = node.addNode("j:referenceInField_" + name + "_" + entry.getValue(), "jnt:referenceInField"); ref.setProperty("j:fieldName", name); ref.setProperty("j:reference", entry.getKey()); } } } if (!result.equals(content)) { return node.getSession().getValueFactory().createValue(result); } return originalValue; }
From source file:org.jahia.modules.wiki.WikiURLInterceptor.java
public Value afterGetValue(JCRPropertyWrapper property, Value storedValue) throws ValueFormatException, RepositoryException { String content = storedValue.getString(); if (content == null || !content.contains(DOC_CONTEXT_PLACEHOLDER)) { return storedValue; }//from w w w. j ava 2 s. c o m if (logger.isDebugEnabled()) { logger.debug("Intercept getValue for " + property.getPath()); } final Map<Long, String> refs = new HashMap<Long, String>(); final ExtendedPropertyDefinition definition = (ExtendedPropertyDefinition) property.getDefinition(); String name = definition.getName(); JCRNodeWrapper parent = property.getParent(); if (parent.isNodeType(JAHIAMIX_REFERENCES_IN_FIELD)) { NodeIterator ni = parent.getNodes(JAHIA_REFERENCE_IN_FIELD_PREFIX); while (ni.hasNext()) { JCRNodeWrapper ref = (JCRNodeWrapper) ni.next(); if (name.equals(ref.getProperty("j:fieldName").getString()) && ref.hasProperty("j:reference")) { refs.put(Long.valueOf(StringUtils.substringAfterLast(ref.getName(), "_")), ref.getProperty("j:reference").getString()); } } } String result = content; try { ComponentManager componentManager = WikiRenderer.getComponentManager(); Parser parser = componentManager.lookup(Parser.class, inputSyntax); XDOM xdom = parser.parse(new StringReader(content)); List<ImageBlock> l = xdom.getChildrenByType(ImageBlock.class, true); for (ImageBlock imageBlock : l) { final String url = imageBlock.getImage().getName(); if (url.startsWith(DOC_CONTEXT_PLACEHOLDER)) { try { String newUrl = replacePlaceholdersByRefs(url, refs, property.getSession().getWorkspace().getName(), property.getSession().getLocale()); imageBlock.getParent().replaceChild(new ImageBlock(new URLImage(newUrl), imageBlock.isFreeStandingURI(), imageBlock.getParameters()), imageBlock); } catch (RepositoryException e) { throw new RuntimeException(e); } } } BlockRenderer br = (BlockRenderer) componentManager.lookup(BlockRenderer.class, inputSyntax); DefaultWikiPrinter p = new DefaultWikiPrinter(); br.render(xdom.getRoot(), p); result = p.toString(); } catch (RuntimeException e) { logger.error("Cannot parse wiki content", e); } catch (ComponentLookupException e) { logger.error("Cannot parse wiki content", e); } catch (ParseException e) { logger.error("Cannot parse wiki content", e); } if (!result.equals(content)) { return property.getSession().getValueFactory().createValue(result); } return storedValue; }
From source file:org.jahia.services.applications.pluto.JahiaPortalURLParserImpl.java
/** * Converts a portal URL to a URL string. * * @param portalURL the portal URL to convert. * @return a URL string representing the portal URL. *//*from w w w. jav a 2s. c om*/ public String toString(PortalURL portalURL) { final StringBuilder buffer = new StringBuilder(); // Append the server URI and the servlet path. //buffer.append(portalURL.getServletPath().startsWith("/") ? "" : "/").append(portalURL.getServletPath()); return buffer.append(StringUtils.substringAfterLast(portalURL.getServletPath(), "/")).append("?") .append(PORTLET_INFO).append("=").append(toPortletPathInfo(portalURL).replace('?', '&')).toString(); }
From source file:org.jahia.services.categories.Category.java
/** * Returns the category key from the full category path. * /*from ww w . j a v a2 s. c o m*/ * @param categoryPath * the full category path * @return the category key from the full category path */ public static String getCategoryKey(String categoryPath) { return StringUtils.substringAfterLast(categoryPath, PATH_DELIMITER); }
From source file:org.jahia.services.content.AclListener.java
private void parseEvents(JCRSessionWrapper systemSession, List<Event> aclEvents, Set<String> aceIdentifiers, Set<String> addedAceIdentifiers, Set<String> removedAcePaths, Set<String> addedExtPermIds, Set<List<String>> removedExtPermissions, Set<String> removedRoles) throws RepositoryException { for (Event next : aclEvents) { if (next.getPath().contains("/j:acl/")) { if (next.getType() == Event.PROPERTY_ADDED || next.getType() == Event.PROPERTY_CHANGED) { try { JCRNodeWrapper nodeByIdentifier = systemSession.getNodeByIdentifier(next.getIdentifier()); if (nodeByIdentifier.isNodeType("jnt:ace") && !nodeByIdentifier.isNodeType("jnt:externalAce") && nodeByIdentifier .getProperty("j:aceType").getValue().getString().equals("GRANT")) { String identifier = next.getIdentifier(); if (identifier != null) { aceIdentifiers.add(identifier); if (next.getType() == Event.PROPERTY_ADDED) { addedAceIdentifiers.add(identifier); }/*from w ww . ja v a 2s. c om*/ } } } catch (ItemNotFoundException e) { logger.error("unable to read node " + next.getPath()); } } else if (next.getType() == Event.NODE_REMOVED && StringUtils.substringAfterLast(next.getPath(), "/").startsWith("GRANT_")) { String identifier = next.getIdentifier(); if (identifier != null) { aceIdentifiers.add(identifier); } removedAcePaths.add(next.getPath()); } } else if (next.getPath().startsWith("/roles/")) { if (next.getType() == Event.NODE_ADDED) { String identifier = next.getIdentifier(); JCRNodeWrapper nodeByIdentifier = systemSession.getNodeByIdentifier(identifier); if (nodeByIdentifier.isNodeType("jnt:externalPermissions")) { addedExtPermIds.add(identifier); } } else if (next.getType() == Event.NODE_REMOVED) { String path = next.getPath(); if (path.endsWith("-access")) { removedExtPermissions.add(Arrays.asList( StringUtils.substringAfterLast(StringUtils.substringBeforeLast(path, "/"), "/"), StringUtils.substringAfterLast(path, "/"))); } else { removedRoles.add(StringUtils.substringAfterLast(path, "/")); } } } } }
From source file:org.jahia.services.content.AclListener.java
private void handleAclModifications(final JCRSessionWrapper systemSession, Set<String> aceIdentifiers, final Set<String> addedAceIdentifiers, Set<String> removedAcePaths, final JCREventIterator events) throws RepositoryException { final Map<String, Set<String>> privilegedAdded = new HashMap<String, Set<String>>(); final Map<String, Set<String>> privilegedToCheck = new HashMap<String, Set<String>>(); final Map<String, JCRNodeWrapper> roleNodes = new HashMap<String, JCRNodeWrapper>(); for (final String aceIdentifier : aceIdentifiers) { final Set<String> roles = new HashSet<String>(); JCRNodeWrapper ace = null;// w w w . j a v a2 s . c o m String principal = null; try { ace = systemSession.getNodeByIdentifier(aceIdentifier); principal = ace.getProperty("j:principal").getString(); if (ace.hasProperty("j:roles")) { Value[] vals = ace.getProperty("j:roles").getValues(); for (Value val : vals) { roles.add(val.getString()); } } else { logger.warn("Missing roles property for acl on " + ace.getPath()); } } catch (ItemNotFoundException e) { // Item does not exist anymore, use empty roles set } catch (InvalidItemStateException e) { // Item does not exist anymore, use empty roles set } if (!addedAceIdentifiers.contains(aceIdentifier)) { QueryManager q = systemSession.getWorkspace().getQueryManager(); String sql = "select * from [jnt:externalAce] as ace where ace.[j:sourceAce] = '" + aceIdentifier + "'"; QueryResult qr = q.createQuery(sql, Query.JCR_SQL2).execute(); NodeIterator ni = qr.getNodes(); while (ni.hasNext()) { JCRNodeWrapper n = (JCRNodeWrapper) ni.nextNode(); String role = n.getProperty("j:roles").getValues()[0].getString(); if (!roles.contains(role)) { List<Value> newVals = new ArrayList<Value>(); for (Value value : n.getProperty("j:sourceAce").getValues()) { if (!value.getString().equals(aceIdentifier)) { newVals.add(value); } } if (newVals.size() == 0) { n.remove(); } else { n.setProperty("j:sourceAce", newVals.toArray(new Value[newVals.size()])); } } } } if (!roles.isEmpty()) { if (systemSession.getWorkspace().getName().equals(Constants.LIVE_WORKSPACE)) { final JCRNodeWrapper finalAce = ace; final String fprincipal = principal; JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(null, Constants.EDIT_WORKSPACE, systemSession.getLocale(), new JCRCallback<Object>() { @Override public Object doInJCR(JCRSessionWrapper defaultSystemSession) throws RepositoryException { final boolean publish = events .getOperationType() == JCRObservationManager.WORKSPACE_CLONE || events .getLastOperationType() == JCRObservationManager.WORKSPACE_CLONE; handleAclModifications(systemSession, defaultSystemSession, roles, finalAce, fprincipal, privilegedAdded, privilegedToCheck, new HashMap<String, JCRNodeWrapper>(), addedAceIdentifiers.contains(aceIdentifier), publish); return null; } }); } else { handleAclModifications(systemSession, systemSession, roles, ace, principal, privilegedAdded, privilegedToCheck, roleNodes, addedAceIdentifiers.contains(aceIdentifier), false); } } } systemSession.save(); if (!systemSession.getWorkspace().getName().equals(Constants.LIVE_WORKSPACE)) { // Handle removed ACL - these users which may have lost their privileged access for (String acePath : removedAcePaths) { final String name = StringUtils.substringAfterLast(acePath, "/"); if (name.startsWith("REF")) { continue; } String site; if (acePath.startsWith("/sites/")) { site = StringUtils.substringBefore(acePath.substring("/sites/".length()), "/"); } else { site = "systemsite"; } String principal = StringUtils.substringAfter(name, "_").replaceFirst("_", ":"); if (principal.startsWith("jcr:read") || principal.startsWith("jcr:write")) { principal = StringUtils.substringAfter(principal, "_").replaceFirst("_", ":"); } if (!PRIVILEGED_GROUPS.contains(principal)) { if (!privilegedToCheck.containsKey(site)) { privilegedToCheck.put(site, new HashSet<String>()); } privilegedToCheck.get(site).add(principal); } } // Users who have new privileged roles do not require check for (Map.Entry<String, Set<String>> entry : privilegedToCheck.entrySet()) { if (privilegedAdded.get(entry.getKey()) != null) { entry.getValue().removeAll(privilegedAdded.get(entry.getKey())); } } for (Map.Entry<String, Set<String>> entry : privilegedAdded.entrySet()) { final String site = entry.getKey(); final JCRGroupNode priv = groupService.lookupGroup(site, JahiaGroupManagerService.SITE_PRIVILEGED_GROUPNAME, systemSession); if (priv != null) { for (String principal : entry.getValue()) { JCRNodeWrapper p = getPrincipal(site, principal); if (p == null || priv.isMember(p)) { continue; } logger.info(principal + " need privileged access"); priv.addMember(p); } } } for (Map.Entry<String, Set<String>> entry : privilegedToCheck.entrySet()) { final String site = entry.getKey(); final JCRGroupNode priv = groupService.lookupGroup(site, JahiaGroupManagerService.SITE_PRIVILEGED_GROUPNAME, systemSession); if (priv != null) { for (String principal : entry.getValue()) { JCRNodeWrapper p = getPrincipal(site, principal); if (p == null || !priv.isMember(p)) { continue; } List<String> rolesName = new ArrayList<String>(); boolean needPrivileged = false; String sql = StringUtils.equals(site, JahiaSitesService.SYSTEM_SITE_KEY) ? "select ace.[j:roles] AS [rep:facet(facet.mincount=1)] from [jnt:ace] as ace where (not ([j:externalPermissionsName] is not null)) and ace.[j:aceType]='GRANT' and ace.[j:principal] = '" + principal + "' and (isdescendantnode(ace, ['/sites/" + site + "']) or not isdescendantnode(ace, ['/sites']))" : "select ace.[j:roles] AS [rep:facet(facet.mincount=1)] from [jnt:ace] as ace where (not ([j:externalPermissionsName] is not null)) and ace.[j:aceType]='GRANT' and ace.[j:principal] = '" + principal + "' and isdescendantnode(ace, ['/sites/" + site + "'])"; rolesName.addAll(getRolesName(systemSession, sql)); try { for (String roleName : rolesName) { JCRNodeWrapper roleNode = getRole(systemSession, roleName, roleNodes); if (roleNode != null) { if (roleNode.hasProperty("j:privilegedAccess") && roleNode.getProperty("j:privilegedAccess").getBoolean()) { needPrivileged = true; break; } } } } catch (PathNotFoundException e) { // ignore exception } if (!needPrivileged) { logger.info(principal + " do not need privileged access"); priv.removeMember(p); } } } } } systemSession.save(); }
From source file:org.jahia.services.content.ConflictResolver.java
private String getTargetName(String path) { if (path.contains("/")) { return StringUtils.substringAfterLast(path, "/"); } else {//from w ww.j a va 2 s . c om return path; } }
From source file:org.jahia.services.content.decorator.JCRFrozenNodeAsRegular.java
@Override public String getName() { if ((localPath.equals("/") || localPath.equals(provider.getRelativeRoot())) && provider.getMountPoint().length() > 1) { String mp = provider.getMountPoint(); return mp.substring(mp.lastIndexOf('/') + 1); } else {//from w w w .j a va 2 s . c om return StringUtils.substringAfterLast(localPath, "/"); } }
From source file:org.jahia.services.content.files.FileServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { long timer = System.currentTimeMillis(); int code = HttpServletResponse.SC_OK; try {/* w w w.j av a2s.c o m*/ FileKey fileKey = parseKey(req); if (fileKey != null && fileKey.getWorkspace() != null && StringUtils.isNotEmpty(fileKey.getPath())) { Cache<String, FileLastModifiedCacheEntry> lastModifiedCache = cacheManager.getLastModifiedCache(); FileLastModifiedCacheEntry lastModifiedEntry = lastModifiedCache.get(fileKey.getCacheKey()); if (isNotModified(fileKey, lastModifiedEntry, req, res)) { // resource is not changed code = HttpServletResponse.SC_NOT_MODIFIED; res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); logAccess(fileKey, req, "ok-not-modified"); return; } Cache<String, Map<String, FileCacheEntry>> contentCache = cacheManager.getContentCache(); Map<String, FileCacheEntry> entries = contentCache.get(fileKey.getCacheKey()); FileCacheEntry fileEntry = entries != null ? entries.get(fileKey.getThumbnail()) : null; if (fileEntry == null) { JCRNodeWrapper n = getNode(fileKey); if (n == null || !n.isFile()) { // cannot find it or it is not a file code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Date lastModifiedDate = n.getLastModifiedAsDate(); long lastModified = lastModifiedDate != null ? lastModifiedDate.getTime() : 0; String eTag = generateETag(n.getIdentifier(), lastModified); if (lastModifiedEntry == null) { lastModifiedEntry = new FileLastModifiedCacheEntry(eTag, lastModified); if (canCache(n)) { lastModifiedCache.put(fileKey.getCacheKey(), lastModifiedEntry); } } if (isNotModified(fileKey, lastModifiedEntry, req, res)) { // resource is not changed code = HttpServletResponse.SC_NOT_MODIFIED; res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); logAccess(fileKey, req, "ok-not-modified"); return; } fileEntry = getFileEntry(fileKey, n, lastModifiedEntry); if (fileEntry != null && fileEntry.getData() != null) { entries = contentCache.get(fileKey.getCacheKey()); if (entries == null) { entries = new HashMap<String, FileCacheEntry>(1); } entries.put(fileKey.getThumbnail(), fileEntry); contentCache.put(fileKey.getCacheKey(), entries); logAccess(fileKey, req, "ok"); } } else { if (lastModifiedEntry == null) { lastModifiedEntry = new FileLastModifiedCacheEntry(fileEntry.getETag(), fileEntry.getLastModified()); lastModifiedCache.put(fileKey.getCacheKey(), lastModifiedEntry); } logAccess(fileKey, req, "ok-cached"); if (logger.isDebugEnabled()) { logger.debug("Serving cached file entry {}", fileKey.toString()); } } if (fileEntry != null) { List<RangeUtils.Range> ranges; boolean useRanges = true; if (fileEntry.getBinary() instanceof BinaryRangesSupport) { useRanges = ((BinaryRangesSupport) fileEntry.getBinary()).supportRanges(); } ranges = useRanges ? RangeUtils.parseRange(req, res, fileEntry.getETag(), fileEntry.getLastModified(), fileEntry.getContentLength()) : null; if (fileKey.getPath().indexOf('%', fileKey.getPath().lastIndexOf('/')) != -1) { res.setHeader("Content-Disposition", "inline; filename=\"" + JCRContentUtils.unescapeLocalNodeName( StringUtils.substringAfterLast(fileKey.getPath(), "/")) + "\""); } res.setDateHeader("Last-Modified", fileEntry.getLastModified()); res.setHeader("ETag", fileEntry.getETag()); InputStream is = null; if (fileEntry.getData() != null) { // writing in-memory data is = new ByteArrayInputStream(fileEntry.getData()); } else if (fileEntry.getBinary() != null) { // spool from an input stream is = fileEntry.getBinary().getStream(); } else { code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (ranges == null || (ranges == RangeUtils.FULL)) { res.setContentType(fileEntry.getMimeType()); if (fileEntry.getContentLength() <= Integer.MAX_VALUE) { res.setContentLength((int) fileEntry.getContentLength()); } else { res.setHeader("Content-Length", Long.toString(fileEntry.getContentLength())); } ServletOutputStream os = res.getOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); } else { res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { res.setContentType(fileEntry.getMimeType()); RangeUtils.Range range = (RangeUtils.Range) ranges.get(0); res.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { res.setContentLength((int) length); } else { // Set the content-length as String to be able to use a long res.setHeader("Content-Length", "" + length); } ServletOutputStream os = res.getOutputStream(); RangeUtils.copy(is, os, range); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } else { res.setContentType("multipart/byteranges; boundary=" + RangeUtils.MIME_SEPARATION); try { res.setBufferSize(RangeUtils.getOutput()); } catch (IllegalStateException e) { // Silent catch } ServletOutputStream os = res.getOutputStream(); RangeUtils.copy(is, os, ranges.iterator(), fileEntry.getMimeType()); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } if ((fileEntry.getData() == null) && (fileEntry.getBinary() != null)) { fileEntry.getBinary().dispose(); fileEntry.setBinary(null); } SpringContextSingleton.getInstance() .publishEvent(new FileDownloadEvent(this, req, fileEntry.getIdentifier(), fileKey.getPath(), fileEntry.getNodeTypes(), fileKey.getWorkspace())); } else { code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } else { code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (RepositoryException e) { logger.error("Cannot get file", e); code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { if (logger.isDebugEnabled()) { logger.debug("Served [{}] with status code [{}] in [{}ms]", new Object[] { req.getRequestURI() + (req.getQueryString() != null ? "?" + req.getQueryString() : ""), code, (System.currentTimeMillis() - timer) }); } } }
From source file:org.jahia.services.content.impl.external.ExternalNodeImpl.java
public String getName() throws RepositoryException { return StringUtils.substringAfterLast(data.getPath(), "/"); }