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.services.content.rules.RulesListener.java

public void onEvent(EventIterator eventIterator) {
    final int operationType = ((JCREventIterator) eventIterator).getOperationType();

    final JCRSessionWrapper session = ((JCREventIterator) eventIterator).getSession();
    final String userId = session.getUser() != null ? session.getUser().getName() : null;
    final String userRealm = session.getUser() != null ? session.getUser().getRealm() : null;
    final Locale locale = session.getLocale();

    final Map<String, AddedNodeFact> eventsMap = new HashMap<String, AddedNodeFact>();

    if (Boolean.TRUE.equals(inRules.get())) {
        return;/*from w  ww  .  j  a va  2 s  . c o m*/
    }

    if (ruleBase == null || SettingsBean.getInstance().isDevelopmentMode() && lastModified() > lastRead) {
        try {
            initRules();
        } catch (Exception e) {
            logger.error("Cannot compile rules", e);
        }
        if (ruleBase == null) {
            return;
        }
    }

    final List<Event> events = new ArrayList<Event>();
    while (eventIterator.hasNext()) {
        Event event = eventIterator.nextEvent();
        if (!isExternal(event)) {
            events.add(event);
        }
    }
    if (events.isEmpty()) {
        return;
    }

    try {
        JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(session.getUser(), workspace, locale,
                new JCRCallback<Object>() {

                    Map<String, String> copies = null;

                    public Object doInJCR(JCRSessionWrapper s) throws RepositoryException {
                        Iterator<Event> it = events.iterator();

                        final List<Object> list = new ArrayList<Object>();

                        String nodeFactOperationType = getNodeFactOperationType(operationType);
                        while (it.hasNext()) {
                            Event event = it.next();
                            String path = event.getPath();
                            try {
                                if (!path.startsWith("/jcr:system/")) {
                                    String eventUuid = event.getIdentifier();
                                    int type = event.getType();
                                    if (type == Event.NODE_ADDED) {
                                        JCRNodeWrapper n = eventUuid != null ? s.getNodeByIdentifier(eventUuid)
                                                : s.getNode(path);
                                        if (n.isNodeType("jmix:observable")
                                                && !n.isNodeType("jnt:translation")) {
                                            final String identifier = n.getIdentifier();
                                            AddedNodeFact rn = eventsMap.get(identifier);
                                            if (rn == null) {
                                                rn = getFact(n, session);
                                                rn.setOperationType(nodeFactOperationType);
                                                final JCRSiteNode resolveSite = n.getResolveSite();
                                                if (resolveSite != null) {
                                                    rn.setInstalledModules(
                                                            resolveSite.getAllInstalledModules());
                                                } else {
                                                    rn.setInstalledModules(new ArrayList<String>());
                                                }
                                                eventsMap.put(identifier, rn);
                                            }
                                            list.add(rn);
                                        }
                                    } else if (type == Event.PROPERTY_ADDED || type == Event.PROPERTY_CHANGED) {
                                        String propertyName = path.substring(path.lastIndexOf('/') + 1);
                                        if (!propertiesToIgnore.contains(propertyName)) {
                                            try {
                                                JCRPropertyWrapper p = null;
                                                try {
                                                    p = (JCRPropertyWrapper) s.getItem(path);
                                                } catch (PathNotFoundException e) {
                                                    // the node could be moved in between
                                                    try {
                                                        p = s.getNodeByIdentifier(eventUuid)
                                                                .getProperty(propertyName);
                                                    } catch (RepositoryException infe) {
                                                        throw e;
                                                    }
                                                }

                                                JCRNodeWrapper parent = p.getParent();
                                                if (parent.isNodeType("jnt:translation")) {
                                                    parent = parent.getParent();
                                                }
                                                if (parent.isNodeType(Constants.NT_RESOURCE)
                                                        || parent.isNodeType("jmix:observable")) {
                                                    AddedNodeFact rn;
                                                    if (parent.isNodeType(Constants.MIX_REFERENCEABLE)) {
                                                        final String identifier = parent.getIdentifier();
                                                        rn = eventsMap.get(identifier);
                                                        if (rn == null) {
                                                            rn = type == Event.PROPERTY_ADDED
                                                                    ? getFact(parent, session)
                                                                    : new AddedNodeFact(parent);
                                                            rn.setOperationType(nodeFactOperationType);
                                                            final JCRSiteNode resolveSite = parent
                                                                    .getResolveSite();
                                                            if (resolveSite != null) {
                                                                rn.setInstalledModules(
                                                                        resolveSite.getAllInstalledModules());
                                                            } else {
                                                                rn.setInstalledModules(new ArrayList<String>());
                                                            }
                                                            eventsMap.put(identifier, rn);
                                                        }
                                                    } else {
                                                        rn = new AddedNodeFact(parent);
                                                        rn.setOperationType(nodeFactOperationType);
                                                        final JCRSiteNode resolveSite = parent.getResolveSite();
                                                        if (resolveSite != null) {
                                                            rn.setInstalledModules(
                                                                    resolveSite.getAllInstalledModules());
                                                        } else {
                                                            rn.setInstalledModules(new ArrayList<String>());
                                                        }
                                                    }
                                                    list.add(new ChangedPropertyFact(rn, p));
                                                }
                                            } catch (PathNotFoundException pnfe) {
                                                if (JCRSessionFactory.getInstance().getProvider(path,
                                                        false) == null || logger.isDebugEnabled()) {
                                                    logger.error("Couldn't access path {}, ignoring it.", pnfe);
                                                }
                                            }
                                        } else if (propertyName.equals("j:published")) {
                                            JCRNodeWrapper n = eventUuid != null
                                                    ? s.getNodeByIdentifier(eventUuid)
                                                    : s.getNode(path);
                                            if (n.isNodeType("jmix:observable")
                                                    && !n.isNodeType("jnt:translation")) {
                                                final PublishedNodeFact e = new PublishedNodeFact(n);
                                                e.setOperationType(nodeFactOperationType);
                                                final JCRSiteNode resolveSite = n.getResolveSite();
                                                if (resolveSite != null) {
                                                    e.setInstalledModules(resolveSite.getAllInstalledModules());
                                                } else {
                                                    e.setInstalledModules(new ArrayList<String>());
                                                }
                                                list.add(e);
                                            }
                                        }
                                    } else if (type == Event.NODE_REMOVED) {
                                        String parentPath = null;
                                        try {
                                            parentPath = StringUtils.substringBeforeLast(path, "/");
                                            JCRNodeWrapper parent = s.getNode(parentPath);
                                            final String identifier = parent.getIdentifier();
                                            AddedNodeFact w = eventsMap.get(identifier);
                                            if (w == null) {
                                                w = new AddedNodeFact(parent);
                                                w.setOperationType(nodeFactOperationType);
                                                final JCRSiteNode resolveSite = parent.getResolveSite();
                                                if (resolveSite != null) {
                                                    w.setInstalledModules(resolveSite.getAllInstalledModules());
                                                } else {
                                                    w.setInstalledModules(new ArrayList<String>());
                                                }
                                                eventsMap.put(identifier, w);
                                            }

                                            final DeletedNodeFact e = new DeletedNodeFact(w, path);
                                            e.setIdentifier(eventUuid);
                                            e.setSession(s);
                                            e.setOperationType(nodeFactOperationType);
                                            e.setTypes(JCRObservationManager.getNodeTypesForDeletedNode(event));
                                            list.add(e);
                                        } catch (PathNotFoundException e) {
                                        }
                                    } else if (type == Event.PROPERTY_REMOVED) {
                                        int index = path.lastIndexOf('/');
                                        String nodePath = path.substring(0, index);
                                        String propertyName = path.substring(index + 1);
                                        if (!propertiesToIgnore.contains(propertyName)) {
                                            try {
                                                JCRNodeWrapper n = s.getNode(nodePath);
                                                String key = n.isNodeType(Constants.MIX_REFERENCEABLE)
                                                        ? n.getIdentifier()
                                                        : n.getPath();
                                                AddedNodeFact rn = eventsMap.get(key);
                                                if (rn == null) {
                                                    rn = new AddedNodeFact(n);
                                                    rn.setOperationType(nodeFactOperationType);
                                                    final JCRSiteNode resolveSite = n.getResolveSite();
                                                    if (resolveSite != null) {
                                                        rn.setInstalledModules(
                                                                resolveSite.getAllInstalledModules());
                                                    } else {
                                                        rn.setInstalledModules(new ArrayList<String>());
                                                    }
                                                    eventsMap.put(key, rn);
                                                }
                                                list.add(new DeletedPropertyFact(rn, propertyName));
                                            } catch (PathNotFoundException e) {
                                                // ignore if parent has also been deleted ?
                                            }
                                        }
                                    } else if (type == Event.NODE_MOVED) {
                                        JCRNodeWrapper n = eventUuid != null ? s.getNodeByIdentifier(eventUuid)
                                                : s.getNode(path);
                                        if (n.isNodeType("jmix:observable")
                                                && !n.isNodeType("jnt:translation")) {
                                            final MovedNodeFact e = new MovedNodeFact(n,
                                                    (String) event.getInfo().get("srcAbsPath"));
                                            e.setOperationType(nodeFactOperationType);
                                            final JCRSiteNode resolveSite = n.getResolveSite();
                                            if (resolveSite != null) {
                                                e.setInstalledModules(resolveSite.getAllInstalledModules());
                                            } else {
                                                e.setInstalledModules(new ArrayList<String>());
                                            }
                                            list.add(e);
                                        }
                                    }
                                }
                            } catch (PathNotFoundException pnfe) {
                                logger.debug(
                                        "Error when executing event. Unable to find node or property for path: "
                                                + path,
                                        pnfe);
                            } catch (ItemNotFoundException infe) {
                                logger.debug(
                                        "Error when executing event. Unable to find node or property for item: "
                                                + event.getIdentifier(),
                                        infe);
                            } catch (Exception e) {
                                logger.error("Error when executing event", e);
                            }
                        }
                        if (!list.isEmpty()) {
                            long time = System.currentTimeMillis();
                            if (logger.isDebugEnabled()) {
                                if (list.size() > 3) {
                                    logger.debug("Executing rules for " + list.subList(0, 3) + " ... and "
                                            + (list.size() - 3) + " other nodes");
                                } else {
                                    logger.debug("Executing rules for " + list);
                                }
                            }
                            final List<Updateable> delayedUpdates = new ArrayList<Updateable>();

                            Map<String, Object> globals = getGlobals(userId, userRealm, delayedUpdates);

                            try {
                                inRules.set(Boolean.TRUE);
                                list.add(new OperationTypeFact(nodeFactOperationType));
                                executeRules(list, globals);

                                if (list.size() > 3) {
                                    logger.info("Rules executed for " + workspace + " " + list.subList(0, 3)
                                            + " ... and " + (list.size() - 3) + " other nodes in "
                                            + (System.currentTimeMillis() - time) + "ms");
                                } else {
                                    logger.info("Rules executed for " + workspace + " " + list + " in "
                                            + (System.currentTimeMillis() - time) + "ms");
                                }

                                if (s.hasPendingChanges()) {
                                    s.save();
                                }
                            } finally {
                                inRules.set(null);
                            }

                            if (!delayedUpdates.isEmpty()) {
                                TimerTask t = new DelayedUpdatesTimerTask(userId, userRealm, delayedUpdates);
                                rulesTimer.schedule(t, UPDATE_DELAY_FOR_LOCKED_NODE);
                            }
                        }
                        return null;
                    }

                    @SuppressWarnings("unchecked")
                    private AddedNodeFact getFact(JCRNodeWrapper node, JCRSessionWrapper session)
                            throws RepositoryException {
                        if (copies == null) {
                            copies = session.getUuidMapping().isEmpty() ? Collections.<String, String>emptyMap()
                                    : MapUtils.invertMap(session.getUuidMapping());
                        }
                        String sourceUuid = !copies.isEmpty() ? copies.get(node.getIdentifier()) : null;
                        return sourceUuid != null
                                ? new CopiedNodeFact(node, sourceUuid,
                                        session.getUuidMapping().containsKey("top-" + sourceUuid))
                                : new AddedNodeFact(node);
                    }
                });
    } catch (Exception e) {
        logger.error("Error when executing event", e);
    }
}

