Example usage for org.apache.commons.lang StringUtils substringBeforeLast

List of usage examples for org.apache.commons.lang StringUtils substringBeforeLast

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringBeforeLast.

Prototype

public static String substringBeforeLast(String str, String separator) 

Source Link

Document

Gets the substring before the last occurrence of a separator.

Usage

From source file:org.jahia.modules.external.ExternalSessionImpl.java

protected Item getItemWithNoCheck(String path) throws PathNotFoundException, RepositoryException {
    path = path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
    if (deletedData.containsKey(path)) {
        throw new PathNotFoundException("This node has been deleted");
    }/*from w  w w.  j  a  va  2s .c o m*/

    final Node fromCache = getFromCacheByPath(path);
    if (fromCache != null) {
        return fromCache;
    }

    String parentPath = StringUtils.substringBeforeLast(path, "/");
    if (parentPath.equals("")) {
        parentPath = "/";
    }
    try {
        if (StringUtils.substringAfterLast(parentPath, "/").startsWith(TRANSLATION_NODE_NAME_BASE)) {
            // Getting a translation property
            return getNode(parentPath).getProperty(StringUtils.substringAfterLast(path, "/"));
        } else if (StringUtils.substringAfterLast(path, "/").startsWith(TRANSLATION_NODE_NAME_BASE)) {
            // Getting translation node
            return handleI18nNode(parentPath, path);
        } else if (StringUtils.substringAfterLast(parentPath, "/").equals(ExternalDataAcl.ACL_NODE_NAME)
                && repository.getDataSource() instanceof ExternalDataSource.AccessControllable) {
            // Getting ace node or acl property
            String last = StringUtils.substringAfterLast(path, "/");
            if (last.startsWith(ExternalDataAce.Type.DENY.toString())
                    || last.startsWith(ExternalDataAce.Type.GRANT.toString())) {
                // get the ace node
                return handleAceNode(parentPath, path, last);
            } else {
                // get the property
                return getNode(parentPath).getProperty(last);
            }
        } else if (StringUtils.substringAfterLast(path, "/").equals(ExternalDataAcl.ACL_NODE_NAME)
                && repository.getDataSource() instanceof ExternalDataSource.AccessControllable) {
            // Getting acl node
            return handleAclNode(parentPath, path);
        } else if ((StringUtils.substringAfterLast(parentPath, "/")
                .startsWith(ExternalDataAce.Type.GRANT.toString())
                || StringUtils.substringAfterLast(path, "/").startsWith(ExternalDataAce.Type.DENY.toString()))
                && StringUtils.substringBeforeLast(parentPath, "/").endsWith("/j:acl")
                && repository.getDataSource() instanceof ExternalDataSource.AccessControllable) {
            // Getting ace node property
            return getNode(parentPath).getProperty(StringUtils.substringAfterLast(path, "/"));
        } else {
            String itemName = StringUtils.substringAfterLast(path, "/");
            if (getRepository().getStoreProvider().getReservedNodes().contains(itemName)) {
                throw new PathNotFoundException(path);
            }
            // Try to get the item as a node
            ExternalContentStoreProvider.setCurrentSession(this);
            try {
                ExternalData data = repository.getDataSource().getItemByPath(path);
                final ExternalNodeImpl node = new ExternalNodeImpl(data, this);
                registerNode(node);
                return node;
            } catch (PathNotFoundException e) {
                // Or a property in the parent node
                ExternalNodeImpl parentFromPath = getFromCacheByPath(parentPath);
                if (parentFromPath == null) {
                    ExternalData data = repository.getDataSource().getItemByPath(parentPath);
                    final ExternalNodeImpl node = new ExternalNodeImpl(data, this);
                    registerNode(node);
                    parentFromPath = node;
                }
                return parentFromPath.getProperty(itemName);
            } finally {
                ExternalContentStoreProvider.removeCurrentSession();
            }
        }
    } catch (PathNotFoundException e) {
        // In case item is not found in provider, lookup in extension provider if available
        if (getExtensionSession() != null && !StringUtils.equals("/", path)) {
            Item item = getExtensionSession().getItem(repository.getStoreProvider().getMountPoint() + path);
            if ((item.isNode() ? (Node) item : item.getParent()).isNodeType("jnt:externalProviderExtension")) {
                throw e;
            }
            return item.isNode() ? new ExtensionNode((Node) item, path, this)
                    : new ExtensionProperty((Property) item, path, this,
                            new ExtensionNode(item.getParent(), parentPath, this));
        } else {
            throw e;
        }
    }
}

From source file:org.jahia.modules.external.ExternalSessionImpl.java

private Item handleAceNode(String parentPath, String path, String last) throws RepositoryException {
    ExternalData parentObject = getParent(StringUtils.substringBeforeLast(parentPath, "/"));
    if (parentObject.getExternalDataAcl() == null || parentObject.getExternalDataAcl().getAce(last) == null) {
        throw new PathNotFoundException(path);
    }//from  w w  w  .j  a v a  2  s  .  c  o  m

    ExternalDataAce externalDataAce = parentObject.getExternalDataAcl().getAce(last);
    ExternalData ace = new ExternalData(ACE_PREFIX + last + ":" + parentObject.getId(), path,
            ExternalDataAce.ACE_NODE_TYPE, externalDataAce.getProperties());

    final ExternalNodeImpl node = new ExternalNodeImpl(ace, this);
    registerNode(node);
    return node;
}

