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.external.ExternalSessionImpl.java
private Item handleI18nNode(String parentPath, String path) throws RepositoryException { ExternalData parentObject = getParent(parentPath); String lang = StringUtils.substringAfterLast(path, TRANSLATION_NODE_NAME_BASE); if ((parentObject.getI18nProperties() == null || !parentObject.getI18nProperties().containsKey(lang)) && (parentObject.getLazyI18nProperties() == null || !parentObject.getLazyI18nProperties().containsKey(lang))) { throw new PathNotFoundException(path); }/*from w w w .jav a 2 s . c o m*/ Map<String, String[]> i18nProps = new HashMap<String, String[]>(); if (parentObject.getI18nProperties() != null && parentObject.getI18nProperties().containsKey(lang)) { i18nProps.putAll(parentObject.getI18nProperties().get(lang)); } i18nProps.put("jcr:language", new String[] { lang }); ExternalData i18n = new ExternalData(TRANSLATION_PREFIX + lang + ":" + parentObject.getId(), path, "jnt:translation", i18nProps); if (parentObject.getLazyI18nProperties() != null && parentObject.getLazyI18nProperties().containsKey(lang)) { i18n.setLazyProperties(parentObject.getLazyI18nProperties().get(lang)); } final ExternalNodeImpl node = new ExternalNodeImpl(i18n, this); registerNode(node); return node; }
From source file:org.jahia.modules.external.ExternalSessionImpl.java
public void move(String source, String dest) throws ItemExistsException, PathNotFoundException, VersionException, ConstraintViolationException, LockException, RepositoryException { getAccessControlManager().checkRemoveNode(source); getAccessControlManager().checkAddChildNodes(StringUtils.substringBeforeLast(dest, "/")); Item sourceNode = getItem(source);//from w w w.ja v a 2s . c o m if (!sourceNode.isNode()) { throw new PathNotFoundException(source); } if (sourceNode instanceof ExtensionNode) { String targetName = StringUtils.substringAfterLast(dest, "/"); String parentPath = StringUtils.substringBeforeLast(dest, "/"); Node targetNode = (Node) getItem(parentPath); final String srcAbsPath = ((ExtensionNode) sourceNode).getJcrNode().getPath(); Node jcrNode = null; if (targetNode instanceof ExtensionNode) { jcrNode = ((ExtensionNode) targetNode).getJcrNode(); } else if (targetNode instanceof ExternalNodeImpl) { final ExternalNodeImpl externalNode = (ExternalNodeImpl) targetNode; Node extendedNode = externalNode.getExtensionNode(true); if (extendedNode != null && externalNode.canItemBeExtended(targetName, ((ExtensionNode) sourceNode).getPrimaryNodeType().getName())) { jcrNode = extendedNode; } } if (jcrNode != null) { getExtensionSession().move(srcAbsPath, jcrNode.getPath() + "/" + targetName); return; } } else if (sourceNode instanceof ExternalNodeImpl) { if (!(repository.getDataSource() instanceof ExternalDataSource.Writable)) { throw new UnsupportedRepositoryOperationException(); } if (source.equals(dest)) { return; } final ExternalNodeImpl externalNode = (ExternalNodeImpl) sourceNode; final ExternalNodeImpl previousParent = (ExternalNodeImpl) externalNode.getParent(); final List<String> previousParentChildren = previousParent.getExternalChildren(); ExternalContentStoreProvider.setCurrentSession(this); try { //todo : store move in session and move node in save ((ExternalDataSource.Writable) repository.getDataSource()).move(source, dest); int oldIndex = previousParentChildren.indexOf(externalNode.getName()); previousParentChildren.remove(externalNode.getName()); unregisterNode(externalNode); ExternalData newData = repository.getDataSource().getItemByPath(dest); final ExternalNodeImpl newExternalNode = new ExternalNodeImpl(newData, this); registerNode(newExternalNode); final ExternalNodeImpl newParent = (ExternalNodeImpl) newExternalNode.getParent(); if (newParent.equals(previousParent)) { previousParentChildren.add(oldIndex, newExternalNode.getName()); } else if (!newParent.getExternalChildren().contains(newExternalNode.getName())) { newParent.getExternalChildren().add(newExternalNode.getName()); } final ExternalData oldData = externalNode.getData(); if (oldData.getId().equals(newData.getId())) { return; } getRepository().getStoreProvider().getExternalProviderInitializerService().updateExternalIdentifier( oldData.getId(), newData.getId(), getRepository().getProviderKey(), getRepository().getDataSource().isSupportsHierarchicalIdentifiers()); return; } finally { ExternalContentStoreProvider.removeCurrentSession(); } } throw new UnsupportedRepositoryOperationException(); }
From source file:org.jahia.modules.external.ExternalSessionImpl.java
public void save() throws AccessDeniedException, ItemExistsException, ConstraintViolationException, InvalidItemStateException, VersionException, LockException, NoSuchNodeTypeException, RepositoryException {/*from w w w.ja va 2 s .com*/ if (extensionSession != null && extensionSession.hasPendingChanges()) { extensionSession.save(); } if (!(repository.getDataSource() instanceof ExternalDataSource.Writable)) { deletedData.clear(); changedData.clear(); orderedData.clear(); return; } ExternalContentStoreProvider.setCurrentSession(this); try { Map<String, ExternalData> changedDataWithI18n = new LinkedHashMap<String, ExternalData>(); for (Map.Entry<String, ExternalData> entry : changedData.entrySet()) { String path = entry.getKey(); ExternalData externalData = entry.getValue(); if (path.startsWith(TRANSLATION_NODE_NAME_BASE, path.lastIndexOf("/") + 1)) { String lang = StringUtils.substringAfterLast(path, TRANSLATION_NODE_NAME_BASE); String parentPath = StringUtils.substringBeforeLast(path, "/"); ExternalData parentData; if (changedDataWithI18n.containsKey(parentPath)) { parentData = changedDataWithI18n.get(parentPath); } else { parentData = repository.getDataSource().getItemByPath(parentPath); } Map<String, Map<String, String[]>> i18nProperties = parentData.getI18nProperties(); if (i18nProperties == null) { i18nProperties = new HashMap<String, Map<String, String[]>>(); parentData.setI18nProperties(i18nProperties); } i18nProperties.put(lang, externalData.getProperties()); if (externalData.getLazyProperties() != null) { Map<String, Set<String>> lazyI18nProperties = parentData.getLazyI18nProperties(); if (lazyI18nProperties == null) { lazyI18nProperties = new HashMap<String, Set<String>>(); parentData.setLazyI18nProperties(lazyI18nProperties); } lazyI18nProperties.put(lang, externalData.getLazyProperties()); } changedDataWithI18n.put(parentPath, parentData); } else { changedDataWithI18n.put(path, externalData); } } ExternalDataSource.Writable writableDataSource = (ExternalDataSource.Writable) repository .getDataSource(); for (String path : orderedData.keySet()) { writableDataSource.order(path, orderedData.get(path)); } orderedData.clear(); for (ExternalData data : changedDataWithI18n.values()) { writableDataSource.saveItem(data); // when data contain binaries we flush the nodes so the binary will be load // from the external data source after an upload, avoid to cache a tmp binary after upload for exemple if (data.getBinaryProperties() != null && data.getBinaryProperties().size() > 0) { ExternalNodeImpl cachedNode = nodesByPath.get(data.getPath()); if (cachedNode != null) { nodesByPath.remove(data.getPath()); nodesByIdentifier.remove(cachedNode.getIdentifier()); } } } changedData.clear(); if (!deletedData.isEmpty()) { List<String> toBeDeleted = new LinkedList<String>(); for (String path : deletedData.keySet()) { writableDataSource.removeItemByPath(path); toBeDeleted.add(deletedData.get(path).getId()); } getRepository().getStoreProvider().getExternalProviderInitializerService().delete(toBeDeleted, getRepository().getStoreProvider().getKey(), getRepository().getDataSource().isSupportsHierarchicalIdentifiers()); deletedData.clear(); } for (ExternalItemImpl newItem : newItems) { newItem.setNew(false); } newItems.clear(); } finally { ExternalContentStoreProvider.removeCurrentSession(); } }
From source file:org.jahia.modules.external.modules.ModulesDataSource.java
public void start() { final String fullFolderPath = module.getSourcesFolder().getPath() + File.separator; final String importFilesRootFolder = fullFolderPath + "src" + File.separator + "main" + File.separator + "import" + File.separator + "content" + File.separator + "modules" + File.separator + module.getId() + File.separator + "files" + File.separator; final String filesNodePath = "/modules/" + module.getIdWithVersion() + "/files"; FileMonitor monitor = new FileMonitor(new FileMonitorCallback() { @Override/*ww w . j av a2 s . c o m*/ public void process(FileMonitorResult result) { logger.info("Detected changes in sources of the module in folder {}: {}", fullFolderPath, result); if (logger.isDebugEnabled()) { logger.debug(result.getInfo()); } boolean nodeTypeLabelsFlushed = false; List<File> importFiles = new ArrayList<File>(); for (final File file : result.getAllAsList()) { invalidateVfsParentCache(fullFolderPath, file); if (file.getPath().startsWith(importFilesRootFolder)) { importFiles.add(file); continue; } String type; try { type = getDataType(getFile(file.getPath())); } catch (FileSystemException e) { if (logger.isDebugEnabled()) { logger.error(e.getMessage(), e); } // Unable to resolve file, continue continue; } if (StringUtils.equals(type, "jnt:propertiesFile")) { // we've detected a properties file, check if its parent is of type jnt:resourceBundleFolder // -> than this one gets the type jnt:resourceBundleFile; otherwise just jnt:file File parent = file.getParentFile(); type = parent != null && StringUtils.equals(Constants.JAHIANT_RESOURCEBUNDLE_FOLDER, folderTypeMapping.get(parent.getName())) ? Constants.JAHIANT_RESOURCEBUNDLE_FILE : type; } if (StringUtils.equals(type, "jnt:resourceBundleFile") && !nodeTypeLabelsFlushed) { NodeTypeRegistry.getInstance().flushLabels(); logger.debug("Flushing node type label caches"); for (NodeTypeRegistry registry : nodeTypeRegistryMap.values()) { registry.flushLabels(); } nodeTypeLabelsFlushed = true; try { JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback<Object>() { @Override public Object doInJCR(JCRSessionWrapper session) throws RepositoryException { JCRSiteNode site = (JCRSiteNode) session.getNode("/modules/" + module.getId()); Set<String> langs = new HashSet<String>(site.getLanguages()); boolean changed = false; if (file.getParentFile().listFiles() != null) { File[] files = file.getParentFile().listFiles(); if (files != null) { for (File f : files) { String s = StringUtils.substringAfterLast( StringUtils.substringBeforeLast(f.getName(), "."), "_"); if (!StringUtils.isEmpty(s) && !langs.contains(s)) { langs.add(s); changed = true; } } } if (changed) { site.setLanguages(langs); session.save(); } } return null; } }); } catch (RepositoryException e) { logger.error(e.getMessage(), e); } } else if (StringUtils.equals(type, JNT_DEFINITION_FILE)) { try { registerCndFiles(file); } catch (IOException | ParseException | RepositoryException e) { logger.error(e.getMessage(), e); } } else if (StringUtils.equals(type, Constants.JAHIANT_VIEWFILE)) { ModulesSourceHttpServiceTracker httpServiceTracker = modulesSourceSpringInitializer .getHttpServiceTracker(module.getId()); if (result.getCreated().contains(file)) { httpServiceTracker.registerResource(file); } else if (result.getDeleted().contains(file)) { httpServiceTracker.unregisterResouce(file); } // in case of jsp, flush the cache if (StringUtils.endsWith(file.getName(), ".jsp")) { httpServiceTracker.flushJspCache(file); } } } if (!importFiles.isEmpty()) { modulesImportExportHelper.updateImportFileNodes(importFiles, importFilesRootFolder, filesNodePath); } SourceControlManagement sourceControl = module.getSourceControl(); if (sourceControl != null) { sourceControl.invalidateStatusCache(); logger.debug("Invalidating SCM status caches for module {}", module.getId()); for (File file : result.getDeleted()) { try { sourceControl.remove(file); } catch (IOException e) { logger.error("An error occurred when trying to remove file from source control", e); } } for (File file : result.getCreated()) { try { sourceControl.add(file); } catch (IOException e) { logger.error("An error occurred when trying to add file in source control", e); } } } } }); monitor.setRecursive(true); Set<String> ignored = new HashSet<>(sourceControlFactory.getIgnoredFiles()); ignored.add(".svn"); ignored.add(".git"); monitor.setFilesToIgnore(ignored); monitor.addFile(module.getSourcesFolder()); fileMonitorJobName = "ModuleSourcesJob-" + module.getId(); FileMonitorJob.schedule(fileMonitorJobName, 5000, monitor); for (String cndFilePath : module.getDefinitionsFiles()) { try { registerCndFiles(new File(fullFolderPath + "src" + File.separator + "main" + File.separator + "resources" + File.separator + cndFilePath)); } catch (IOException | ParseException | RepositoryException e) { logger.error(e.getMessage(), e); } } }
From source file:org.jahia.modules.external.modules.ModulesDataSource.java
private ExternalData enhanceData(String path, ExternalData data) { try {/* w w w.ja va 2s . c o m*/ ExtendedNodeType type = NodeTypeRegistry.getInstance().getNodeType(data.getType()); if (type.isNodeType("jnt:moduleVersionFolder")) { String name = module.getName(); String v = module.getVersion().toString(); data.getProperties().put("j:title", new String[] { name + " (" + v + ")" }); } else if (type.isNodeType(JNT_EDITABLE_FILE)) { Set<String> lazyProperties = data.getLazyProperties(); if (lazyProperties == null) { lazyProperties = new HashSet<String>(); data.setLazyProperties(lazyProperties); } String nodeTypeName = StringUtils .replace(StringUtils.substringBetween(path, SRC_MAIN_RESOURCES, "/"), "_", ":"); // add nodetype only if it is resolved if (nodeTypeName != null) { nodeTypeName = nodeTypeName.replace('-', '_'); data.getProperties().put("nodeTypeName", new String[] { nodeTypeName }); } lazyProperties.add(SOURCE_CODE); // set Properties if (type.isNodeType(Constants.JAHIAMIX_VIEWPROPERTIES)) { Properties properties = new SortedProperties(); InputStream is = null; try { is = getFile(StringUtils.substringBeforeLast(path, ".") + PROPERTIES_EXTENSION).getContent() .getInputStream(); properties.load(is); Map<String, String[]> dataProperties = new HashMap<String, String[]>(); for (Map.Entry<?, ?> property : properties.entrySet()) { ExtendedPropertyDefinition propertyDefinition = type.getPropertyDefinitionsAsMap() .get(property.getKey()); String[] values; if (propertyDefinition != null && propertyDefinition.isMultiple()) { values = StringUtils.split(((String) property.getValue()), ","); } else { values = new String[] { (String) property.getValue() }; } dataProperties.put((String) property.getKey(), values); } data.getProperties().putAll(dataProperties); } catch (FileSystemException e) { //no properties files, do nothing } catch (IOException e) { logger.error("Cannot read property file", e); } finally { IOUtils.closeQuietly(is); } } } else { String ext = StringUtils.substringAfterLast(path, "."); Map<?, ?> extensions = (Map<?, ?>) SpringContextSingleton.getBean("fileExtensionIcons"); if ("img".equals(extensions.get(ext))) { InputStream is = null; try { is = getFile(data.getPath()).getContent().getInputStream(); BufferedImage bimg = ImageIO.read(is); if (bimg != null) { data.setMixin(JMIX_IMAGE_LIST); data.getProperties().put("j:height", new String[] { Integer.toString(bimg.getHeight()) }); data.getProperties().put("j:width", new String[] { Integer.toString(bimg.getWidth()) }); } } catch (FileSystemException e) { //no properties files, do nothing } catch (IOException e) { logger.error("Cannot read property file", e); } catch (Exception e) { logger.error("unable to enhance image " + data.getPath(), e); } finally { if (is != null) { IOUtils.closeQuietly(is); } } } } } catch (NoSuchNodeTypeException e) { logger.error("Unknown type", e); } SourceControlManagement sourceControl = module.getSourceControl(); if (sourceControl != null) { try { SourceControlManagement.Status status = getScmStatus(path); if (status != SourceControlManagement.Status.UNMODIFIED) { List<String> mixin = data.getMixin(); if (mixin == null) { mixin = new ArrayList<String>(); } if (!mixin.contains("jmix:sourceControl")) { mixin.add("jmix:sourceControl"); } data.setMixin(mixin); data.getProperties().put("scmStatus", new String[] { status.name().toLowerCase() }); } } catch (IOException e) { logger.error("Failed to get SCM status", e); } } return data; }
From source file:org.jahia.modules.external.modules.ModulesDataSource.java
private void checkCndItemUsage(String path, String message) throws RepositoryException { try {/*from w ww. ja va2 s .c o m*/ ExternalData item = getCndItemByPath(path); if (!NODETYPES_TYPES.contains(item.getType())) { item = getCndItemByPath(StringUtils.substringBeforeLast(path, "/")); if ("modulesDataSource.errors.delete".equals(message) || "modulesDataSource.errors.move".equals(message)) { message += ".property"; } } final String type = StringUtils.substringAfterLast(item.getPath(), "/"); // Check for usage of the nodetype before moving it checkCndItemUsageByWorkspace(type, "default", message); checkCndItemUsageByWorkspace(type, "live", message); } catch (NoSuchNodeTypeException e) { // do nothing } }
From source file:org.jahia.modules.external.modules.ModulesDataSource.java
private void saveCndResourceBundle(ExternalData data, String key) throws RepositoryException { String resourceBundleName = module.getResourceBundleName(); if (resourceBundleName == null) { resourceBundleName = "resources." + module.getId(); }/* w ww . ja v a 2 s. c om*/ String rbBasePath = "/src/main/resources/resources/" + StringUtils.substringAfterLast(resourceBundleName, "."); Map<String, Map<String, String[]>> i18nProperties = data.getI18nProperties(); if (i18nProperties != null) { List<File> newFiles = new ArrayList<File>(); for (Map.Entry<String, Map<String, String[]>> entry : i18nProperties.entrySet()) { String lang = entry.getKey(); Map<String, String[]> properties = entry.getValue(); String[] values = properties.get(Constants.JCR_TITLE); String title = ArrayUtils.isEmpty(values) ? null : values[0]; values = properties.get(Constants.JCR_DESCRIPTION); String description = ArrayUtils.isEmpty(values) ? null : values[0]; String rbPath = rbBasePath + "_" + lang + PROPERTIES_EXTENSION; InputStream is = null; InputStreamReader isr = null; OutputStream os = null; OutputStreamWriter osw = null; try { FileObject file = getFile(rbPath); FileContent content = file.getContent(); Properties p = new SortedProperties(); if (file.exists()) { is = content.getInputStream(); isr = new InputStreamReader(is, Charsets.ISO_8859_1); p.load(isr); isr.close(); is.close(); } else if (StringUtils.isBlank(title) && StringUtils.isBlank(description)) { continue; } else { newFiles.add(new File(file.getName().getPath())); } if (!StringUtils.isEmpty(title)) { p.setProperty(key, title); } if (!StringUtils.isEmpty(description)) { p.setProperty(key + "_description", description); } os = content.getOutputStream(); osw = new OutputStreamWriter(os, Charsets.ISO_8859_1); p.store(osw, rbPath); ResourceBundle.clearCache(); } catch (FileSystemException e) { logger.error("Failed to save resourceBundle", e); throw new RepositoryException("Failed to save resourceBundle", e); } catch (IOException e) { logger.error("Failed to save resourceBundle", e); throw new RepositoryException("Failed to save resourceBundle", e); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(isr); IOUtils.closeQuietly(os); IOUtils.closeQuietly(osw); } } SourceControlManagement sourceControl = module.getSourceControl(); if (sourceControl != null) { try { sourceControl.add(newFiles); } catch (IOException e) { logger.error("Failed to add files to source control", e); throw new RepositoryException("Failed to add new files to source control: " + newFiles, e); } } } }
From source file:org.jahia.modules.external.modules.osgi.ModulesSourceHttpServiceTracker.java
protected String getResourcePath(File file) { return StringUtils.substringAfterLast(FilenameUtils.separatorsToUnix(file.getPath()), "/src/main/resources"); }
From source file:org.jahia.modules.external.test.db.BaseDatabaseDataSource.java
@Override public final List<String> getChildren(String path) { String nodeType;// www . ja v a2s . c om try { nodeType = getNodeTypeName(path); } catch (PathNotFoundException e) { // cannot handle that path return Collections.emptyList(); } if (nodeType.equals(getSchemaNodeType())) { return getTableNames(); } else if (nodeType.equals(getTableNodeType())) { return getRowIDs(StringUtils.substringAfterLast(path, "/"), new HashMap<String, Value>()); } else { return Collections.emptyList(); } }
From source file:org.jahia.modules.external.test.db.CanLoadChildrenInBatchMappedDatabaseDataSource.java
@Override public List<ExternalData> getChildrenNodes(String path) throws RepositoryException { String nodeType;/* ww w . ja v a2 s . com*/ try { nodeType = getNodeTypeName(path); } catch (PathNotFoundException e) { // cannot handle that path return Collections.emptyList(); } if (nodeType.equals(getSchemaNodeType())) { final List<String> tableNames = getTableNames(); final List<ExternalData> children = new ArrayList<ExternalData>(tableNames.size()); for (String tableName : tableNames) { children.add(getItemByPath("/" + tableName)); } return children; } else if (nodeType.equals(getTableNodeType())) { final List<String> rowIDs = getRowIDs(StringUtils.substringAfterLast(path, "/"), Collections.<String, Value>emptyMap()); final List<ExternalData> children = new ArrayList<ExternalData>(rowIDs.size()); for (String rowID : rowIDs) { children.add(getItemByPath(path + "/" + rowID)); } return children; } else { return Collections.emptyList(); } }