From source file:org.jahia.services.content.rules.RulesNotificationService.java

private void sendMail(String template, Object user, String toMail, String fromMail, String ccList,
        String bcclist, Locale locale, KnowledgeHelper drools)
        throws RepositoryException, ScriptException, IOException {
    if (!notificationService.isEnabled()) {
        return;//  w ww .j  a v a 2  s . c o  m
    }
    if (StringUtils.isEmpty(toMail)) {
        logger.warn("A mail couldn't be sent because to: has no recipient");
        return;
    }

    // Resolve template :
    String extension = StringUtils.substringAfterLast(template, ".");
    ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
    ScriptContext scriptContext = new SimpleScriptContext();
    final Bindings bindings = new SimpleBindings();
    bindings.put("currentUser", user);
    bindings.put("contextPath", Jahia.getContextPath());
    bindings.put("currentLocale", locale);
    final Object object = drools.getMatch().getTuple().getHandle().getObject();
    JCRNodeWrapper node = null;
    if (object instanceof AbstractNodeFact) {
        node = ((AbstractNodeFact) object).getNode();
        bindings.put("currentNode", node);
        final int siteURLPortOverride = SettingsBean.getInstance().getSiteURLPortOverride();
        bindings.put("servername",
                "http" + (siteURLPortOverride == 443 ? "s" : "") + "://" + node.getResolveSite().getServerName()
                        + ((siteURLPortOverride != 0 && siteURLPortOverride != 80 && siteURLPortOverride != 443)
                                ? ":" + siteURLPortOverride
                                : ""));
    }
    InputStream scriptInputStream = JahiaContextLoaderListener.getServletContext()
            .getResourceAsStream(template);
    if (scriptInputStream == null && node != null) {
        RulesListener rulesListener = RulesListener.getInstance(node.getSession().getWorkspace().getName());
        String packageName = drools.getRule().getPackageName();
        JahiaTemplateManagerService jahiaTemplateManagerService = ServicesRegistry.getInstance()
                .getJahiaTemplateManagerService();
        for (Map.Entry<String, String> entry : rulesListener.getModulePackageNameMap().entrySet()) {
            if (packageName.equals(entry.getValue())) {
                JahiaTemplatesPackage templatePackage = jahiaTemplateManagerService
                        .getTemplatePackage(entry.getKey());
                Resource resource = templatePackage.getResource(template);
                if (resource != null) {
                    scriptInputStream = resource.getInputStream();
                    break;
                }
            }
        }
    }
    if (scriptInputStream != null) {
        String resourceBundleName = StringUtils.substringBeforeLast(Patterns.SLASH
                .matcher(StringUtils.substringAfter(Patterns.WEB_INF.matcher(template).replaceAll(""), "/"))
                .replaceAll("."), ".");
        String subject = "";
        try {
            ResourceBundle resourceBundle = ResourceBundles.get(resourceBundleName, locale);
            bindings.put("bundle", resourceBundle);
            subject = resourceBundle.getString("subject");
        } catch (MissingResourceException e) {
            if (node != null) {
                final Value[] values = node.getResolveSite().getProperty("j:installedModules").getValues();
                for (Value value : values) {
                    try {
                        ResourceBundle resourceBundle = ResourceBundles
                                .get(ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                                        .getTemplatePackageById(value.getString()).getName(), locale);
                        subject = resourceBundle.getString(
                                drools.getRule().getName().toLowerCase().replaceAll(" ", ".") + ".subject");
                        bindings.put("bundle", resourceBundle);
                    } catch (MissingResourceException ee) {
                        // Do nothing
                    }
                }
            }
        }
        Reader scriptContent = null;
        try {
            scriptContent = new InputStreamReader(scriptInputStream);
            scriptContext.setWriter(new StringWriter());
            // The following binding is necessary for Javascript, which doesn't offer a console by default.
            bindings.put("out", new PrintWriter(scriptContext.getWriter()));
            scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
            scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                    ScriptContext.GLOBAL_SCOPE);
            scriptEngine.eval(scriptContent, scriptContext);
            StringWriter writer = (StringWriter) scriptContext.getWriter();
            String body = writer.toString();
            notificationService.sendMessage(fromMail, toMail, ccList, bcclist, subject, null, body);
        } finally {
            if (scriptContent != null) {
                IOUtils.closeQuietly(scriptContent);
            }
        }
    }
}

From source file:org.jahia.services.importexport.DocumentViewImportHandler.java