From source file:org.jahia.modules.external.ExternalSessionImpl.java

protected String[] getI18nPropertyValues(ExternalData data, String lang, String propertyName)
        throws PathNotFoundException {
    ExternalDataSource dataSource = repository.getDataSource();
    if (dataSource instanceof ExternalDataSource.LazyProperty) {
        ExternalContentStoreProvider.setCurrentSession(this);
        try {//from w ww .  ja va 2 s .c  o m
            return ((ExternalDataSource.LazyProperty) dataSource).getI18nPropertyValues(
                    StringUtils.substringBeforeLast(data.getPath(), "/"), lang, propertyName);
        } finally {
            ExternalContentStoreProvider.removeCurrentSession();
        }
    } else {
        throw new PathNotFoundException(repository.getProviderKey() + " doesn't support lazy properties");
    }
}

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 ww w .j  av a2 s  .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 {/* w  ww. j av a  2  s.  c  o m*/
    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//from w ww.j a  v  a 2s .  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  v a 2s  .  com
        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 {//  w w  w  .j av  a2 s. com
        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

@Override
public void saveItem(ExternalData data) throws RepositoryException {
    super.saveItem(data);
    boolean hasProperties = false;
    try {/* w  ww  .  j ava2s  .c o  m*/
        ExtendedNodeType type = NodeTypeRegistry.getInstance().getNodeType(data.getType());

        if (type.isNodeType(JNT_DEFINITION_FILE)) {
            checkCndFormat(data);
            hasProperties = saveEditableFile(data, type);
            try {
                registerCndFiles(getRealFile(data.getPath()));
            } catch (FileSystemException e) {
                throw new RepositoryException("Failed to read file " + data.getPath(), e);
            } catch (Exception e) {
                if (e instanceof RepositoryException) {
                    throw (RepositoryException) e;
                } else {
                    throw new RepositoryException("Couldn't save file " + data.getPath(), e);
                }
            }
        } else if (type.isNodeType(JNT_EDITABLE_FILE)) {
            hasProperties = saveEditableFile(data, type);
        } else if (type.isNodeType(JNT_NODE_TYPE)) {
            saveNodeType(data);
        } else if (type.isNodeType("jnt:propertyDefinition")) {
            savePropertyDefinition(data);
        } else if (type.isNodeType("jnt:childNodeDefinition")) {
            saveChildNodeDefinition(data);
        } else if (type.isNodeType("jnt:namespaceDefinition")) {
            registerNamespace(data);
        }
    } catch (NoSuchNodeTypeException e) {
        logger.error("Unknown type", e);
        throw e;
    }
    SourceControlManagement sourceControl = module.getSourceControl();
    if (sourceControl != null) {
        String path = data.getPath();
        String pathLoweCase = path.toLowerCase();
        if (!pathLoweCase.contains(CND_SLASH)) {
            if (pathLoweCase.endsWith("/" + Constants.JCR_CONTENT)) {
                path = path.substring(0, path.indexOf("/" + Constants.JCR_CONTENT));
            }
            try {
                sourceControl.add(getRealFile(path));
                if (hasProperties) {
                    sourceControl.add(getRealFile(
                            StringUtils.substringBeforeLast(data.getPath(), ".") + PROPERTIES_EXTENSION));
                }
            } catch (IOException e) {
                logger.error("Failed to add file " + path + " to source control", e);
                throw new RepositoryException("Failed to add file " + path + " to source control", e);
            }
        } else {
            sourceControl.invalidateStatusCache();
        }
    }
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

private void saveProperties(ExternalData data) throws RepositoryException {
    OutputStream outputStream = null;
    try {//from  www  .j  a va2  s . c  om
        ExtendedNodeType propertiesType = NodeTypeRegistry.getInstance()
                .getNodeType(Constants.JAHIAMIX_VIEWPROPERTIES);
        Map<String, ExtendedPropertyDefinition> propertyDefinitionMap = propertiesType
                .getDeclaredPropertyDefinitionsAsMap();
        Properties properties = new SortedProperties();
        for (Map.Entry<String, String[]> property : data.getProperties().entrySet()) {
            if (propertyDefinitionMap.containsKey(property.getKey())) {
                String[] v = property.getValue();
                if (v != null) {
                    String propertyValue = StringUtils.join(v, ",");
                    if (propertyDefinitionMap.get(property.getKey()).getRequiredType() != PropertyType.BOOLEAN
                            || !propertyValue.equals("false")) {
                        properties.put(property.getKey(), propertyValue);
                    }
                }
            }
        }
        FileObject file = getFile(StringUtils.substringBeforeLast(data.getPath(), ".") + PROPERTIES_EXTENSION);
        Properties original = new Properties();
        if (file.exists()) {
            original.load(file.getContent().getInputStream());
            for (String s : propertyDefinitionMap.keySet()) {
                original.remove(s);
            }
        }
        properties.putAll(original);
        if (!properties.isEmpty()) {
            outputStream = file.getContent().getOutputStream();
            properties.store(outputStream, data.getPath());
        } else {
            if (file.exists()) {
                file.delete();
            }
        }
        ResourceBundle.clearCache();
    } catch (FileSystemException e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException("Failed to write source code", e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException("Failed to write source code", e);
    } catch (NoSuchNodeTypeException e) {
        logger.error("Unable to find type : " + data.getType() + " for node " + data.getPath(), e);
        throw e;
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}