public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
        throws SAXException {
    if (error > 0) {
        error++;/*from  ww w  .  j  av  a2 s .c o  m*/
        return;
    }

    batchCount++;
    // do a session.save each maxBatch
    if (batchCount > maxBatch) {
        try {
            ReferencesHelper.resolveCrossReferences(session, references, false);
            session.save(JCRObservationManager.IMPORT);
            batchCount = 0;
        } catch (CompositeConstraintViolationException e) {
            logger.error("Constraint violation exception", e);
            throw new SAXException("Cannot save batch", e);
        } catch (ConstraintViolationException e) {
            if (e.getMessage().contains("mandatory child node") && nodes.size() > 1
                    && e.getMessage().startsWith(nodes.peek().getPath())) {
                // save on the next node when next node is needed (like content node for files)
                batchCount = maxBatch - 1;
            } else {
                throw new SAXException("Cannot save batch", e);
            }
        } catch (RepositoryException e) {
            throw new SAXException("Cannot save batch", e);
        }
    }

    if (ugcLevel > 0 || "live".equals(atts.getValue("j:originWS"))) {
        if (importUserGeneratedContent) {
            ugcLevel++;
        } else {
            error++;
            return;
        }
    }

    if (atts.getIndex(ImportExportBaseService.STATIC_MOUNT_POINT_ATTR) > -1) {
        String providerKey = atts.getValue(ImportExportBaseService.STATIC_MOUNT_POINT_ATTR);
        Map<String, JCRStoreProvider> providers = JCRSessionFactory.getInstance().getProviders();
        if (!providers.containsKey(providerKey) || !providers.get(providerKey).isAvailable()) {
            error++;
            return;
        }
    }
    if (atts.getIndex(ImportExportBaseService.DYNAMIC_MOUNT_POINT_ATTR) > -1) {
        try {
            String providerKey = session
                    .getNode(atts.getValue(ImportExportBaseService.DYNAMIC_MOUNT_POINT_ATTR)).getIdentifier();
            Map<String, JCRStoreProvider> providers = JCRSessionFactory.getInstance().getProviders();
            if (!providers.containsKey(providerKey) || !providers.get(providerKey).isAvailable()) {
                error++;
                return;
            }
        } catch (RepositoryException e) {
            error++;
            return;
        }
    }

    String decodedLocalName = ISO9075.decode(localName);

    for (Map.Entry<Pattern, String> entry : replacements.entrySet()) {
        decodedLocalName = entry.getKey().matcher(decodedLocalName).replaceAll(entry.getValue());
    }

    String decodedQName = qName.replace(localName, decodedLocalName);

    if (rootBehavior == ROOT_BEHAVIOUR_RENAME && pathes.size() <= 1
            && !pathMapping.containsKey(pathes.peek() + "/" + decodedQName)) {
        String newName = JCRContentUtils.findAvailableNodeName(nodes.peek(), decodedQName);
        if (!decodedQName.equals(newName)) {
            pathMapping.put(nodes.peek().getPath() + "/" + decodedQName + "/",
                    nodes.peek().getPath() + "/" + newName + "/");
            decodedQName = newName;
        }
    }

    if (rootBehavior == ROOT_BEHAVIOUR_IGNORE && pathes.size() <= 1) {
        session.getPathMapping().put("/" + decodedQName + "/",
                nodes.peek().getPath().equals("/") ? "/" : nodes.peek().getPath() + "/");
        pathes.push("");
        return;
    }

    pathes.push(pathes.peek() + "/" + decodedQName);

    try {

        if (ignorePath != null) {
            nodes.push(null);
            return;
        }

        String path;
        if (nodes.peek().getPath().equals("/")) {
            path = "/" + decodedQName;
        } else {
            path = nodes.peek().getPath() + "/" + decodedQName;
        }

        if (pathes.peek().startsWith("/users/") && "jnt:user".equals(atts.getValue("jcr:primaryType"))) {
            Matcher m = Pattern.compile("/users/([^/]+)").matcher(pathes.peek());
            if (m.matches()) {
                path = JahiaUserManagerService.getInstance().getUserSplittingRule()
                        .getPathForUsername(m.group(1));
            }
        }

        String pt = atts.getValue(Constants.JCR_PRIMARYTYPE);

        // Create missing structure for group members
        if ("jnt:member".equals(pt) && nodes.peek().isNodeType("jnt:members")
                && "j:members".equals(nodes.peek().getName())) {
            String memberRef = atts.getValue("j:member");
            if (memberRef != null) {
                String referenceValue = getReferenceValue(memberRef);
                JCRNodeWrapper principal;
                if (referenceValue.startsWith("/")) {
                    for (String key : pathMapping.keySet()) {
                        if (referenceValue.startsWith(key)) {
                            referenceValue = StringUtils.replace(referenceValue, key, pathMapping.get(key));
                            break;
                        }
                    }
                    principal = session.getNode(referenceValue);
                } else {
                    principal = session.getNodeByIdentifier(memberRef);
                }
                JCRGroupNode groupNode = JahiaGroupManagerService.getInstance().lookupGroupByPath(
                        StringUtils.substringBeforeLast(nodes.peek().getPath(), "/"), session);
                JCRNodeWrapper member = groupNode.addMember(principal);
                if (member != null) {
                    uuids.add(member.getIdentifier());
                }
                nodes.push(member);
                return;
            }
        }

        if (pathMapping.containsKey(path + "/")) {
            path = StringUtils.substringBeforeLast(pathMapping.get(path + "/"), "/");
            decodedQName = StringUtils.substringAfter(path, "/");
        }

        if (noSubNodesImport.contains(pt)) {
            ignorePath = path;
        }
        JCRNodeWrapper child = null;

        boolean isValid = true;
        try {
            child = session.getNode(path);
            if (child.hasPermission("jcr:versionManagement") && child.isVersioned() && !child.isCheckedOut()) {
                session.checkout(child);
            }
        } catch (PathNotFoundException e) {
            isValid = false;
        }

        if (!importUserGeneratedContent || ugcLevel > 0) {
            String originalUuid = atts.getValue("jcr:uuid");
            String uuid = originalUuid;
            if (uuid != null && uuidMapping.containsKey(uuid)) {
                uuid = uuidMapping.get(uuid);
            } else if (enforceUuid) {
                uuid = null;
            }

            if (isValid && enforceUuid && uuid != null) {
                if (!child.getIdentifier().equals(uuid)) {
                    child.remove();
                    isValid = false;
                }
            }

            if (!isValid || (child.getDefinition() != null && child.getDefinition().allowsSameNameSiblings())) {
                isValid = false;
                if (nodes.peek().hasPermission("jcr:addChildNodes")) {
                    if ("jnt:acl".equals(pt) && !nodes.peek().isNodeType("jmix:accessControlled")) {
                        nodes.peek().addMixin("jmix:accessControlled");
                    }
                    Calendar created = null;
                    String createdBy = null;
                    Calendar lastModified = null;
                    String lastModifiedBy = null;
                    if (!StringUtils.isEmpty(atts.getValue("jcr:created"))) {
                        created = ISO8601.parse(atts.getValue("jcr:created"));
                    }
                    if (!StringUtils.isEmpty(atts.getValue("jcr:lastModified"))) {
                        lastModified = ISO8601.parse(atts.getValue("jcr:lastModified"));
                    }
                    if (!StringUtils.isEmpty(atts.getValue("jcr:createdBy"))) {
                        createdBy = atts.getValue("jcr:createdBy");
                    }
                    if (!StringUtils.isEmpty(atts.getValue("jcr:lastModifiedBy"))) {
                        lastModifiedBy = atts.getValue("jcr:lastModifiedBy");
                    }

                    //                    String share = atts.getValue("j:share");
                    //                    if (!StringUtils.isEmpty(uuid) && uuidMapping.containsKey(uuid)) {
                    //                        child = nodes.peek().clone(session.getNodeByUUID(uuidMapping.get(uuid)), decodedQName);
                    //                    } else if (!StringUtils.isEmpty(share)) {
                    //                        for (Map.Entry<String, String> entry : pathMapping.entrySet()) {
                    //                            if (share.startsWith(entry.getKey())) {
                    //                                share = entry.getValue() + StringUtils.substringAfter(share, entry.getKey());
                    //                                break;
                    //                            }
                    //                        }
                    //                        child = nodes.peek().clone(session.getNode(share), decodedQName);
                    //                    } else {
                    if (!StringUtils.isEmpty(uuid)) {
                        switch (uuidBehavior) {
                        case IMPORT_UUID_COLLISION_THROW:
                            try {
                                JCRNodeWrapper node = session.getNodeByUUID(uuid);
                                if (node.isNodeType("mix:shareable")) {
                                    // ..
                                } else {
                                    throw new ItemExistsException(uuid);
                                }
                            } catch (ItemNotFoundException e) {
                            }
                        case IMPORT_UUID_COLLISION_REMOVE_EXISTING:
                            try {
                                JCRNodeWrapper node = session.getNodeByUUID(uuid);
                                // make sure conflicting node is not importTargetNode or an ancestor thereof
                                if (nodes.peek().getPath().startsWith(node.getPath())) {
                                    String msg = "cannot remove ancestor node";
                                    logger.debug(msg);
                                    throw new ConstraintViolationException(msg);
                                }
                                // remove conflicting
                                node.remove();
                            } catch (ItemNotFoundException e) {
                            }
                            break;
                        case IMPORT_UUID_COLLISION_REPLACE_EXISTING:
                            throw new UnsupportedOperationException();

                        case IMPORT_UUID_CREATE_NEW:
                            uuid = null;

                            break;
                        case IMPORT_UUID_COLLISION_MOVE_EXISTING:
                            try {
                                JCRNodeWrapper node = session.getNodeByUUID(uuid);
                                // make sure conflicting node is not importTargetNode or an ancestor thereof
                                if (nodes.peek().getPath().startsWith(node.getPath())) {
                                    String msg = "cannot move ancestor node";
                                    logger.debug(msg);
                                    throw new ConstraintViolationException(msg);
                                }
                                if (!node.getPath().equals(path)) {
                                    // move conflicting
                                    session.move(node.getPath(), path);
                                    node = session.getNodeByUUID(uuid);
                                }
                                child = node;
                                isValid = true;
                            } catch (ItemNotFoundException e) {
                            }
                            break;
                        }
                    }
                    if (!isValid) {
                        try {
                            session.checkout(nodes.peek());
                        } catch (PathNotFoundException e) {
                            logger.error("Couldn't find parent node " + nodes.peek(), e);
                        }
                        try {
                            checkDependencies(path, pt, atts);
                            child = nodes.peek().addNode(decodedQName, pt, uuid, created, createdBy,
                                    lastModified, lastModifiedBy);
                        } catch (ConstraintViolationException e) {
                            if (pathes.size() <= 2 && nodes.peek().getName().equals(decodedQName)
                                    && nodes.peek().getPrimaryNodeTypeName().equals(pt)) {
                                session.getPathMapping().put("/" + decodedQName,
                                        nodes.peek().getPath().equals("/") ? "" : nodes.peek().getPath());
                                return;
                            } else {
                                throw e;
                            }
                        }
                    }

                    addMixins(child, atts);
                    uploadFile(atts, decodedQName, path, child);

                    setAttributes(child, atts);
                    uuids.add(child.getIdentifier());
                    if (child.isFile() && currentFilePath == null) {
                        currentFilePath = child.getPath();
                    }
                    if (child.isNodeType(Constants.JAHIANT_MOUNTPOINT)) {
                        session.save(JCRObservationManager.IMPORT);
                    }
                    //                    }
                } else {
                    throw new AccessDeniedException(
                            "Missing jcr:addChildNodes permission for user " + session.getUser().getName());
                }
            } else {
                if (child.hasPermission("jcr:modifyProperties") && child.isCheckedOut()) {
                    if (!noUpdateTypes.contains(child.getPrimaryNodeType().getName())
                            && atts.getValue("jcr:primaryType") != null) {
                        addMixins(child, atts);
                        setAttributes(child, atts);
                        uploadFile(atts, decodedQName, path, child);
                    }
                }
                uuids.add(child.getIdentifier());
            }
            if (originalUuid != null) {
                uuidMapping.put(originalUuid, child.getIdentifier());
            }
            if (nodes.peek().getPrimaryNodeType().hasOrderableChildNodes()
                    && nodes.peek().hasPermission("jcr:write")
                    && !JCRSessionFactory.getInstance().getMountPoints().containsKey(child.getPath())) {
                nodes.peek().orderBefore(decodedQName, null);
            }
        }
        if (child == null) {
            error++;
        } else {
            nodes.push(child);
        }
    } catch (NoSuchNodeTypeException e) {
        if (logger.isDebugEnabled()) {
            logger.warn("Cannot import " + pathes.pop(), e);
        } else {
            logger.warn("Cannot import \"{}\" due to missing node type definition \"{}\"", pathes.pop(),
                    e.getMessage());
        }
        error++;
    } catch (AccessDeniedException e) {
        if (logger.isDebugEnabled()) {
            logger.warn("Cannot import " + pathes.pop() + getLocation(), e);
        } else {
            logger.warn("Cannot import \"{}\" due to \"{}\"", pathes.pop(), e.getMessage());
        }
        error++;
    } catch (RepositoryException re) {
        logger.error("Cannot import " + pathes.pop() + getLocation(), re);
        error++;
    } catch (Exception re) {
        throw new SAXException(re);
    }
}

From source file:org.jahia.services.importexport.FilesAclImportHandler.java

public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    if ("file".equals(localName) && ImportExportBaseService.JAHIA_URI.equals(uri)) {
        String path = attributes.getValue(ImportExportBaseService.JAHIA_URI, "path");
        String acl = attributes.getValue(ImportExportBaseService.JAHIA_URI, "fileacl");

        InputStream content = null;

        try {/*w w  w .  java2  s .c  o  m*/
            boolean contentFound = false;
            if (this.filePath != null) {
                content = findExtractedContent(path);
            } else {
                contentFound = findContent(path);
            }

            if (path.startsWith("/shared") || path.startsWith("/users")) {
                path = "/sites/" + site.getSiteKey() + "/files" + path;
            } /*
              // DB-HOT-28
              else if (path.startsWith("/users/")) {
              Matcher m = Pattern.compile("/users/([^/]+)(/.*)?").matcher(path);
              if (m.matches()) {
                  path = ServicesRegistry.getInstance().getJahiaUserManagerService().getUserSplittingRule().getPathForUsername(m.group(1));
                  path = path + "/files" + ((m.group(2) != null) ? m.group(2) : "");
              }
              }*/

            if (session.itemExists(path)) {
                return;
            }
            JCRNodeWrapper f;
            path = JCRContentUtils.escapeNodePath(path);
            path = Patterns.COLON.matcher(path).replaceAll("_");

            String parentPath = StringUtils.substringBeforeLast(path, "/");
            try {
                f = session.getNode(parentPath);
            } catch (PathNotFoundException e) {
                f = ImportExportBaseService.getInstance().ensureDir(session, parentPath, site);
            }

            Calendar created = new GregorianCalendar();
            String creationDate = attributes.getValue("dav:creationdate");
            if (creationDate != null) {
                if (creationDate.endsWith("Z")) {
                    created.setTime(DATE_FORMAT_Z.parseDateTime(creationDate).toDate());
                } else {
                    created.setTime(DATE_FORMAT.parseDateTime(creationDate).toDate());
                }
            }
            Calendar lastModified = new GregorianCalendar();
            String modificationDate = attributes.getValue("dav:modificationdate");
            if (modificationDate != null) {
                if (modificationDate.endsWith("Z")) {
                    lastModified.setTime(DATE_FORMAT_Z.parseDateTime(modificationDate).toDate());
                } else {
                    lastModified.setTime(DATE_FORMAT.parseDateTime(modificationDate).toDate());
                }
            }
            String createdBy = attributes.getValue("dav:creationuser");
            String lastModifiedBy = attributes.getValue("dav:modificationuser");
            final String itemType = "file".equals(attributes.getValue("jahia:itemType"))
                    || StringUtils.isNotBlank(attributes.getValue("dav:getcontenttype")) ? "file" : "folder";
            final boolean binaryAvailable = content != null && !contentFound;
            final boolean isCorruptedFile = !binaryAvailable && "file".equals(itemType);

            if (isCorruptedFile) {
                logger.error(MessageFormat.format("Impossible to import the file {0} as its binary is missing",
                        path));
                corruptedFilesLogger.error(path);
            } else {
                checkoutNode(f);
                if (!binaryAvailable) {
                    f = f.addNode(StringUtils.substringAfterLast(path, "/"), "jnt:folder", null, created,
                            createdBy, lastModified, lastModifiedBy);
                } else {
                    f = f.addNode(StringUtils.substringAfterLast(path, "/"), "jnt:file", null, created,
                            createdBy, lastModified, lastModifiedBy);
                    String contentType = attributes.getValue("dav:getcontenttype");
                    if (content != null) {
                        if (contentType == null || contentType.length() == 0
                                || "application/binary".equals(contentType)) {
                            if (logger.isDebugEnabled()) {
                                logger.debug(
                                        "We don't have a proper content type for file content {}, let's force its detection",
                                        f.getPath());
                            }
                            // We don't have a proper content type, let's force its detection
                            contentType = null;
                        }
                        f.getFileContent().uploadFile(content, contentType);
                    } else {
                        f.getFileContent().uploadFile(zis, contentType);
                    }
                }
                if (acl != null && acl.length() > 0) {
                    StringTokenizer st = new StringTokenizer(acl, "|");
                    while (st.hasMoreElements()) {
                        String s = st.nextToken();
                        int beginIndex = s.lastIndexOf(":");

                        String principal = s.substring(0, beginIndex);

                        Set<String> grantedRoles = new HashSet<String>();
                        Set<String> removedRoles = new HashSet<String>();
                        String perm = s.substring(beginIndex + 1);
                        if (perm.charAt(0) == 'r') {
                            if (CollectionUtils.isEmpty(LegacyImportHandler.CUSTOM_FILES_READ_ROLES)) {
                                grantedRoles.addAll(LegacyImportHandler.READ_ROLES);
                            } else {
                                grantedRoles.addAll(LegacyImportHandler.CUSTOM_FILES_READ_ROLES);
                            }
                        } else {
                            if (CollectionUtils.isEmpty(LegacyImportHandler.CUSTOM_FILES_READ_ROLES)) {
                                removedRoles.addAll(LegacyImportHandler.READ_ROLES);
                            } else {
                                removedRoles.addAll(LegacyImportHandler.CUSTOM_FILES_READ_ROLES);
                            }
                        }
                        if (perm.charAt(1) == 'w') {
                            if (CollectionUtils.isEmpty(LegacyImportHandler.CUSTOM_FILES_WRITE_ROLES)) {
                                grantedRoles.addAll(LegacyImportHandler.WRITE_ROLES);
                            } else {
                                grantedRoles.addAll(LegacyImportHandler.CUSTOM_FILES_WRITE_ROLES);
                            }
                        } else {
                            if (CollectionUtils.isEmpty(LegacyImportHandler.CUSTOM_FILES_WRITE_ROLES)) {
                                removedRoles.addAll(LegacyImportHandler.WRITE_ROLES);
                            } else {
                                removedRoles.addAll(LegacyImportHandler.CUSTOM_FILES_WRITE_ROLES);
                            }
                        }

                        if (!grantedRoles.isEmpty()) {
                            f.grantRoles(principal, grantedRoles);
                        }
                        if (!removedRoles.isEmpty()) {
                            f.denyRoles(principal, removedRoles);
                        }
                    }
                }
                for (int i = 0; i < attributes.getLength(); i++) {
                    String attUri = attributes.getURI(i);
                    String attName = attributes.getLocalName(i);
                    if (!ImportExportBaseService.JAHIA_URI.equals(attUri) || (!"path".equals(attName)
                            && !"fileacl".equals(attName) && !"lastModification".equals(attName))) {
                        try {
                            setPropertyField(f.getPrimaryNodeType(), localName, f,
                                    getMappedProperty(f.getPrimaryNodeType(), attributes.getQName(i)),
                                    attributes.getValue(i));
                        } catch (RepositoryException e) {
                            logger.warn("Error importing " + localName + " " + path, e);
                        }
                    }
                }
                session.save(JCRObservationManager.IMPORT);
            }
        } catch (Exception e) {
            logger.error("error", e);
        } finally {
            IOUtils.closeQuietly(content);
        }
    }
}

From source file:org.jahia.services.importexport.FilesAclImportHandler.java

private boolean setPropertyField(ExtendedNodeType baseType, String localName, JCRNodeWrapper node,
        String propertyName, String value) throws RepositoryException {
    if (propertyName == null || "#skip".equals(propertyName)) {
        return false;
    }/* w w w . java2s.co  m*/
    JCRNodeWrapper parent = node;
    String mixinType = null;
    if (propertyName.contains("|")) {
        mixinType = StringUtils.substringBefore(propertyName, "|");
        propertyName = StringUtils.substringAfter(propertyName, "|");
    }
    if (StringUtils.contains(propertyName, "/")) {
        String parentPath = StringUtils.substringBeforeLast(propertyName, "/");
        if (parent.hasNode(parentPath)) {
            parent = parent.getNode(parentPath);
        }
        propertyName = StringUtils.substringAfterLast(propertyName, "/");
    }
    parent = checkoutNode(parent);
    if (!StringUtils.isEmpty(mixinType) && !parent.isNodeType(mixinType)) {
        parent.addMixin(mixinType);
    }

    ExtendedPropertyDefinition propertyDefinition = null;
    propertyDefinition = parent.getApplicablePropertyDefinition(propertyName);
    if (propertyDefinition == null) {
        return false;

    }
    if (propertyDefinition.isProtected()) {
        // System.out.println("protected : " + propertyName);
        return false;
    }
    Node n = parent;

    // System.out.println("setting " + propertyName);

    if (value != null && value.length() != 0 && !value.equals("<empty>")) {
        switch (propertyDefinition.getRequiredType()) {
        case PropertyType.DATE:
            GregorianCalendar cal = new GregorianCalendar();
            try {
                DateFormat df = new SimpleDateFormat(ImportExportService.DATE_FORMAT);
                Date d = df.parse(value);
                cal.setTime(d);
                n.setProperty(propertyName, cal);
            } catch (java.text.ParseException e) {
                logger.error(e.getMessage(), e);
            }
            break;

        default:
            switch (propertyDefinition.getSelector()) {
            case SelectorType.CATEGORY: {
                String[] cats = Patterns.COMMA.split(value);
                List<Value> values = new ArrayList<Value>();
                for (int i = 0; i < cats.length; i++) {
                    String cat = cats[i];
                    Query q = session.getWorkspace().getQueryManager()
                            .createQuery("select * from [jnt:category] as cat where NAME(cat) = '"
                                    + JCRContentUtils.sqlEncode(cat) + "'", Query.JCR_SQL2);
                    NodeIterator ni = q.execute().getNodes();
                    if (ni.hasNext()) {
                        values.add(session.getValueFactory().createValue(ni.nextNode()));
                    }
                }
                n.setProperty(propertyName, values.toArray(new Value[values.size()]));
                break;
            }
            case SelectorType.RICHTEXT: {
                n.setProperty(propertyName, value);
                break;
            }
            default: {
                String[] vcs = propertyDefinition.getValueConstraints();
                List<String> constraints = Arrays.asList(vcs);
                if (!propertyDefinition.isMultiple()) {
                    if (value.startsWith("<jahia-resource")) {
                        value = ResourceBundleMarker.parseMarkerValue(value).getResourceKey();
                        if (value.startsWith(propertyDefinition.getResourceBundleKey())) {
                            value = value.substring(propertyDefinition.getResourceBundleKey().length() + 1);
                        }
                    }
                    value = baseType != null && mapping != null
                            ? mapping.getMappedPropertyValue(baseType, localName, value)
                            : value;
                    if (constraints.isEmpty() || constraints.contains(value)) {
                        try {
                            n.setProperty(propertyName, value);
                        } catch (Exception e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                } else {
                    String[] strings = Patterns.TRIPPLE_DOLLAR.split(value);
                    List<Value> values = new ArrayList<Value>();
                    for (int i = 0; i < strings.length; i++) {
                        String string = strings[i];

                        if (string.startsWith("<jahia-resource")) {
                            string = ResourceBundleMarker.parseMarkerValue(string).getResourceKey();
                            if (string.startsWith(propertyDefinition.getResourceBundleKey())) {
                                string = string
                                        .substring(propertyDefinition.getResourceBundleKey().length() + 1);
                            }
                        }
                        value = baseType != null ? mapping.getMappedPropertyValue(baseType, localName, value)
                                : value;
                        if (constraints.isEmpty() || constraints.contains(value)) {
                            values.add(new ValueImpl(string, propertyDefinition.getRequiredType()));
                        }
                    }
                    ;
                    n.setProperty(propertyName, values.toArray(new Value[values.size()]));
                }
                break;
            }
            }
        }
    } else {
        return false;
    }

    return true;
}

From source file:org.jahia.services.importexport.LegacyImportHandler.java

/**
 * Receive notification of the start of an element.
 * <p/>/*from  w  w w  .  java2 s  .com*/
 * <p>
 * By default, do nothing. Application writers may override this method in a subclass to take specific actions at the start of each
 * element (such as allocating a new tree node or writing output to a file).
 * </p>
 *
 * @param uri        The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace processing is not being
 *                   performed.
 * @param localName  The local name (without prefix), or the empty string if Namespace processing is not being performed.
 * @param qName      The qualified name (with prefix), or the empty string if qualified names are not available.
 * @param attributes The attributes attached to the element. If there are no attributes, it shall be an empty Attributes object.
 * @throws org.xml.sax.SAXException Any SAX exception, possibly wrapping another exception.
 * @see org.xml.sax.ContentHandler#startElement
 */
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    int ctx = -1;
    String uuid = null;
    try {
        currentNode = localName;
        uuid = attributes.getValue("jcr:uuid");

        if (!currentCtx.isEmpty()) {
            ctx = currentCtx.peek().ctx.peek();
        }

        if (logger.isDebugEnabled()) {
            logger.debug(StringUtils.repeat(" ", level) + "<" + currentNode + "> , ctx = " + ctx);
        }
        level++;
        final Map<String, String> creationMetadata = getMetadataForNodeCreation(attributes);
        if (ctx == -1) {
            if (HTTP_WWW_JAHIA_ORG.equals(uri) && PAGE.equals(localName)) {
                createPage(attributes.getValue(Name.NS_JCR_URI, "primaryType"),
                        attributes.getValue("jahia:title"), attributes.getValue("jahia:template"),
                        attributes.getValue(HTTP_WWW_JAHIA_ORG, "pageKey"), uuid, creationMetadata,
                        attributes.getValue("jahia:pid"), attributes.getValue("jcr:mixinTypes"),
                        getAdditionalProperties(attributes.getValue("jcr:additionalProperties")));
                setAcl(attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl"));
                setMetadata(attributes);
                setSeoURLs(attributes.getValue(HTTP_WWW_JAHIA_ORG, "urlMappings"));
                return;
            } else if (HTTP_WWW_JAHIA_ORG.equals(uri) && EMPTY.equals(localName)) {
                logger.warn("The site " + currentSiteNode.getDisplayableName()
                        + " was not published in language " + locale + ", nothing to import");
                return;
            }
            logger.error("Unexpected root markup: <" + uri + ":" + localName + " /> for site"
                    + currentSiteNode.getDisplayableName());
            return;
        }

        switch (ctx) {
        case CTX_PAGE:
            if (localName.endsWith("List") && getCurrentContentType() != null
                    && getCurrentContentType().getChildNodeDefinitionsAsMap()
                            .containsKey(StringUtils.substringBeforeLast(localName, "List"))) {
                // Must be a container list
                ExtendedNodeDefinition nodeDef = getCurrentContentType().getChildNodeDefinitionsAsMap()
                        .get(StringUtils.substringBeforeLast(localName, "List"));

                createContentList(nodeDef, uuid, creationMetadata, attributes);
                setMetadata(attributes);
                setAcl(attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl"));
                setSeoURLs(attributes.getValue(HTTP_WWW_JAHIA_ORG, "urlMappings"));
            } else {
                logger.error("Unexpected " + localName + " element (" + uuid
                        + ") in import file - skipping it and its subtree (more info in debug mode)");
                if (logger.isDebugEnabled() && localName.endsWith("List")) {
                    if (getCurrentContentType() == null) {
                        logger.debug("CurrentContentType is null!");
                    } else {
                        logger.debug(
                                "Only the following elements are allowed sccording to the source definitions: "
                                        + getCurrentContentType().getChildNodeDefinitionsAsMap().keySet()
                                                .toString());
                    }
                }
                currentCtx.peek().pushSkip();
            }
            break;
        case CTX_CTN:
            if (localName.endsWith("List") && getCurrentContentType() != null
                    && getCurrentContentType().getChildNodeDefinitionsAsMap()
                            .containsKey(StringUtils.substringBeforeLast(localName, "List"))) {
                // Must be a container list
                ExtendedNodeDefinition nodeDef = getCurrentContentType().getChildNodeDefinitionsAsMap()
                        .get(StringUtils.substringBeforeLast(localName, "List"));

                try {
                    createContentList(nodeDef, uuid, creationMetadata, attributes);
                    if (currentCtx.peek().ctx.peek() != CTX_DIRECTSUBNODES) {
                        setMetadata(attributes);
                        setAcl(attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl"));
                        setSeoURLs(attributes.getValue(HTTP_WWW_JAHIA_ORG, "urlMappings"));
                    }
                } catch (ConstraintViolationException cve) {
                    logger.error(
                            "Error when creating contentList with def={} (localname={} , uuid={} , currentContentType={})",
                            new Object[] { nodeDef.getName(), localName, uuid,
                                    getCurrentContentType().getName() });
                }
            } else {
                logger.debug("create field " + localName);
                ExtendedItemDefinition itemDef;
                if (getCurrentContentType().getChildNodeDefinitionsAsMap().containsKey(localName)
                        && getCurrentContentType().getPropertyDefinitionsAsMap().containsKey(localName)) {
                    itemDef = getCurrentContentType().getChildNodeDefinitionsAsMap().get(localName);
                    if (!itemDef.getDeclaringNodeType().getName()
                            .equals(getCurrentContentType().getNodeTypeDefinition().getName())) {
                        ExtendedItemDefinition itemDef2 = getCurrentContentType().getPropertyDefinitionsAsMap()
                                .get(localName);
                        if (itemDef2.getDeclaringNodeType().getName()
                                .equals(getCurrentContentType().getNodeTypeDefinition().getName())) {
                            itemDef = itemDef2;
                        }
                    }
                } else if (getCurrentContentType().getChildNodeDefinitionsAsMap().containsKey(localName)) {
                    itemDef = getCurrentContentType().getChildNodeDefinitionsAsMap().get(localName);
                } else {
                    itemDef = getCurrentContentType().getPropertyDefinitionsAsMap().get(localName);
                }
                if (itemDef == null) {
                    logger.error("Definition not found for field " + localName + " in node "
                            + getCurrentContentType().getName() + " , uuid=" + uuid);
                } else if (logger.isDebugEnabled()) {
                    if (itemDef.isNode()) {
                        logger.debug(
                                "The field {} is a subnode of the node type {} (child node definition = {})",
                                new Object[] { localName, getCurrentContentType().getName(),
                                        itemDef.getName() });
                    } else {
                        logger.debug("The field is a property: " + localName);
                    }
                }
                if (itemDef != null && (itemDef.isNode() || setPropertyField(getCurrentContentType(), localName,
                        attributes.getValue("jahia:value"), creationMetadata))) {
                    String mappedProperty = mapping.getMappedProperty(getCurrentContentType(), localName);
                    if ("#skip".equals(mappedProperty)) {
                        currentCtx.peek().pushSkip();
                    } else {
                        currentCtx.peek().pushField(mappedProperty);
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Not imported field " + localName + ", definition not found");
                        StringBuilder s = new StringBuilder();
                        for (String def : getCurrentContentType().getChildNodeDefinitionsAsMap().keySet())
                            s.append(def).append(", ");
                        logger.debug("Allowed sub definitions: " + (s.length() > 0 ? s : "none"));
                        for (String def : getCurrentContentType().getPropertyDefinitionsAsMap().keySet())
                            s.append(def).append(", ");
                        logger.debug("Allowed properties: " + (s.length() > 0 ? s : "none"));
                    }
                    currentCtx.peek().pushSkip();
                }
            }
            break;
        case CTX_LIST:
            /**
             * ExtendedNodeDefinition ctnDefinition =
             * listType.getDeclaredUnstructuredChildNodeDefinitions().values().iterator().next(); ExtendedNodeType ctnType =
             * ctnDefinition.getRequiredPrimaryTypes()[0];
             */
            String pt = attributes.getValue(Name.NS_JCR_URI, "primaryType");
            if (pt == null && StringUtils.startsWith(originatingJahiaRelease, "5")) {
                pt = qName;
            }

            createContent(pt, uuid, attributes.getValue("jahia:jahiaLinkActivation_picker_relationship"),
                    creationMetadata, attributes.getValue("jcr:mixinTypes"),
                    getAdditionalProperties(attributes.getValue("jcr:additionalProperties")));
            setMetadata(attributes);
            setAcl(attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl"));
            setSeoURLs(attributes.getValue(HTTP_WWW_JAHIA_ORG, "urlMappings"));
            break;
        case CTX_FIELD:
            setNodeField(uri, localName, uuid, attributes);
            break;

        case CTX_SHAREABLE:
            if ("#shareableSource".equals(mapping.getMappedNode(getCurrentContentType(), localName))) {
                createShareableNode(attributes.getValue("jahia:value"));
            } else {
                currentCtx.peek().pushSkip();
            }
            break;
        case CTX_SKIP:
            currentCtx.peek().pushSkip();
            break;
        case CTX_NAVLINK:
            currentCtx.peek().pushNavLink(getCurrentContentType(),
                    attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl"));
            currentCtx.peek().properties.peek().putAll(convertToProperties(attributes));
            final JCRNodeWrapper page = currentCtx.peek().contents.peek();

            String title = attributes.getValue("jahia:title");
            if (HTTP_WWW_JAHIA_ORG.equals(uri) && PAGE.equals(localName)) {
                String acl = null;
                if (logger.isDebugEnabled()) {
                    logger.debug("page acls: " + currentCtx.peek().acls.toString());
                }
                for (String a : currentCtx.peek().acls) {
                    if (a != null) {
                        acl = a;
                    }
                }
                if (attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl") != null) {
                    acl = attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl");
                }
                Map<String, String> props = currentCtx.peek().properties.peek();
                createPage(attributes.getValue(Name.NS_JCR_URI, "primaryType"), title,
                        attributes.getValue("jahia:template"),
                        attributes.getValue(HTTP_WWW_JAHIA_ORG, "pageKey"), uuid, creationMetadata,
                        attributes.getValue("jahia:pid"), attributes.getValue("jcr:mixinTypes"),
                        getAdditionalProperties(attributes.getValue("jcr:additionalProperties")));
                setMetadata(props, creationMetadata);
                setAcl(acl);
                setSeoURLs(attributes.getValue(HTTP_WWW_JAHIA_ORG, "urlMappings"));
                // todo : add a link here ??
            } else if (HTTP_WWW_JAHIA_ORG.equals(uri) && LINK.equals(localName)) {
                createInternalLink(page, title, uuid, attributes.getValue("jahia:reference"), "jnt:nodeLink",
                        creationMetadata, attributes.getValue("jcr:mixinTypes"),
                        getAdditionalProperties(attributes.getValue("jcr:additionalProperties")));
            } else if (HTTP_WWW_JAHIA_ORG.equals(uri) && localName.equals("url")) {
                createExternalLink(page, title, uuid, attributes.getValue("jahia:value"), externalLinkType,
                        externalLinkUrlPropertyName, externalLinkInternationalized, creationMetadata,
                        attributes.getValue("jcr:mixinTypes"),
                        getAdditionalProperties(attributes.getValue("jcr:additionalProperties")));
            }

            break;
        case CTX_DIRECTSUBNODES:
            String ctnPt = attributes.getValue(Name.NS_JCR_URI, "primaryType");
            if (ctnPt == null && StringUtils.startsWith(originatingJahiaRelease, "5")) {
                ctnPt = qName;
            }

            createContent(ctnPt, uuid, attributes.getValue("jahia:jahiaLinkActivation_picker_relationship"),
                    creationMetadata, attributes.getValue("jcr:mixinTypes"),
                    getAdditionalProperties(attributes.getValue("jcr:additionalProperties")));
            setMetadata(attributes);
            setAcl(attributes.getValue(HTTP_WWW_JAHIA_ORG, "acl"));
            setSeoURLs(attributes.getValue(HTTP_WWW_JAHIA_ORG, "urlMappings"));

            break;
        }
    } catch (RepositoryException e) {
        logger.error(MessageFormat.format(
                "Error while processing element: [uri={0}], [localName={1}], [qName={2}], [uuid={3}], [ctx={4}]",
                uri, localName, qName, uuid, ctx));
        throw new SAXException(e);
    }

}

From source file:org.jahia.services.importexport.LegacyImportHandler.java

private void createContentList(ExtendedNodeDefinition listDefinition, String uuid,
        Map<String, String> creationMetadata, Attributes attributes) throws RepositoryException {
    String nodeName = mapping.getMappedNode(getCurrentContentType(), listDefinition.getName());

    String nodeType = Constants.JAHIANT_CONTENTLIST;
    if (nodeName.indexOf("|") > 0) {
        nodeType = StringUtils.substringBefore(nodeName, "|");
        nodeName = StringUtils.substringAfter(nodeName, "|");
    }//from   w w  w  . ja v a2  s . c o m
    ExtendedNodeType primaryNodeType = listDefinition.getRequiredPrimaryTypes()[0];
    try {
        primaryNodeType = registry.getNodeType(
                StringUtils.substringBeforeLast(listDefinition.getRequiredPrimaryTypes()[0].getName(), "List"));
    } catch (NoSuchNodeTypeException ex) {
    }
    String mappedNodeType = mapping.getMappedType(primaryNodeType);
    if ("#skip".equals(nodeName) || "#skip".equals(mappedNodeType)) {
        currentCtx.peek().pushSkip();
    } else if ("#navlink".equals(nodeName) || "#navlink".equals(mappedNodeType)) {
        currentCtx.peek().pushNavLink(listDefinition.getRequiredPrimaryTypes()[0], null);
    } else if ("#directSubNodes".equals(nodeName) || "#directSubNodes".equals(mappedNodeType)) {
        currentCtx.peek().pushDirectContainer();
    } else {
        JCRNodeWrapper parent = getCurrentContentNode();
        if (StringUtils.contains(nodeName, "/")) {
            String parentPath = StringUtils.substringBeforeLast(nodeName, "/");
            if (parent.hasNode(parentPath)) {
                parent = parent.getNode(parentPath);
            } else {
                parent = parent.addNode(parentPath, Constants.JAHIANT_CONTENTLIST);
            }
            nodeName = StringUtils.substringAfterLast(nodeName, "/");
        }
        if (StringUtils.isEmpty(nodeType)
                && parent.getPrimaryNodeType().getChildNodeDefinitionsAsMap().get(nodeName) != null) {
            String[] strings = parent.getPrimaryNodeType().getChildNodeDefinitionsAsMap().get(nodeName)
                    .getRequiredPrimaryTypeNames();
            nodeType = strings[0];
        }
        List<String> mappedOldNodeNames = mapping.getMappedNodesForType(getCurrentContentType(), true);
        int indexOfName = mappedOldNodeNames.indexOf(listDefinition.getName());
        List<String> mappedNewNodeNames = null;
        if (indexOfName != -1) {
            mappedNewNodeNames = mapping.getMappedNodesForType(getCurrentContentType(), false)
                    .subList(indexOfName, mappedOldNodeNames.size());
        }
        JCRNodeWrapper node = addOrCheckoutNode(parent, nodeName, nodeType, mappedNewNodeNames,
                creationMetadata);

        performActions(mapping.getActions(getCurrentContentType(), listDefinition.getName()), node,
                creationMetadata);
        uuidMapping.put(uuid, node.getIdentifier());

        ExtendedNodeType listType = listDefinition.getRequiredPrimaryTypes()[0];
        currentCtx.peek().pushList(node, listType);

        if (currentCtx.peek().properties.peek() != null) {
            for (Map.Entry<String, String> entry : currentCtx.peek().properties.peek().entrySet()) {
                setPropertyField(getCurrentContentType(), entry.getKey(), entry.getValue(), creationMetadata);
            }
        }
    }

    handleContainerListSorting(attributes.getValue("jahia:sortHandler"), primaryNodeType);
}

From source file:org.jahia.services.importexport.LegacyImportHandler.java

private boolean setPropertyField(ExtendedNodeType baseType, String localName, JCRNodeWrapper node,
        String propertyName, String value, Map<String, String> creationMetadata) throws RepositoryException {
    JCRNodeWrapper parent = node;//from w  w  w.  ja  v  a  2s. co m
    String mixinType = null;
    if (propertyName.contains("|")) {
        mixinType = StringUtils.substringBefore(propertyName, "|");
        propertyName = StringUtils.substringAfter(propertyName, "|");
    }
    if (StringUtils.contains(propertyName, "/")) {
        String parentPath = StringUtils.substringBeforeLast(propertyName, "/");
        if (parent.hasNode(parentPath)) {
            parent = parent.getNode(parentPath);
        }
        propertyName = StringUtils.substringAfterLast(propertyName, "/");
    }
    parent = checkoutNode(parent);
    if (!StringUtils.isEmpty(mixinType) && !parent.isNodeType(mixinType)) {
        parent.addMixin(mixinType);
    }

    ExtendedPropertyDefinition propertyDefinition;
    propertyDefinition = parent.getApplicablePropertyDefinition(propertyName);
    if (propertyDefinition == null) {
        return false;
    }
    if (propertyDefinition.isProtected()) {
        return false;
    }

    if (StringUtils.isNotBlank(value) && !value.equals("<empty>")) {
        Node n = parent;
        if (propertyDefinition.isInternationalized()) {
            n = getOrCreateI18N(parent, locale, creationMetadata);
        }
        if (!n.isCheckedOut()) {
            session.checkout(n);
        }
        switch (propertyDefinition.getRequiredType()) {
        case PropertyType.DATE:
            GregorianCalendar cal = new GregorianCalendar();
            try {
                DateFormat df = new SimpleDateFormat(ImportExportService.DATE_FORMAT);
                Date d = df.parse(value);
                cal.setTime(d);
                n.setProperty(propertyName, cal);
            } catch (java.text.ParseException e) {
                logger.error(e.getMessage(), e);
            }
            break;

        case PropertyType.REFERENCE:
        case PropertyType.WEAKREFERENCE:
            if (propertyDefinition.isMultiple()) {
                String[] strings = Patterns.TRIPPLE_DOLLAR.split(value);
                for (String s : strings) {
                    createReferenceValue(s, propertyDefinition.getSelector(), n, propertyName);
                }
            } else {
                createReferenceValue(value, propertyDefinition.getSelector(), n, propertyName);
            }
            break;

        default:
            switch (propertyDefinition.getSelector()) {
            case SelectorType.RICHTEXT: {
                if (value.contains("=\"###")) {
                    int count = 1;
                    StringBuilder buf = new StringBuilder(value);
                    while (buf.indexOf("=\"###") > -1) {
                        int from = buf.indexOf("=\"###") + 2;
                        int to = buf.indexOf("\"", from);

                        String ref = buf.substring(from, to);
                        if (ref.startsWith("###/webdav")) {
                            ref = StringUtils.substringAfter(ref, "###/webdav");
                            buf.replace(from, to, "##doc-context##/{workspace}/##ref:link" + count + "##");
                        } else if (ref.startsWith("###file:")) {
                            ref = StringUtils.substringAfter(ref, "###file:");
                            final int qmPos = ref.indexOf('?');
                            boolean isUuid = false;
                            if (qmPos != -1) {
                                if (StringUtils.substring(ref, qmPos + 1).startsWith("uuid=default:")) {
                                    ref = StringUtils.substring(ref, qmPos + 14);
                                    isUuid = true;
                                } else
                                    ref = StringUtils.substringBefore(ref, "?");
                            }
                            if (!isUuid)
                                ref = correctFilename(ref);
                            buf.replace(from, to, "##doc-context##/{workspace}/##ref:link" + count + "##");
                        } else {
                            ref = StringUtils.substringAfterLast(ref, "/");
                            // we keep the URL parameters if any
                            String params = "";
                            int pos = ref.indexOf('?');
                            if (pos == -1) {
                                pos = ref.indexOf('#');
                            }
                            if (pos != -1) {
                                params = ref.substring(pos);
                                ref = ref.substring(0, pos);
                            }
                            buf.replace(from, to,
                                    "##cms-context##/{mode}/{lang}/##ref:link" + count + "##.html" + params);
                        }
                        try {
                            ref = URLDecoder.decode(ref, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                        }

                        if (!references.containsKey(ref)) {
                            references.put(ref, new ArrayList<String>());
                        }
                        references.get(ref)
                                .add(n.getIdentifier() + "/[" + count + "]" + propertyDefinition.getName());
                        count++;
                    }
                    value = buf.toString();
                }
                n.setProperty(propertyName, value);
                if (logger.isDebugEnabled())
                    logger.debug("Setting on node " + n.getPath() + " property " + propertyName + " with value="
                            + value);
                break;
            }
            default: {
                String[] vcs = propertyDefinition.getValueConstraints();
                List<String> constraints = Arrays.asList(vcs);
                if (!propertyDefinition.isMultiple()) {
                    if (value.startsWith("<jahia-resource")) {
                        value = ResourceBundleMarker.parseMarkerValue(value).getResourceKey();
                        if (value.startsWith(propertyDefinition.getResourceBundleKey())) {
                            value = value.substring(propertyDefinition.getResourceBundleKey().length() + 1);
                        }
                    } else if ("jcr:description".equals(propertyName)) {
                        value = removeHtmlTags(value);
                    }

                    value = baseType != null ? mapping.getMappedPropertyValue(baseType, localName, value)
                            : value;
                    if (valueMatchesContraints(value, constraints)) {
                        try {
                            n.setProperty(propertyName, value);
                            if (logger.isDebugEnabled())
                                logger.debug("Setting on node " + n.getPath() + " property " + propertyName
                                        + " with value=" + value);
                        } catch (Exception e) {
                            logger.error("Impossible to set property " + propertyName + " due to exception", e);
                        }
                    } else {
                        logger.error(
                                "Impossible to set property " + propertyName + " due to some constraint error");
                        logger.error(" - value       = " + value);
                        logger.error(" - constraints = " + constraints.toString());
                    }
                } else {
                    String[] strings = Patterns.TRIPPLE_DOLLAR.split(value);
                    List<Value> values = new ArrayList<Value>();
                    for (String string : strings) {

                        if (string.startsWith("<jahia-resource")) {
                            string = ResourceBundleMarker.parseMarkerValue(string).getResourceKey();
                            if (string.startsWith(propertyDefinition.getResourceBundleKey())) {
                                string = string
                                        .substring(propertyDefinition.getResourceBundleKey().length() + 1);
                            }
                        }
                        value = baseType != null ? mapping.getMappedPropertyValue(baseType, localName, value)
                                : value;
                        if (constraints.isEmpty() || constraints.contains(value)) {
                            values.add(new ValueImpl(string, propertyDefinition.getRequiredType()));
                        }
                    }
                    n.setProperty(propertyName, values.toArray(new Value[values.size()]));
                    if (logger.isDebugEnabled())
                        logger.debug("Setting on node " + n.getPath() + " property " + propertyName
                                + " with value=" + values);
                }
                break;
            }
            }
        }
    } else {
        return false;
    }

    return true;
}

From source file:org.jahia.services.importexport.ReferencesHelper.java

public static void updateReferencesInLive(final Map<String, Object> resolvedReferences)
        throws RepositoryException {
    if (!resolvedReferences.isEmpty()) {
        JCRTemplate.getInstance().doExecuteWithSystemSessionAsUser(null, "live", null,
                new JCRCallback<Object>() {

                    public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                        for (Map.Entry<String, Object> entry : resolvedReferences.entrySet()) {
                            String nodeIdentifier = StringUtils.substringBeforeLast(entry.getKey(), "/");
                            String propertyName = StringUtils.substringAfterLast(entry.getKey(), "/");

                            try {
                                JCRNodeWrapper node = session.getNodeByIdentifier(nodeIdentifier);
                                ExtendedPropertyDefinition definition = node
                                        .getApplicablePropertyDefinition(propertyName);
                                if (definition != null) {
                                    if (entry.getValue() instanceof String) {
                                        if (!node.hasProperty(propertyName) || !node.getProperty(propertyName)
                                                .getString().equals(entry.getValue())) {
                                            node.setProperty(propertyName,
                                                    session.getValueFactory().createValue(
                                                            (String) entry.getValue(),
                                                            definition.getRequiredType()));
                                        }
                                    } else if (entry.getValue() instanceof Set) {
                                        Set<String> values = (Set<String>) entry.getValue();
                                        if (!node.hasProperty(propertyName)) {
                                            JCRPropertyWrapper property = node.setProperty(propertyName,
                                                    new Value[0]);
                                            for (String value : values) {
                                                property.addValue(session.getValueFactory().createValue(value,
                                                        definition.getRequiredType()));
                                            }
                                        } else {
                                            JCRPropertyWrapper property = node.getProperty(propertyName);
                                            Value[] previous = property.getValues();
                                            for (Value value : previous) {
                                                values.remove(value.getString());
                                            }
                                            for (String value : values) {
                                                property.addValue(session.getValueFactory().createValue(value,
                                                        definition.getRequiredType()));
                                            }
                                        }
                                    }/*from  w ww .  j av a 2s. c o  m*/
                                }
                            } catch (ItemNotFoundException e) {
                                logger.debug("Node not found in live", e);
                            }
                        }
                        session.save();
                        return null;
                    }
                });
        resolvedReferences.clear();
    }
}