Java Examples for javax.jcr.Node

The following java examples will help you to understand the usage of javax.jcr.Node. These source code samples are taken from different open source projects.

Example 1
Project: nextreports-server-master  File: JcrStorageDao.java View source code
public Entity[] getEntityChildren(String path) throws NotFoundException {
    checkPath(path);
    Node node = getNode(path);
    try {
        if (!node.hasNodes()) {
            return new Entity[0];
        }
        List<Entity> entities = new ArrayList<Entity>();
        NodeIterator nodes = node.getNodes();
        while (nodes.hasNext()) {
            Entity entity = getEntity(nodes.nextNode());
            if (entity != null) {
                entities.add(entity);
            }
        }
        return entities.toArray(new Entity[entities.size()]);
    } catch (RepositoryException e) {
        throw convertJcrAccessException(e);
    }
}
Example 2
Project: Cream-master  File: JcrMapper.java View source code
public static <T> T create(String parentNodePath, T entity) {
    try {
        MD md = getMetadata(entity.getClass());
        String entityName = jcrom.getName(entity);
        if (entityName == null || entityName.equals("")) {
            throw new JcrMappingException("The name of the entity being created is empty!");
        }
        if (parentNodePath == null || parentNodePath.equals("")) {
            throw new JcrMappingException("The parent path of the entity being created is empty!");
        }
        Node parentNode;
        Session session = getSession();
        Node rootNode = session.getRootNode();
        if (parentNodePath.equals("/")) {
            // special case, add directly to the root node
            parentNode = rootNode;
        } else {
            String relativePath = relativePath(parentNodePath);
            if (rootNode.hasNode(relativePath)) {
                parentNode = rootNode.getNode(relativePath);
            } else {
                // if not found create it
                parentNode = rootNode.addNode(relativePath);
            }
        }
        Node newNode = jcrom.addNode(parentNode, entity, md.mixinTypes);
        session.save();
        if (md.isVersionable) {
            checkinRecursively(session.getWorkspace().getVersionManager(), newNode);
        }
        return entity;
    } catch (RepositoryException e) {
        throw new JcrMappingException("Could not create node", e);
    }
}
Example 3
Project: magnolia-thymeleaf-renderer-master  File: AbstractMockMagnoliaTest.java View source code
@Before
public void setUp() throws Exception {
    /** mock up magnolia */
    node = mock(Node.class);
    Session session = mock(Session.class);
    Workspace workspace = mock(Workspace.class);
    when(workspace.getName()).thenReturn("pages");
    when(session.getWorkspace()).thenReturn(workspace);
    when(session.hasPermission(any(), any())).thenReturn(true);
    when(node.getSession()).thenReturn(session);
    when(node.getPath()).thenReturn("/home");
    NodeIterator nodeIterator = mock(NodeIterator.class);
    when(nodeIterator.hasNext()).thenReturn(false);
    when(node.getNodes()).thenReturn(nodeIterator);
    HttpServletRequest request = new MockHttpServletRequest();
    request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
    HttpServletResponse response = new MockHttpServletResponse();
    WebContext webCtx = mock(WebContext.class);
    when(webCtx.getRequest()).thenReturn(request);
    when(webCtx.getResponse()).thenReturn(response);
    AggregationState state = mock(AggregationState.class);
    when(state.getMainContentNode()).thenReturn(node);
    // when(state.equals(state)).thenReturn(true);
    when(webCtx.getAggregationState()).thenReturn(state);
    AccessManager accessManager = mock(AccessManager.class);
    when(accessManager.isGranted(anyString(), anyLong())).thenReturn(true);
    when(webCtx.getAccessManager(anyString())).thenReturn(accessManager);
    when(webCtx.getLocale()).thenReturn(Locale.ENGLISH);
    MgnlContext.setInstance(webCtx);
    config = mock(ServerConfiguration.class);
    when(config.isAdmin()).thenReturn(true);
    componentProvider = mock(ComponentProvider.class);
    Components.setComponentProvider(componentProvider);
    when(componentProvider.getComponent(ServerConfiguration.class)).thenReturn(config);
    engine = mock(RenderingEngine.class);
    when(componentProvider.getComponent(RenderingEngine.class)).thenReturn(engine);
    Provider<AggregationState> provider = mock(Provider.class);
    TemplatingFunctions templatingFunctions = new TemplatingFunctions(provider);
    when(componentProvider.getComponent(TemplatingFunctions.class)).thenReturn(templatingFunctions);
    I18nContentSupport i18nContentSupport = mock(I18nContentSupport.class);
    when(i18nContentSupport.getDefaultLocale()).thenReturn(Locale.ENGLISH);
    when(componentProvider.getComponent(I18nContentSupport.class)).thenReturn(i18nContentSupport);
    RenderableVariationResolver variationResolver = mock(RenderableVariationResolver.class);
    when(componentProvider.getComponent(RenderableVariationResolver.class)).thenReturn(variationResolver);
    I18nizer i18nizer = mock(I18nizer.class);
    when(componentProvider.getComponent(I18nizer.class)).thenReturn(i18nizer);
    Components.pushProvider(componentProvider);
    DefaultMessagesManager mgr = new DefaultMessagesManager();
    when(componentProvider.getComponent(MessagesManager.class)).thenReturn(mgr);
    when(componentProvider.getComponent(BeanMerger.class)).thenReturn(new ProxyBasedBeanMerger());
    RenderContext.push();
    RenderContext.get().setModel(new HashMap<>());
    ServletContext servletContext = mock(ServletContext.class);
    thymeEngine = new SpringTemplateEngine();
    thymeEngine.addTemplateResolver(new ClassLoaderTemplateResolver());
    thymeEngine.addDialect(new MagnoliaDialect());
    renderer = new ThymeleafRenderer();
    renderer.setApplicationContext(webApplicationContext);
    renderer.setServletContext(servletContext);
    renderer.setEngine(thymeEngine);
    renderableDefinition = mock(RenderableDefinition.class);
    renderingContext = mock(RenderingContext.class);
    when(engine.getRenderingContext()).thenReturn(renderingContext);
    AreaElement areaElement = new AreaElement(config, renderingContext, engine, variationResolver);
    areaElement.setContent(node);
    when(componentProvider.newInstance(eq(AreaElement.class), any())).thenReturn(areaElement);
    stringWriter = new StringWriter();
    AppendableWriter out = new AppendableWriter(stringWriter);
    when(renderingContext.getAppendable()).thenReturn(out);
    BlossomTemplateDefinition templateDefinition = mock(BlossomTemplateDefinition.class);
    when(templateDefinition.getDialog()).thenReturn(null);
    AreaDefinition areaDef = mock(AreaDefinition.class);
    when(areaDef.getName()).thenReturn("Area");
    when(areaDef.getEnabled()).thenReturn(true);
    Map<String, AreaDefinition> areaMap = new HashMap<>();
    areaMap.put("Area", areaDef);
    when(templateDefinition.getAreas()).thenReturn(areaMap);
    when(renderingContext.getRenderableDefinition()).thenReturn(templateDefinition);
    when(i18nizer.decorate(templateDefinition)).thenReturn(templateDefinition);
}
Example 4
Project: ecms-develop-master  File: UIDialogForm.java View source code
public void releaseLock() throws Exception {
    if (isKeepinglock()) {
        Node currentNode = getNode();
        if ((currentNode != null) && currentNode.isLocked()) {
            try {
                if (currentNode.holdsLock()) {
                    String lockToken = LockUtil.getLockTokenOfUser(currentNode);
                    if (lockToken != null) {
                        currentNode.getSession().addLockToken(LockUtil.getLockToken(currentNode));
                    }
                    currentNode.unlock();
                    currentNode.removeMixin(Utils.MIX_LOCKABLE);
                    currentNode.save();
                    //remove lock from Cache
                    LockUtil.removeLock(currentNode);
                }
            } catch (LockException le) {
                if (LOG.isErrorEnabled()) {
                    LOG.error("Fails when unlock node that is editing", le);
                }
            }
        }
    }
    setIsKeepinglock(false);
}
Example 5
Project: accesscontroltool-master  File: DumpServiceImpl.java View source code
private void createTransientDumpNode(String dump, Node rootNode) throws ItemExistsException, PathNotFoundException, NoSuchNodeTypeException, LockException, VersionException, ConstraintViolationException, RepositoryException, ValueFormatException {
    NodeIterator nodeIt = rootNode.getNodes();
    // TreeSet used here since only this type offers the methods first() and
    // last()
    TreeSet<Node> dumpNodes = new TreeSet<Node>(new JcrCreatedComparator());
    Node previousDumpNode = null;
    // get all dump nodes
    while (nodeIt.hasNext()) {
        Node currNode = nodeIt.nextNode();
        if (currNode.getName().startsWith(DUMP_NODE_PREFIX)) {
            dumpNodes.add(currNode);
        }
    }
    // try to get previous dump node
    if (!dumpNodes.isEmpty()) {
        previousDumpNode = dumpNodes.first();
    }
    // is limit of dump nodes to save reached?
    if (dumpNodes.size() > (nrOfSavedDumps - 1)) {
        Node oldestDumpNode = dumpNodes.last();
        oldestDumpNode.remove();
    }
    Node dumpNode = getNewDumpNode(dump, rootNode);
    // order the newest dump node as first child node of ac root node
    if (previousDumpNode != null) {
        rootNode.orderBefore(dumpNode.getName(), previousDumpNode.getName());
    }
}
Example 6
Project: example-projects-master  File: ExoJcrEx01.java View source code
public static void main(String[] args) throws Exception {
    RepositoryImpl repository = setup();
    // Add some nodes and properties
    {
        CredentialsImpl credentials = new CredentialsImpl("root", "exo".toCharArray());
        SessionImpl session = (SessionImpl) repository.login(credentials, "production");
        Node rootNode = session.getRootNode();
        // clean up before test
        if (rootNode.hasNode("training")) {
            rootNode.getNode("training").remove();
        }
        Node training = rootNode.addNode("training", "nt:unstructured");
        Node day1 = training.addNode("Day-1");
        day1.setProperty("name", "JCR concepts, architecture and benefits");
        Node day2 = training.addNode("Day-2");
        day2.setProperty("name", "JCR for developers");
        session.save();
        session.logout();
    }
    // Read nodes and properties
    {
        CredentialsImpl credentials = new CredentialsImpl("root", "exo".toCharArray());
        SessionImpl session = (SessionImpl) repository.login(credentials, "production");
        Node rootNode = session.getRootNode();
        Node training = rootNode.getNode("training");
        NodeIterator nodeIterator = training.getNodes();
        while (nodeIterator.hasNext()) {
            Node node = (Node) nodeIterator.next();
            System.out.println(node.getName() + ":" + node.getProperty("name").getString());
        }
        session.logout();
    }
}
Example 7
Project: Hippo-CMS-Konakart-master  File: AbstractProductFactory.java View source code
@Override
public void add(String storeId, Product product, LanguageIf language, String baseImagePath) throws Exception {
    if (!shouldAddProduct(product, language)) {
        log.info("The product " + product.getName() + " will not be added to Hippo");
        return;
    }
    KKCndConstants.PRODUCT_TYPE product_type = KKCndConstants.PRODUCT_TYPE.findByType(product.getType());
    String productDocType = HippoModuleConfig.getConfig().getClientEngineConfig().getProductNodeTypeMapping().get(product_type.getNamespace());
    if (StringUtils.isEmpty(productDocType)) {
        log.error("No product namespace has been associated for the product namespace : " + product_type.getNamespace() + ". Please set the it within the pluginconfig located " + "at " + HippoModuleConfig.KONAKART_PRODUCT_TYPE_NAMESPACES_PATH);
        return;
    }
    String absPath = contentRoot + "/" + Codecs.encodeNode(productFolder) + "/" + createProductNodeRoot(product);
    // Create or retrieve the root folder
    Node rootFolder;
    // Does not exist - create it.
    if (!session.getRootNode().hasNode(StringUtils.removeStart(absPath, "/"))) {
        rootFolder = nodeHelper.createMissingFolders(absPath);
    } else {
        rootFolder = session.getNode(absPath);
    }
    // Create or retrieve the product node
    Node productNode = nodeHelper.createOrRetrieveDocument(rootFolder, product, productDocType, session.getUserID(), getLanguageToSetToHippoDoc(language));
    boolean addNewProduct = !productNode.hasNode(KKCndConstants.PRODUCT_ID);
    boolean hasCheckout = false;
    // Check if the node is check-in
    if (!productNode.isCheckedOut()) {
        nodeHelper.checkout(productNode.getPath());
        hasCheckout = true;
    }
    // Set the state of the product
    String state = (product.getStatus() == 0) ? NodeHelper.UNPUBLISHED_STATE : NodeHelper.PUBLISHED_STATE;
    nodeHelper.updateState(productNode, state);
    // Update the node
    updateProperties(storeId, product, productNode, language);
    // Create the konakart ref product
    createOrUpdateKonakartProduct(product, productNode);
    // Upload images
    uploadImages(language, productNode, baseImagePath, product);
    // Save the session
    productNode.getSession().save();
    // Save the node
    if (hasCheckout) {
        nodeHelper.checkin(productNode.getPath());
    }
    if (addNewProduct) {
        if (log.isDebugEnabled()) {
            log.debug("The konakart product with id : {} has been added", product.getId());
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("The konakart product with id : {} has been updated", product.getId());
        }
    }
}
Example 8
Project: HippoWeblog-master  File: ContentRewriterImpl.java View source code
/**
     * Internal method that rewrites all links, optionally makes links in external form or adds a rel="external" to external links
     * @param html String of the HTML
     * @param node {@link Node} that contains the HTML
     * @param requestContext {@link HstRequestContext}
     * @param externalizeLinks boolean that defines if all links should be rewritten to external form, e.g. http://example.com/link.html
     * @return rewritten String of the HTML
     */
private String rewriteContent(String html, Node node, HstRequestContext requestContext, boolean externalizeLinks) {
    // only create if really needed
    StringBuilder sb = null;
    // strip off html & body tag
    String innerHTML = SimpleHtmlExtractor.getInnerHtml(html, "body", false);
    if (innerHTML == null) {
        innerHTML = html;
    }
    innerHTML = innerHTML.trim().replaceAll("facetselect=\".+?\"", "");
    int globalOffset = 0;
    while (innerHTML.indexOf(LINK_TAG, globalOffset) > -1) {
        int offset = innerHTML.indexOf(LINK_TAG, globalOffset);
        int hrefIndexStart = innerHTML.indexOf(HREF_ATTR_NAME, offset);
        if (hrefIndexStart == -1) {
            break;
        }
        if (sb == null) {
            sb = new StringBuilder(html.length());
        }
        hrefIndexStart += HREF_ATTR_NAME.length();
        offset = hrefIndexStart;
        int endTag = innerHTML.indexOf(END_TAG, offset);
        boolean appended = false;
        if (hrefIndexStart < endTag) {
            int hrefIndexEnd = innerHTML.indexOf(ATTR_END, hrefIndexStart);
            if (hrefIndexEnd > hrefIndexStart) {
                String documentPath = innerHTML.substring(hrefIndexStart, hrefIndexEnd);
                offset = endTag;
                sb.append(innerHTML.substring(globalOffset, hrefIndexStart));
                if (isExternal(documentPath)) {
                    sb.append(documentPath);
                } else {
                    HstLink href = getDocumentLink(documentPath, node, requestContext, (Mount) null);
                    if (href != null && href.getPath() != null) {
                        sb.append(href.toUrlForm(requestContext, externalizeLinks));
                    } else {
                        log.warn("Skip href because url is null");
                    }
                }
                sb.append(innerHTML.substring(hrefIndexEnd, endTag));
                if (!externalizeLinks && isExternal(documentPath)) {
                    sb.append(REL_EXTERNAL);
                }
                appended = true;
            }
        }
        if (!appended && offset > globalOffset) {
            sb.append(innerHTML.substring(globalOffset, offset));
        }
        globalOffset = offset;
    }
    if (sb != null) {
        sb.append(innerHTML.substring(globalOffset, innerHTML.length()));
        innerHTML = String.valueOf(sb);
        sb = null;
    }
    globalOffset = 0;
    while (innerHTML.indexOf(IMG_TAG, globalOffset) > -1) {
        int offset = innerHTML.indexOf(IMG_TAG, globalOffset);
        int srcIndexStart = innerHTML.indexOf(SRC_ATTR_NAME, offset);
        if (srcIndexStart == -1) {
            break;
        }
        if (sb == null) {
            sb = new StringBuilder(innerHTML.length());
        }
        srcIndexStart += SRC_ATTR_NAME.length();
        offset = srcIndexStart;
        int endTag = innerHTML.indexOf(END_TAG, offset);
        boolean appended = false;
        if (srcIndexStart < endTag) {
            int srcIndexEnd = innerHTML.indexOf(ATTR_END, srcIndexStart);
            if (srcIndexEnd > srcIndexStart) {
                String srcPath = innerHTML.substring(srcIndexStart, srcIndexEnd);
                offset = endTag;
                sb.append(innerHTML.substring(globalOffset, srcIndexStart));
                if (isExternal(srcPath)) {
                    sb.append(srcPath);
                } else {
                    HstLink binaryLink = getBinaryLink(srcPath, node, requestContext, (Mount) null);
                    if (binaryLink != null && binaryLink.getPath() != null) {
                        sb.append(binaryLink.toUrlForm(requestContext, externalizeLinks));
                    } else {
                        log.warn("Could not translate image src. Skip src");
                    }
                }
                sb.append(innerHTML.substring(srcIndexEnd, endTag));
                appended = true;
            }
        }
        if (!appended && offset > globalOffset) {
            sb.append(innerHTML.substring(globalOffset, offset));
        }
        globalOffset = offset;
    }
    if (sb == null) {
        return innerHTML;
    } else {
        sb.append(innerHTML.substring(globalOffset, innerHTML.length()));
        return sb.toString();
    }
}
Example 9
Project: jackalope-master  File: PageManagerImpl.java View source code
@Override
public Page create(String parentPath, String pageName, String template, String title, boolean autoSave) throws WCMException {
    if (parentPath == null)
        throw new IllegalArgumentException("Parent path can't be null.");
    if (pageName == null && title == null)
        throw new IllegalArgumentException("Page and title name can't be both null.");
    if (template != null && !template.isEmpty())
        throw new UnsupportedOperationException("Templates are not supported.");
    try {
        Node parent = JcrUtils.getOrCreateByPath(parentPath, JcrConstants.NT_UNSTRUCTURED, session);
        if (pageName == null || pageName.isEmpty())
            pageName = JcrUtil.createValidName(title, JcrUtil.HYPHEN_LABEL_CHAR_MAPPING);
        if (!JcrUtil.isValidName(pageName))
            throw new IllegalArgumentException("Illegal page name: " + pageName);
        Node pageNode = parent.addNode(pageName, JcrConstants.CQ_PAGE);
        Node contentNode = pageNode.addNode("jcr:content", JcrConstants.CQ_PAGE_CONTENT);
        if (title != null && !title.isEmpty())
            contentNode.setProperty("jcr:title", title);
        if (autoSave) {
            session.save();
        }
        return getPage(pageNode.getPath());
    } catch (RepositoryException e) {
        throw new WCMException("Unable to create page", e);
    }
}
Example 10
Project: spring-modules-master  File: JcrTemplateTests.java View source code
/*
     * Test method for 'org.springmodules.jcr.JcrTemplate.getNodeByUUID(String)'
     */
public void testGetNodeByUUID() throws RepositoryException {
    MockControl resultMock = MockControl.createControl(Node.class);
    Node result = (Node) resultMock.getMock();
    String uuid = "uuid";
    sessionControl.expectAndReturn(session.getNodeByUUID(uuid), result);
    sessionControl.replay();
    sfControl.replay();
    assertSame(jt.getNodeByUUID(uuid), result);
}
Example 11
Project: jackrabbit-master  File: UserImporterTest.java View source code
public void testImportWithIntermediatePath() throws IOException, RepositoryException, SAXException, NotExecutableException {
    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<sv:node sv:name=\"some\" xmlns:mix=\"http://www.jcp.org/jcr/mix/1.0\" xmlns:nt=\"http://www.jcp.org/jcr/nt/1.0\" xmlns:fn_old=\"http://www.w3.org/2004/10/xpath-functions\" xmlns:fn=\"http://www.w3.org/2005/xpath-functions\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:sv=\"http://www.jcp.org/jcr/sv/1.0\" xmlns:rep=\"internal\" xmlns:jcr=\"http://www.jcp.org/jcr/1.0\">" + "   <sv:property sv:name=\"jcr:primaryType\" sv:type=\"Name\"><sv:value>rep:AuthorizableFolder</sv:value></sv:property>" + "   <sv:property sv:name=\"jcr:uuid\" sv:type=\"String\"><sv:value>d5433be9-68d0-4fba-bf96-efc29f461993</sv:value></sv:property>" + "<sv:node sv:name=\"intermediate\">" + "   <sv:property sv:name=\"jcr:primaryType\" sv:type=\"Name\"><sv:value>rep:AuthorizableFolder</sv:value></sv:property>" + "   <sv:property sv:name=\"jcr:uuid\" sv:type=\"String\"><sv:value>d87354a4-037e-4756-a8fb-deb2eb7c5149</sv:value></sv:property>" + "<sv:node sv:name=\"path\">" + "   <sv:property sv:name=\"jcr:primaryType\" sv:type=\"Name\"><sv:value>rep:AuthorizableFolder</sv:value></sv:property>" + "   <sv:property sv:name=\"jcr:uuid\" sv:type=\"String\"><sv:value>24263272-b789-4568-957a-3bcaf99dbab3</sv:value></sv:property>" + "<sv:node sv:name=\"t3\">" + "   <sv:property sv:name=\"jcr:primaryType\" sv:type=\"Name\"><sv:value>rep:User</sv:value></sv:property>" + "   <sv:property sv:name=\"jcr:uuid\" sv:type=\"String\"><sv:value>0b8854ad-38f0-36c6-9807-928d28195609</sv:value></sv:property>" + "   <sv:property sv:name=\"rep:password\" sv:type=\"String\"><sv:value>{sha1}4358694eeb098c6708ae914a10562ce722bbbc34</sv:value></sv:property>" + "   <sv:property sv:name=\"rep:principalName\" sv:type=\"String\"><sv:value>t3</sv:value></sv:property>" + "</sv:node>" + "</sv:node>" + "</sv:node>" + "</sv:node>";
    NodeImpl target = (NodeImpl) sImpl.getNode(umgr.getUsersPath());
    try {
        doImport(target, xml);
        assertTrue(target.isModified());
        assertTrue(sImpl.hasPendingChanges());
        Authorizable newUser = umgr.getAuthorizable("t3");
        assertNotNull(newUser);
        assertFalse(newUser.isGroup());
        assertEquals("t3", newUser.getPrincipal().getName());
        assertEquals("t3", newUser.getID());
        NodeImpl n = ((UserImpl) newUser).getNode();
        assertTrue(n.isNew());
        Node parent = n.getParent();
        assertFalse(n.isSame(target));
        assertTrue(((NodeImpl) parent).isNodeType(UserConstants.NT_REP_AUTHORIZABLE_FOLDER));
        assertFalse(parent.getDefinition().isProtected());
        assertTrue(target.hasNode("some"));
        assertTrue(target.hasNode("some/intermediate/path"));
    } finally {
        sImpl.refresh(false);
    }
}
Example 12
Project: jcr-master  File: TestImport.java View source code
/**
    * Test for http://jira.exoplatform.org/browse/JCR-872
    * 
    * @throws Exception
    */
public void testAclImportDocumentView() throws Exception {
    AccessManager accessManager = ((SessionImpl) root.getSession()).getAccessManager();
    NodeImpl testRoot = (NodeImpl) root.addNode("TestRoot", "exo:article");
    testRoot.addMixin("exo:owneable");
    testRoot.addMixin("exo:privilegeable");
    testRoot.setProperty("exo:title", "test");
    session.save();
    assertTrue(accessManager.hasPermission(testRoot.getACL(), PermissionType.SET_PROPERTY, new Identity("exo")));
    testRoot.setPermission(testRoot.getSession().getUserID(), PermissionType.ALL);
    testRoot.setPermission("exo", new String[] { PermissionType.SET_PROPERTY });
    testRoot.removePermission(IdentityConstants.ANY);
    session.save();
    assertTrue(accessManager.hasPermission(testRoot.getACL(), PermissionType.SET_PROPERTY, new Identity("exo")));
    assertFalse(accessManager.hasPermission(testRoot.getACL(), PermissionType.READ, new Identity("exo")));
    File tmp = File.createTempFile("testAclImpormt", "tmp");
    tmp.deleteOnExit();
    serialize(testRoot, false, true, tmp);
    testRoot.remove();
    session.save();
    NodeImpl importRoot = (NodeImpl) root.addNode("ImportRoot");
    deserialize(importRoot, XmlSaveType.SESSION, true, ImportUUIDBehavior.IMPORT_UUID_COLLISION_REMOVE_EXISTING, new BufferedInputStream(new FileInputStream(tmp)));
    session.save();
    Node n1 = importRoot.getNode("TestRoot");
    assertTrue("Wrong ACL", accessManager.hasPermission(((NodeImpl) n1).getACL(), PermissionType.SET_PROPERTY, new Identity("exo")));
    assertFalse("Wrong ACL", accessManager.hasPermission(((NodeImpl) n1).getACL(), PermissionType.READ, new Identity("exo")));
    importRoot.remove();
    session.save();
}
Example 13
Project: sling-master  File: ResourceResolverWithVanityBloomFilterTest.java View source code
@Before
public synchronized void setup() throws Exception {
    closeResolver();
    resResolver = resourceResolverFactory.getAdministrativeResourceResolver(null);
    setMaxCachedVanityPathEntries(0);
    cleanupResolverFactory = resourceResolverFactory;
    session = resResolver.adaptTo(Session.class);
    mappingsFacade = new MappingsFacade(eventsCounter);
    // Do the mappings setup only once, and clean it up 
    // after all tests
    rootNode = maybeCreateNode(session.getRootNode(), "content", "nt:unstructured");
    rootPath = rootNode.getPath();
    session.save();
    if (toDelete.isEmpty()) {
        final Node mapRoot = maybeCreateNode(session.getRootNode(), "etc", "nt:folder");
        final Node map = maybeCreateNode(mapRoot, "map", "sling:Mapping");
        final Node http = maybeCreateNode(map, "http", "sling:Mapping");
        maybeCreateNode(http, "localhost.80", "sling:Mapping");
        final Node https = maybeCreateNode(map, "https", "sling:Mapping");
        maybeCreateNode(https, "localhost.443", "sling:Mapping");
        toDelete.add(map.getPath());
        toDelete.add(rootNode.getPath());
    }
    mapRoot = session.getNode("/etc");
    session.save();
    // define a vanity path for the rootPath
    vanity = new String[] { "testVanity", "testV", "testVanityToUpdate" };
    rootNode.setProperty("sling:vanityPath", vanity);
    rootNode.addMixin("sling:VanityPath");
    saveMappings(session);
}
Example 14
Project: Priha-master  File: VersionTest.java View source code
/**
     * Tests if
     * <ul> <li><code>Version.setProperty(String, String[])</code></li>
     * <li><code>Version.setProperty(String, String[], int)</code></li>
     * <li><code>Version.setProperty(String, Value[])</code></li>
     * <li><code>Version.setProperty(String, Value[], int)</code></li>
     * <li><code>Version.setProperty(String, boolean)</code></li>
     * <li><code>Version.setProperty(String, double)</code></li>
     * <li><code>Version.setProperty(String, InputStream)</code></li>
     * <li><code>Version.setProperty(String, String)</code></li>
     * <li><code>Version.setProperty(String, Calendar)</code></li>
     * <li><code>Version.setProperty(String, Node)</code></li>
     * <li><code>Version.setProperty(String, Value)</code></li>
     * <li><code>Version.setProperty(String, long)</code></li>
     * </ul> all throw a
     * {@link javax.jcr.nodetype.ConstraintViolationException}
     */
public void testSetProperty() throws Exception {
    // create Value[] object
    Value[] vArray = new Value[3];
    vArray[0] = superuser.getValueFactory().createValue("abc");
    vArray[1] = superuser.getValueFactory().createValue("xyz");
    vArray[2] = superuser.getValueFactory().createValue("123");
    // create String array
    String[] s = { "abc", "xyz", "123" };
    try {
        version.setProperty(propertyName1, s);
        version.save();
        fail("Version should be read-only: Version.setProperty(String,String[]) did not throw a ConstraintViolationException");
    } catch (ConstraintViolationException success) {
    }
    try {
        version.setProperty(propertyName1, s, PropertyType.STRING);
        version.save();
        fail("Version should be read-only: Version.setProperty(String,String[],int) did not throw a ConstraintViolationException");
    } catch (ConstraintViolationException success) {
    }
    try {
        version.setProperty(propertyName1, vArray);
        version.save();
        fail("Version should be read-only: Version.setProperty(String,Value[]) did not throw a ConstraintViolationException");
    } catch (ConstraintViolationException success) {
    }
    try {
        version.setProperty(propertyName1, vArray, PropertyType.STRING);
        version.save();
        fail("Version should be read-only: Version.setProperty(String,Value[],int]) did not throw a ConstraintViolationException");
    } catch (ConstraintViolationException success) {
    }
    try {
        version.setProperty(propertyName1, true);
        version.save();
        fail("Version should be read-only: Version.setProperty(String,boolean) did not throw a ConstraintViolationException");
    } catch (ConstraintViolationException success) {
    }
    try {
        version.setProperty(propertyName1, 123);
        version.save();
        fail("Version should be read-only: Version.setProperty(String,double) did not throw a ConstraintViolationException");
    } catch (ConstraintViolationException success) {
    }
    try {
        byte[] bytes = { 73, 26, 32, -36, 40, -43, -124 };
        InputStream inpStream = new ByteArrayInputStream(bytes);
        version.setProperty(propertyName1, inpStream);
        version.save();
        fail("Version should be read-only: Version.setProperty(String,InputStream) did not throw a ConstraintViolationException");
    } catch (ConstraintViolationException success) {
    }
    try {
        version.setProperty(propertyName1, "abc");
        version.save();
        fail("Version should be read-only: Version.setProperty(String,String) did not throw a ConstraintViolationException");
    } catch (ConstraintViolationException success) {
    }
    try {
        Calendar c = new GregorianCalendar(1945, 1, 6, 16, 20, 0);
        version.setProperty(propertyName1, c);
        version.save();
        fail("Version should be read-only: Version.setProperty(String,Calendar) did not throw a ConstraintViolationException");
    } catch (ConstraintViolationException success) {
    }
    try {
        version.setProperty(propertyName1, testRootNode);
        version.save();
        fail("Version should be read-only: Version.setProperty(String,Node) did not throw a ConstraintViolationException");
    } catch (ConstraintViolationException success) {
    }
    try {
        Value v = superuser.getValueFactory().createValue("abc");
        version.setProperty(propertyName1, v);
        version.save();
        fail("Version should be read-only: Version.setProperty(String,Value) did not throw a ConstraintViolationException");
    } catch (ConstraintViolationException success) {
    }
    try {
        version.setProperty(propertyName1, -2147483650L);
        version.save();
        fail("Version should be read-only: Version.setProperty(String,long) did not throw a ConstraintViolationException");
    } catch (ConstraintViolationException success) {
    }
}
Example 15
Project: terye-master  File: RestoreTest.java View source code
/**
     * VersionException expected on Node.restore(Version, boolean) if the
     * specified version is not part of this node's version history.
     *
     * @throws RepositoryException
     */
public void testRestoreInvalidVersion() throws RepositoryException {
    Version vNode2 = versionableNode2.checkin();
    try {
        versionableNode.restore(vNode2, true);
        fail("VersionException expected on Node.restore(Version, boolean) if the specified version is not part of this node's version history.");
    } catch (VersionException e) {
    }
}
Example 16
Project: 2014-sling-rookie-session-master  File: JcrReadSample.java View source code
String readJcrContent(Session session) throws RepositoryException {
    // get node directly
    Node day1 = session.getNode("/content/adaptto/2013/day1");
    // get first child node
    Node firstTalk = day1.getNodes().nextNode();
    // read property values
    String title = firstTalk.getProperty("jcr:title").getString();
    long duration = firstTalk.getProperty("durationMin").getLong();
    // read multi-valued property
    Value[] tagValues = firstTalk.getProperty("tags").getValues();
    String[] tags = new String[tagValues.length];
    for (int i = 0; i < tagValues.length; i++) {
        tags[i] = tagValues[i].getString();
    }
    return "First talk: " + title + " (" + duration + " min)\n" + "Tags: " + Arrays.toString(tags) + "\n" + "Path: " + firstTalk.getPath();
}
Example 17
Project: acs-aem-commons-master  File: WorkflowInstanceRemoverImpl.java View source code
/**
     * {@inheritDoc}
     */
public int removeWorkflowInstances(final ResourceResolver resourceResolver, final Collection<String> modelIds, final Collection<String> statuses, final Collection<Pattern> payloads, final Calendar olderThan, final int batchSize, final int maxDurationInMins) throws PersistenceException, WorkflowRemovalException, InterruptedException, WorkflowRemovalForceQuitException {
    final long start = System.currentTimeMillis();
    long end = -1;
    int count = 0;
    int checkedCount = 0;
    int workflowRemovedCount = 0;
    if (maxDurationInMins > 0) {
        // Max duration has been requested (greater than 0)
        // Convert minutes to milliseconds
        long maxDurationInMs = maxDurationInMins * MS_IN_ONE_MINUTE;
        // Compute the end time
        end = start + maxDurationInMs;
    }
    try {
        this.start(resourceResolver);
        final List<Resource> containerFolders = this.getWorkflowInstanceFolders(resourceResolver);
        for (Resource containerFolder : containerFolders) {
            log.debug("Checking [ {} ] for workflow instances to remove", containerFolder.getPath());
            final Collection<Resource> sortedFolders = this.getSortedAndFilteredFolders(containerFolder);
            for (final Resource folder : sortedFolders) {
                int remaining = 0;
                for (final Resource instance : folder.getChildren()) {
                    if (this.forceQuit.get()) {
                        throw new WorkflowRemovalForceQuitException();
                    } else if (end > 0 && System.currentTimeMillis() >= end) {
                        throw new WorkflowRemovalMaxDurationExceededException();
                    }
                    final ValueMap properties = instance.getValueMap();
                    if (!StringUtils.equals(NT_CQ_WORKFLOW, properties.get(JcrConstants.JCR_PRIMARYTYPE, String.class))) {
                        // Only process cq:Workflow's
                        remaining++;
                        continue;
                    }
                    checkedCount++;
                    final String status = getStatus(instance);
                    final String model = properties.get(PN_MODEL_ID, String.class);
                    final Calendar startTime = properties.get(PN_STARTED_AT, Calendar.class);
                    final String payload = properties.get(PAYLOAD_PATH, String.class);
                    if (StringUtils.isBlank(payload)) {
                        log.warn("Unable to find payload for Workflow instance [ {} ]", instance.getPath());
                        remaining++;
                        continue;
                    } else if (CollectionUtils.isNotEmpty(statuses) && !statuses.contains(status)) {
                        log.trace("Workflow instance [ {} ] has non-matching status of [ {} ]", instance.getPath(), status);
                        remaining++;
                        continue;
                    } else if (CollectionUtils.isNotEmpty(modelIds) && !modelIds.contains(model)) {
                        log.trace("Workflow instance [ {} ] has non-matching model of [ {} ]", instance.getPath(), model);
                        remaining++;
                        continue;
                    } else if (olderThan != null && startTime != null && startTime.before(olderThan)) {
                        log.trace("Workflow instance [ {} ] has non-matching start time of [ {} ]", instance.getPath(), startTime);
                        remaining++;
                        continue;
                    } else {
                        if (CollectionUtils.isNotEmpty(payloads)) {
                            // Only evaluate payload patterns if they are provided
                            boolean match = false;
                            if (StringUtils.isNotEmpty(payload)) {
                                for (final Pattern pattern : payloads) {
                                    if (payload.matches(pattern.pattern())) {
                                        // payload matches a pattern
                                        match = true;
                                        break;
                                    }
                                }
                                if (!match) {
                                    // Not a match; skip to next workflow instance
                                    log.trace("Workflow instance [ {} ] has non-matching payload path [ {} ]", instance.getPath(), payload);
                                    remaining++;
                                    continue;
                                }
                            }
                        }
                        try {
                            instance.adaptTo(Node.class).remove();
                            log.debug("Removed workflow instance at [ {} ]", instance.getPath());
                            workflowRemovedCount++;
                            count++;
                        } catch (RepositoryException e) {
                            log.error("Could not remove workflow instance at [ {} ]. Continuing...", instance.getPath(), e);
                        }
                        if (count % batchSize == 0) {
                            this.batchComplete(resourceResolver, checkedCount, workflowRemovedCount);
                            log.info("Removed a running total of [ {} ] workflow instances", count);
                        }
                    }
                }
                if (remaining == 0 && isWorkflowDatedFolder(folder) && !StringUtils.startsWith(folder.getName(), new SimpleDateFormat(WORKFLOW_FOLDER_FORMAT).format(new Date()))) {
                    // MUST match the YYYY-MM-DD(.*) pattern; do not try to remove root folders
                    try {
                        folder.adaptTo(Node.class).remove();
                        log.debug("Removed empty workflow folder node [ {} ]", folder.getPath());
                        // Incrementing only count to trigger batch save and not total since is not a WF
                        count++;
                    } catch (RepositoryException e) {
                        log.error("Could not remove workflow folder at [ {} ]", folder.getPath(), e);
                    }
                }
            }
            // Save final batch if needed, and update tracking nodes
            this.complete(resourceResolver, checkedCount, workflowRemovedCount);
        }
    } catch (PersistenceException e) {
        this.forceQuit.set(false);
        log.error("Error persisting changes with Workflow Removal", e);
        this.error(resourceResolver);
        throw e;
    } catch (WorkflowRemovalException e) {
        this.forceQuit.set(false);
        log.error("Error with Workflow Removal", e);
        this.error(resourceResolver);
        throw e;
    } catch (InterruptedException e) {
        this.forceQuit.set(false);
        log.error("Errors in persistence retries during Workflow Removal", e);
        this.error(resourceResolver);
        throw e;
    } catch (WorkflowRemovalForceQuitException e) {
        this.forceQuit.set(false);
        log.warn("Workflow removal was force quit. The removal state is unknown.");
        this.forceQuit(resourceResolver);
        throw e;
    } catch (WorkflowRemovalMaxDurationExceededException e) {
        log.warn("Workflow removal exceeded max duration of [ {} ] minutes. Final removal commit initiating...", maxDurationInMins);
        this.complete(resourceResolver, checkedCount, count);
    }
    if (log.isInfoEnabled()) {
        log.info("Workflow Removal Process Finished! " + "Removed a total of [ {} ] workflow instances in [ {} ] ms", count, System.currentTimeMillis() - start);
    }
    return count;
}
Example 18
Project: bricket-master  File: MultiboxPanel.java View source code
private List<ImageObject> createImageList(MultiboxConfig conf) {
    Reference ref = conf.getReference();
    BrixNode dataNode = ref.getNodeModel().getObject();
    // Erwartet wird ein Folder Namens thumb
    // DataNode enthält die Layoutbilder, thumbs die gleichnamigen
    // Thumbnails
    // Für *.flv Dateien befindet sich in thumbs jeweils eine *.png Datei
    List<String> slides = new ArrayList<String>();
    List<String> thumbs = new ArrayList<String>();
    Properties mbProperties = new Properties();
    for (JcrNodeIterator iterator = dataNode.getNodes(); iterator.hasNext(); ) {
        BrixNode node = new BrixNode((Node) iterator.next(), dataNode.getSession());
        if (node.getPath().endsWith("/mb.properties")) {
            try {
                mbProperties.load(node.getNode(Property.JCR_CONTENT).getProperty("jcr:data").getBinary().getStream());
            } catch (RepositoryException e) {
                log.error("error retrieving properties from jcr.", e);
            } catch (IOException e) {
                log.error("error creating properties.", e);
            }
        } else if (node.getPath().endsWith("/thumb")) {
            for (JcrNodeIterator subit = node.getNodes(); subit.hasNext(); ) {
                BrixNode thumb = new BrixNode((Node) subit.next(), dataNode.getSession());
                final String url = ((BricketApplication) getApplication()).getBrixLinkUrl(thumb, getRequestCycle());
                thumbs.add(url);
            }
        } else {
            final String url = ((BricketApplication) getApplication()).getBrixLinkUrl(node, getRequestCycle());
            slides.add(url);
        }
    }
    List<ImageObject> res = new ArrayList<ImageObject>();
    for (String slide : slides) {
        if (slide != null) {
            String title = slide.substring(slide.lastIndexOf('/') + 1);
            int order = Integer.MAX_VALUE;
            try {
                order = Integer.valueOf(mbProperties.getProperty(title + ".order"));
            } catch (NumberFormatException nfe) {
                log.error("invalid order value for: " + slide);
            }
            res.add(new ImageObject(slide, findThumb(slide, thumbs), title, mbProperties.getProperty(title + ".sub"), mbProperties.getProperty(title + ".desc"), order));
        }
    }
    Collections.sort(res, new ImageObjectOrderComparator());
    return res;
}
Example 19
Project: brix-cms-master  File: NodeWrapper.java View source code
public static JcrNode wrap(Node delegate, JcrSession session) {
    if (delegate == null) {
        return null;
    } else {
        Behavior behavior = session.getBehavior();
        if (behavior != null) {
            JcrNode node = behavior.wrap(delegate, session);
            if (node != null) {
                return node;
            }
        }
        return new NodeWrapper(delegate, session);
    }
}
Example 20
Project: brix-cms-plugins-master  File: ItemFilter.java View source code
@Override
public boolean isFilteredItem(Item item) {
    try {
        if (item instanceof Node) {
            Node node = (Node) item;
            if (node.isNodeType(BrixNode.JCR_MIXIN_BRIX_HIDDEN)) {
                return true;
            }
        } else {
            String name = item.getName();
            if (name.startsWith("brix:")) {
                return true;
            }
        }
    } catch (RepositoryException e) {
        return true;
    }
    return super.isFilteredItem(item);
}
Example 21
Project: chromattic-master  File: LinkManagerTestCase.java View source code
public void testAdd() throws Exception {
    Session session = login();
    AbstractLinkManager mgr = createLinkManager(session);
    Node root = session.getRootNode();
    Node a = root.addNode("a5");
    a.addMixin("mix:referenceable");
    Node b = root.addNode("b5");
    b.addMixin("mix:referenceable");
    //
    assertNull(mgr.setReferenced(b, "ref", a));
    assertEquals(b, mgr.getReferents(a, "ref"));
    //
    session.save();
    mgr = createLinkManager(session);
    assertEquals(b, mgr.getReferents(a, "ref"));
}
Example 22
Project: etk-component-master  File: DomainSessionImpl.java View source code
protected void _setLocalName(EntityContext ctx, String localName) throws RepositoryException {
    if (ctx == null) {
        throw new NullPointerException();
    }
    //
    switch(ctx.getStatus()) {
        case TRANSIENT:
            ((TransientEntityContextState) ctx.state).setLocalName(localName);
            break;
        case PERSISTENT:
            Node parentNode = ctx.getNode().getParent();
            String name = ctx.getNode().getName();
            int index = name.indexOf(':');
            String prefix = index == -1 ? null : name.substring(0, index);
            _move(ThrowableFactory.ISE, ctx, parentNode, prefix, localName);
            break;
        default:
            throw new IllegalStateException("Removed node cannot have its name updated");
    }
}
Example 23
Project: forum-master  File: JCRDataStorage.java View source code
private Node getNodeAt(SessionProvider sProvider, String relPath) throws Exception {
    if (relPath.indexOf(CommonUtils.SLASH) == 0) {
        relPath = relPath.substring(1);
    } else if (relPath.indexOf(Utils.CATEGORY) == 0) {
        relPath = dataLocator.getForumCategoriesLocation() + CommonUtils.SLASH + relPath;
    }
    return sessionManager.getSession(sProvider).getRootNode().getNode(relPath);
}
Example 24
Project: gatein-mop-master  File: NameEncodingTestCase.java View source code
public void testEncodeSite() throws Exception {
    ModelImpl model = pomService.getModel();
    Workspace workspace = model.getWorkspace();
    Site site = workspace.addSite(ObjectType.GROUP_SITE, ":");
    ChromatticSessionImpl session = (ChromatticSessionImpl) model.getSession();
    Node siteNode = session.getNode(site);
    assertEquals("mop:%04", siteNode.getName());
}
Example 25
Project: hippo-jcr-shell-master  File: JcrWrapper.java View source code
public static boolean removeNode(final Node node) {
    try {
        removeFromCache(node.getPath());
        if (node.getDepth() > 0) {
            removeFromCache(node.getParent().getPath());
        }
        node.remove();
        return true;
    } catch (RepositoryException e) {
        e.printStackTrace();
        return false;
    }
}
Example 26
Project: jackhammer-master  File: WatchCommand.java View source code
@Override
public void run() {
    if (!directory.exists()) {
        System.out.println("Cannot watch directory " + directory.getPath() + ". The specified path could not be found.");
        return;
    }
    Node node;
    try {
        String tmp = rootPath;
        if (rootPath.startsWith("/"))
            tmp = rootPath.substring(1);
        if ("".equals(tmp)) {
            node = session.getRootNode();
        } else {
            node = session.getRootNode().getNode(tmp);
        }
    } catch (RepositoryException e) {
        throw new RuntimeException("Unable to get node", e);
    }
    final DefaultFileHandlerFactory fileHandlerFactory = new DefaultFileHandlerFactory(new PathRelativizer(directory));
    final EventBus eventBus = new EventBus();
    eventBus.register(new LoggingEventListener(new Path(rootPath)));
    eventBus.register(new UploadingEventListener(fileHandlerFactory, session, node));
    final FileAlterationObserver observer = new FileAlterationObserver(directory);
    final FileAlterationMonitor monitor = new FileAlterationMonitor(1000);
    PathRelativizer pathRelativizer = new PathRelativizer(directory);
    FileAlterationListener listener = new JackhammerFileAlternationListener(eventBus, pathRelativizer);
    observer.addListener(listener);
    monitor.addObserver(observer);
    try {
        System.out.println("Watching " + directory.getCanonicalPath() + " and uploading changes to " + node.getPath());
        monitor.start();
    } catch (Exception e) {
        throw new RuntimeException("Unable to monitor files", e);
    }
}
Example 27
Project: jackrabbit-migration-master  File: NodeCopier.java View source code
/**
	 * Copy node with srcPath from one repository to another using the export and import functions by first partitioning node to subnodes of size less than 
	 * limit before exporting
	 * @param srcSession
	 * @param destSession
	 * @param srcPath 
	 * @param destPath 
	 * @param limit - size of a node in the partition
	 * @param createNodeType
	 * @throws RepositoryException
	 * @throws IOException
	 */
public static void copy(Session srcSession, Session destSession, String srcPath, String destPath, long limit, boolean addNodeType) throws RepositoryException, IOException {
    if (!srcSession.nodeExists(srcPath)) {
        log.error(srcPath + " does not exist");
        return;
    }
    createNodes(srcSession, destSession, destPath, addNodeType);
    Node node = srcSession.getNode(srcPath);
    int srcPathLength = srcPath.length();
    NodePartitioner partitioner = new NodeSizePartitioner(limit);
    Set<Map.Entry<String, Boolean>> descendants = partitioner.partition(node);
    for (Map.Entry<String, Boolean> entry : descendants) {
        String relPath = entry.getKey().substring(srcPathLength);
        copy(srcSession, destSession, srcPath, destPath, relPath, entry.getValue(), addNodeType);
    }
}
Example 28
Project: jcrom-extended-master  File: TestMapping.java View source code
static void printNode(Node node, String indentation) throws Exception {
    System.out.println();
    System.out.println(indentation + "------- NODE -------");
    System.out.println(indentation + "Path: " + node.getPath());
    System.out.println(indentation + "------- Properties: ");
    PropertyIterator propertyIterator = node.getProperties();
    while (propertyIterator.hasNext()) {
        Property p = propertyIterator.nextProperty();
        if (!p.getName().equals("jcr:data") && !p.getName().equals("jcr:mixinTypes") && !p.getName().equals("fileBytes")) {
            System.out.print(indentation + p.getName() + ": ");
            if (p.getDefinition().getRequiredType() == PropertyType.BINARY) {
                System.out.print("binary, (length:" + p.getLength() + ") ");
            } else if (!p.getDefinition().isMultiple()) {
                System.out.print(p.getString());
            } else {
                for (Value v : p.getValues()) {
                    System.out.print(v.getString() + ", ");
                }
            }
            System.out.println();
        }
        if (p.getName().equals("jcr:childVersionHistory")) {
            System.out.println(indentation + "------- CHILD VERSION HISTORY -------");
            printNode(node.getSession().getNodeByIdentifier(p.getString()), indentation + "\t");
            System.out.println(indentation + "------- CHILD VERSION ENDS -------");
        }
    }
    NodeIterator nodeIterator = node.getNodes();
    while (nodeIterator.hasNext()) {
        printNode(nodeIterator.nextNode(), indentation + "\t");
    }
}
Example 29
Project: jcromfx-master  File: TestMapping.java View source code
static void printNode(Node node, String indentation) throws Exception {
    System.out.println();
    System.out.println(indentation + "------- NODE -------");
    System.out.println(indentation + "Path: " + node.getPath());
    System.out.println(indentation + "------- Properties: ");
    PropertyIterator propertyIterator = node.getProperties();
    while (propertyIterator.hasNext()) {
        Property p = propertyIterator.nextProperty();
        if (!p.getName().equals("jcr:data") && !p.getName().equals("jcr:mixinTypes") && !p.getName().equals("fileBytes")) {
            System.out.print(indentation + p.getName() + ": ");
            if (p.getDefinition().getRequiredType() == PropertyType.BINARY) {
                System.out.print("binary, (length:" + p.getLength() + ") ");
            } else if (!p.getDefinition().isMultiple()) {
                System.out.print(p.getString());
            } else {
                for (Value v : p.getValues()) {
                    System.out.print(v.getString() + ", ");
                }
            }
            System.out.println();
        }
        if (p.getName().equals("jcr:childVersionHistory")) {
            System.out.println(indentation + "------- CHILD VERSION HISTORY -------");
            printNode(node.getSession().getNodeByIdentifier(p.getString()), indentation + "\t");
            System.out.println(indentation + "------- CHILD VERSION ENDS -------");
        }
    }
    NodeIterator nodeIterator = node.getNodes();
    while (nodeIterator.hasNext()) {
        printNode(nodeIterator.nextNode(), indentation + "\t");
    }
}
Example 30
Project: knowledge_vault-master  File: DirectDocumentModule.java View source code
/**
	 * Used when importing mail with attachments
	 */
public Document create(String token, Document doc, InputStream is, String userId) throws UnsupportedMimeTypeException, FileSizeExceededException, UserQuotaExceededException, VirusDetectedException, ItemExistsException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException, ExtensionException {
    log.debug("create({}, {}, {}, {})", new Object[] { token, doc, is, userId });
    Document newDocument = null;
    Node parentNode = null;
    Session session = null;
    int size = is.available();
    if (Config.SYSTEM_READONLY) {
        throw new AccessDeniedException("System is in read-only mode");
    }
    if (size > Config.MAX_FILE_SIZE) {
        log.error("Uploaded file size: {} ({}), Max file size: {} ({})", new Object[] { FormatUtil.formatSize(size), size, FormatUtil.formatSize(Config.MAX_FILE_SIZE), Config.MAX_FILE_SIZE });
        throw new FileSizeExceededException(Integer.toString(size));
    }
    String parent = JCRUtils.getParent(doc.getPath());
    String name = JCRUtils.getName(doc.getPath());
    // Add to KEA - must have the same extension
    int idx = name.lastIndexOf('.');
    String fileExtension = idx > 0 ? name.substring(idx) : ".tmp";
    File tmp = File.createTempFile("okm", fileExtension);
    try {
        if (token == null) {
            session = JCRUtils.getSession();
        } else {
            session = JcrSessionManager.getInstance().get(token);
        }
        // Escape dangerous chars in name
        name = JCRUtils.escape(name);
        doc.setPath(parent + "/" + name);
        parentNode = session.getRootNode().getNode(parent.substring(1));
        // Check file restrictions
        String mimeType = Config.mimeTypes.getContentType(name.toLowerCase());
        doc.setMimeType(mimeType);
        if (Config.RESTRICT_FILE_MIME && MimeTypeDAO.findByName(mimeType) == null) {
            throw new UnsupportedMimeTypeException(mimeType);
        }
        // Manage temporary files
        byte[] buff = new byte[4 * 1024];
        FileOutputStream fos = new FileOutputStream(tmp);
        int read;
        while ((read = is.read(buff)) != -1) {
            fos.write(buff, 0, read);
        }
        fos.flush();
        fos.close();
        is.close();
        is = new FileInputStream(tmp);
        if (!Config.SYSTEM_ANTIVIR.equals("")) {
            VirusDetection.detect(tmp);
        }
        // Start KEA
        // Adding submitted keywords
        Collection<String> keywords = doc.getKeywords() != null ? doc.getKeywords() : new ArrayList<String>();
        if (!Config.KEA_MODEL_FILE.equals("")) {
            MetadataExtractor mdExtractor = new MetadataExtractor(Config.KEA_AUTOMATIC_KEYWORD_EXTRACTION_NUMBER);
            MetadataDTO mdDTO = mdExtractor.extract(tmp);
            for (ListIterator<Term> it = mdDTO.getSubjectsAsTerms().listIterator(); it.hasNext(); ) {
                Term term = it.next();
                log.info("Term:" + term.getText());
                if (Config.KEA_AUTOMATIC_KEYWORD_EXTRACTION_RESTRICTION) {
                    if (RDFREpository.getInstance().getKeywords().contains(term.getText())) {
                        // Replacing spaces to "_" and adding at ends space for other word
                        keywords.add(term.getText().replace(" ", "_"));
                    }
                } else {
                    // Replacing spaces to "_" and adding at ends space for other word
                    keywords.add(term.getText().replace(" ", "_"));
                }
            }
        }
        // End KEA
        // EP - PRE
        Ref<Node> refParentNode = new Ref<Node>(parentNode);
        Ref<File> refTmp = new Ref<File>(tmp);
        Ref<Document> refDoc = new Ref<Document>(doc);
        DocumentExtensionManager.getInstance().preCreate(session, refParentNode, refTmp, refDoc);
        parentNode = refParentNode.get();
        name = JCRUtils.escape(JCRUtils.getName(refDoc.get().getPath()));
        mimeType = refDoc.get().getMimeType();
        keywords = refDoc.get().getKeywords();
        Node documentNode = BaseDocumentModule.create(session, parentNode, /* doc.getTitle() */
        name, null, mimeType, keywords.toArray(new String[keywords.size()]), is);
        // EP - POST
        Ref<Node> refDocumentNode = new Ref<Node>(documentNode);
        DocumentExtensionManager.getInstance().postCreate(session, refParentNode, refDocumentNode);
        // Check document filters
        // DocumentUtils.checkFilters(session, documentNode, mimeType);
        // Set returned document properties
        newDocument = BaseDocumentModule.getProperties(session, documentNode);
        if (userId == null) {
            // Check subscriptions
            BaseNotificationModule.checkSubscriptions(documentNode, session.getUserID(), "CREATE_DOCUMENT", null);
            // Check scripting
            BaseScriptingModule.checkScripts(session, parentNode, documentNode, "CREATE_DOCUMENT");
            // Activity log
            UserActivity.log(session.getUserID(), "CREATE_DOCUMENT", documentNode.getUUID(), mimeType + ", " + size + ", " + doc.getPath());
        } else {
            // Check subscriptions
            BaseNotificationModule.checkSubscriptions(documentNode, userId, "CREATE_MAIL_ATTACHMENT", null);
            // Check scripting
            BaseScriptingModule.checkScripts(session, parentNode, documentNode, "CREATE_MAIL_ATTACHMENT");
            // Activity log
            UserActivity.log(userId, "CREATE_MAIL_ATTACHMENT", documentNode.getUUID(), mimeType + ", " + size + ", " + doc.getPath());
        }
    } catch (javax.jcr.ItemExistsException e) {
        log.warn(e.getMessage(), e);
        JCRUtils.discardsPendingChanges(parentNode);
        throw new ItemExistsException(e.getMessage(), e);
    } catch (javax.jcr.PathNotFoundException e) {
        log.warn(e.getMessage(), e);
        JCRUtils.discardsPendingChanges(parentNode);
        throw new PathNotFoundException(e.getMessage(), e);
    } catch (javax.jcr.AccessDeniedException e) {
        log.warn(e.getMessage(), e);
        JCRUtils.discardsPendingChanges(parentNode);
        throw new AccessDeniedException(e.getMessage(), e);
    } catch (javax.jcr.RepositoryException e) {
        log.error(e.getMessage(), e);
        JCRUtils.discardsPendingChanges(parentNode);
        throw new RepositoryException(e.getMessage(), e);
    } catch (java.io.IOException e) {
        log.error(e.getMessage(), e);
        JCRUtils.discardsPendingChanges(parentNode);
        throw e;
    } catch (MetadataExtractionException e) {
        log.error(e.getMessage(), e);
        JCRUtils.discardsPendingChanges(parentNode);
        throw new RepositoryException(e.getMessage(), e);
    } catch (VirusDetectedException e) {
        JCRUtils.discardsPendingChanges(parentNode);
        throw e;
    } catch (DatabaseException e) {
        JCRUtils.discardsPendingChanges(parentNode);
        throw e;
    } catch (ExtensionException e) {
        JCRUtils.discardsPendingChanges(parentNode);
        throw e;
    } finally {
        org.apache.commons.io.FileUtils.deleteQuietly(tmp);
        if (token == null)
            JCRUtils.logout(session);
    }
    log.info("create: {}", newDocument);
    return newDocument;
}
Example 31
Project: ks-master  File: JCRDataStorage.java View source code
public void addCalculateModeratorEventListener() throws Exception {
    SessionProvider sProvider = SessionProvider.createSystemProvider();
    Node categoryHome = getCategoryHome(sProvider);
    try {
        NodeIterator iter = categoryHome.getNodes();
        NodeIterator iter1;
        while (iter.hasNext()) {
            Node catNode = iter.nextNode();
            if (catNode.isNodeType(EXO_FORUM_CATEGORY)) {
                addModeratorCalculateListener(catNode);
                iter1 = catNode.getNodes();
                while (iter1.hasNext()) {
                    Node forumNode = iter1.nextNode();
                    if (forumNode.isNodeType(EXO_FORUM)) {
                        addModeratorCalculateListener(forumNode);
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("Failed to add calculate moderator event listener", e);
    } finally {
        sProvider.close();
    }
}
Example 32
Project: magnolia-templating-master  File: LinkModel.java View source code
/**
     * Get the title for an internal link by returning the first of the following items that are available
     * <ul>
     * <li>The title field of the component</li>
     * <li>The title of the referenced page</li>
     * <li>The node name of the referenced page</li>
     * </ul>.
     */
protected String getInternalTitle() {
    final String title = PropertyUtil.getString(content, PROPERTY_NAME_TITLE);
    if (StringUtils.isNotBlank(title)) {
        return title;
    }
    try {
        final Node linkedNode = templatingFunctions.contentByReference(content, PROPERTY_NAME_INTERNAL, RepositoryConstants.WEBSITE);
        final String pageTitle = PropertyUtil.getString(linkedNode, PROPERTY_NAME_TITLE, "");
        if (StringUtils.isNotBlank(pageTitle)) {
            return pageTitle;
        }
        return linkedNode.getName();
    } catch (RepositoryException e) {
        log.warn("An error occurred when trying to get referenced content for node [{}] and property [{}]", content, PROPERTY_NAME_INTERNAL, e);
    }
    return "";
}
Example 33
Project: modeshape-master  File: ModeshapePersistenceIT.java View source code
@Test
public void shouldNotImportInitialContentIfWorkspaceContentsChanged() throws Exception {
    startRunStop( repository -> {
        Session ws1Session = repository.login();
        Node node = ws1Session.getNode("/a");
        assertNotNull(node);
        node.remove();
        ws1Session.getRootNode().addNode("testNode");
        ws1Session.save();
    }, true, false);
    startRunStop( repository -> {
        Session ws1Session = repository.login();
        try {
            ws1Session.getNode("/a");
            fail("The initial content should be be re-imported if a workspace is not empty");
        } catch (PathNotFoundException e) {
        }
        ws1Session.getNode("/testNode");
    }, false, true);
}
Example 34
Project: org.liveSense.service.thumbnailGenerator-master  File: ThumbnailGeneratorJobEventHandler.java View source code
public boolean createThumbnailsForImage(Resource resource) throws RepositoryException, Exception {
    try {
        log.info("Generating thumbnail for image " + resource.getPath());
        Node node = null;
        if (resource != null)
            node = resource.adaptTo(Node.class);
        if (node == null)
            return false;
        // if thumbnail folder does not exists we generate it
        if (!node.getParent().hasNode(thumbnailFolder)) {
            node.getParent().addNode(thumbnailFolder, "thumbnail:thumbnailFolder");
        }
        // session.save();
        Node thumbnailFolderNode = node.getParent().getNode(thumbnailFolder);
        // Removing thumbnail images
        NodeIterator iter = thumbnailFolderNode.getNodes(resource.getName() + "*");
        while (iter.hasNext()) {
            Node rm = iter.nextNode();
            if (rm.isNodeType("thumbnail:thumbnailImage") && rm.hasProperty("originalNodeLastModified") && rm.getProperty("originalNodeLastModified").getDate().equals(node.getNode("jcr:content").getProperty("jcr:lastModified").getDate())) {
            } else {
                log.info(" -> Removing old thumbnail: " + rm.getName());
                rm.remove();
            }
        }
        // Generating thumbnail images
        for (int i = 0; i < thumbnailResolutions.length; i++) {
            String[] reso = thumbnailResolutions[i].split("x");
            int width, height;
            width = Integer.parseInt(reso[0]);
            height = Integer.parseInt(reso[1]);
            String thumbnailName = resource.getName() + "." + width + "." + height + ".jpg";
            if (!thumbnailFolderNode.hasNode(thumbnailName)) {
                final BufferedImage src = ImageIO.read(node.getNode("jcr:content").getProperty("jcr:data").getBinary().getStream());
                if (src == null) {
                    final StringBuffer sb = new StringBuffer();
                    for (String fmt : ImageIO.getReaderFormatNames()) {
                        sb.append(fmt);
                        sb.append(' ');
                    }
                    throw new IOException("Unable to read image, registered formats: " + sb);
                }
                final double scale = (double) width / src.getWidth();
                int destWidth = width;
                int destHeight = height > 0 ? height : new Double(scale * src.getHeight()).intValue();
                log.info(" ---> Generating thumbnail, w={}, h={}", destWidth, destHeight);
                final BufferedImage dest = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
                ScaleFilter filter = new ScaleFilter(destWidth, destHeight);
                filter.filter(src, dest);
                final File tmp = File.createTempFile(getClass().getSimpleName(), resource.getName() + "." + Calendar.getInstance().getTimeInMillis());
                try {
                    FileOutputStream outs = new FileOutputStream(tmp);
                    ImageIO.write(dest, "jpg", outs);
                    outs.flush();
                    outs.close();
                    // Create thumbnail node and set the mandatory properties
                    Node thumbnail = thumbnailFolderNode.addNode(thumbnailName, "thumbnail:thumbnailImage");
                    thumbnail.addNode("jcr:content", "nt:resource").setProperty("jcr:data", new Binary() {

                        InputStream is;

                        @Override
                        public InputStream getStream() throws RepositoryException {
                            try {
                                is = new FileInputStream(tmp);
                            } catch (FileNotFoundException e) {
                                log.error("IOError: ", e);
                            }
                            return is;
                        }

                        @Override
                        public int read(byte[] b, long position) throws IOException, RepositoryException {
                            return is.read(b, (int) position, 4096);
                        }

                        @Override
                        public long getSize() throws RepositoryException {
                            try {
                                return is.available();
                            } catch (IOException e) {
                                throw new RepositoryException(e);
                            }
                        }

                        @Override
                        public void dispose() {
                            try {
                                is.close();
                            } catch (Exception e) {
                                log.error("Dispose error!");
                            }
                        }
                    });
                    thumbnail.getNode("jcr:content").setProperty("jcr:lastModified", Calendar.getInstance());
                    thumbnail.getNode("jcr:content").setProperty("jcr:mimeType", "image/jpg");
                    thumbnail.setProperty("originalNodePath", resource.getPath());
                    thumbnail.setProperty("originalNodeLastModified", node.getNode("jcr:content").getProperty("jcr:lastModified").getDate());
                    thumbnail.setProperty("width", destWidth);
                    thumbnail.setProperty("height", destHeight);
                    log.info(" -> generated name: " + thumbnail.getPath() + " Width: {} Height: {} ", Integer.toString(destWidth), Integer.toString(destHeight));
                //session.save();
                } catch (Exception e) {
                    return false;
                } finally {
                    if (tmp != null) {
                        tmp.delete();
                    }
                }
            }
        }
        return true;
    } finally {
    }
}
Example 35
Project: platform-master  File: LoginHistoryServiceImpl.java View source code
/**
     * Create exo:LoginHistoryHome node.
     *
     * @throws RepositoryException
     */
protected void createHomeNode() throws RepositoryException {
    SessionProvider sProvider = SessionProvider.createSystemProvider();
    try {
        ManageableRepository currentRepo = this.repositoryService.getCurrentRepository();
        Session session = sProvider.getSession(currentRepo.getConfiguration().getDefaultWorkspaceName(), currentRepo);
        Node rootNode = session.getRootNode();
        if (!rootNode.hasNode(HOME)) {
            Node homeNode = rootNode.addNode(HOME, "exo:LoginHisSvc_loginHistoryService");
            homeNode.addMixin("exo:privilegeable");
            Map<String, String[]> permissions = new HashMap<String, String[]>();
            permissions.put("*:/platform/administrators", PermissionType.ALL);
            permissions.put("*:/platform/users", new String[] { PermissionType.READ });
            ((ExtendedNode) homeNode).setPermissions(permissions);
            homeNode.addMixin("exo:owneable");
            rootNode.save();
            // --- PLF-2493 : Umbrella for usability issues
            if (homeNode.canAddMixin("exo:hiddenable")) {
                homeNode.addMixin("exo:hiddenable");
            }
            Node globalLoginCounterNode = homeNode.addNode(ALL_USERS, "exo:LoginHisSvc_globalLoginCounter");
            globalLoginCounterNode.setProperty("exo:LoginHisSvc_globalLoginCounter_lastIndex", 0);
            homeNode.save();
            LOG.info("Login history storage initialized.");
        }
    } finally {
        sProvider.close();
    }
}
Example 36
Project: sling-pipes-master  File: WritePipeTest.java View source code
@Test
public void testSimpleTree() throws Exception {
    Resource confResource = context.resourceResolver().getResource(PATH_PIPE + "/" + NN_SIMPLETREE);
    Pipe pipe = plumber.getPipe(confResource);
    assertNotNull("pipe should be found", pipe);
    assertTrue("this pipe should be marked as content modifier", pipe.modifiesContent());
    pipe.getOutput();
    context.resourceResolver().commit();
    Resource appleResource = context.resourceResolver().getResource("/content/fruits/apple");
    ValueMap properties = appleResource.adaptTo(ValueMap.class);
    assertTrue("There should be hasSeed set to true", properties.get("hasSeed", false));
    assertArrayEquals("Colors should be correctly set", new String[] { "green", "red" }, properties.get("colors", String[].class));
    Node appleNode = appleResource.adaptTo(Node.class);
    NodeIterator children = appleNode.getNodes();
    assertTrue("Apple node should have children", children.hasNext());
}
Example 37
Project: sling-web-resource-master  File: WebResourceInventoryManagerImpl.java View source code
public Map<String, String> getWebResources(Session session) throws RepositoryException {
    Map<String, String> result = new HashMap<String, String>();
    Query query = session.getWorkspace().getQueryManager().createQuery("SELECT * FROM [webresource:WebResourceGroup] as webResourceGroupSet", Query.JCR_SQL2);
    QueryResult queryResult = query.execute();
    NodeIterator queryIt = queryResult.getNodes();
    while (queryIt.hasNext()) {
        Node webResourceNode = queryIt.nextNode();
        result.put(webResourceNode.getProperty(WebResourceGroup.NAME).getString(), webResourceNode.getPath());
    }
    return result;
}
Example 38
Project: SlingBeans-master  File: VltManager.java View source code
public void importContentToRemote(String contentPath, String jcrPath, boolean nonRecursive) throws Exception {
    if (lockUpdates) {
        return;
    }
    contentPath = normalizePath(contentPath, true);
    jcrPath = normalizePath(jcrPath, true);
    LogHelper.logInfo(this, "importContent(%s, %s, %s)", contentPath, jcrPath, nonRecursive);
    //  File localFile = new File(localContentPath);
    File vltContent = new File(contentPath);
    FileArchive vltFileArchive = new FileArchive(vltContent);
    vltSession = getSession();
    vltFileArchive.open(false);
    ImportOptions impOpts = new ImportOptions();
    impOpts.setNonRecursive(false);
    DefaultWorkspaceFilter defaultWorkspaceFilter = new DefaultWorkspaceFilter();
    defaultWorkspaceFilter.add(new PathFilterSet(jcrPath));
    impOpts.setFilter(defaultWorkspaceFilter);
    Importer imp = new Importer(impOpts);
    Node remoteRootNode = null;
    remoteRootNode = vltSession.getRootNode();
    imp.run(vltFileArchive, remoteRootNode);
    vltFileArchive.close();
}
Example 39
Project: spring-modules-jcr-master  File: JcrTemplateTests.java View source code
/*
     * Test method for 'org.springmodules.jcr.JcrTemplate.getNodeByUUID(String)'
     */
public void testGetNodeByUUID() throws RepositoryException {
    MockControl resultMock = MockControl.createControl(Node.class);
    Node result = (Node) resultMock.getMock();
    String uuid = "uuid";
    sessionControl.expectAndReturn(session.getNodeByUUID(uuid), result);
    sessionControl.replay();
    sfControl.replay();
    assertSame(jt.getNodeByUUID(uuid), result);
}
Example 40
Project: experiencemanager-java-msmrollout-master  File: ExampleLiveActionFactory.java View source code
public void execute(Resource source, Resource target, LiveRelationship liverel, boolean autoSave, boolean isResetRollout) throws WCMException {
    String lastMod = null;
    log.info(" *** Executing ExampleLiveAction *** ");
    /* Determine if the LiveAction is configured to copy the cq:lastModifiedBy property */
    if ((Boolean) configs.get("repLastModBy")) {
        /* get the source's cq:lastModifiedBy property */
        if (source != null && source.adaptTo(Node.class) != null) {
            ValueMap sourcevm = source.adaptTo(ValueMap.class);
            lastMod = sourcevm.get(com.day.cq.wcm.api.NameConstants.PN_PAGE_LAST_MOD_BY, String.class);
        }
        /* set the target node's la-lastModifiedBy property */
        Session session = null;
        if (target != null && target.adaptTo(Node.class) != null) {
            ResourceResolver resolver = target.getResourceResolver();
            session = resolver.adaptTo(javax.jcr.Session.class);
            Node targetNode;
            try {
                targetNode = target.adaptTo(javax.jcr.Node.class);
                targetNode.setProperty("la-lastModifiedBy", lastMod);
                log.info(" *** Target node lastModifiedBy property updated: {} ***", lastMod);
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        if (autoSave) {
            try {
                session.save();
            } catch (Exception e) {
                try {
                    session.refresh(true);
                } catch (RepositoryException e1) {
                    e1.printStackTrace();
                }
                e.printStackTrace();
            }
        }
    }
}
Example 41
Project: staging-extension-master  File: SocialDataExportResource.java View source code
/**
   * Export space avatar.
   *
   * @param exportTasks the export tasks
   * @param space the space
   * @param spaceIdentity the space identity
   * @throws UnsupportedEncodingException the unsupported encoding exception
   * @throws Exception the exception
   * @throws PathNotFoundException the path not found exception
   * @throws RepositoryException the repository exception
   * @throws ValueFormatException the value format exception
   */
private void exportSpaceAvatar(List<ExportTask> exportTasks, Space space, Identity spaceIdentity) throws UnsupportedEncodingException, Exception, PathNotFoundException, RepositoryException, ValueFormatException {
    // No method to get avatar using Social API, so we have to use JCR
    String avatarURL = spaceIdentity.getProfile().getAvatarUrl();
    avatarURL = avatarURL == null ? null : URLDecoder.decode(avatarURL, "UTF-8");
    if (avatarURL != null && avatarURL.contains(space.getPrettyName())) {
        int beginIndexAvatarPath = avatarURL.indexOf("repository/social") + ("repository/social").length();
        int endIndexAvatarPath = avatarURL.indexOf("?");
        String avatarNodePath = endIndexAvatarPath >= 0 ? avatarURL.substring(beginIndexAvatarPath, endIndexAvatarPath) : avatarURL.substring(beginIndexAvatarPath);
        Session session = AbstractJCRImportOperationHandler.getSession(repositoryService, "social");
        Node avatarNode = (Node) session.getItem(avatarNodePath);
        Node avatarJCRContentNode = avatarNode.getNode("jcr:content");
        String fileName = "avatar";
        String mimeType = avatarJCRContentNode.hasProperty("jcr:data") ? avatarJCRContentNode.getProperty("jcr:mimeType").getString() : null;
        InputStream inputStream = avatarJCRContentNode.hasProperty("jcr:data") ? avatarJCRContentNode.getProperty("jcr:data").getStream() : null;
        Calendar lastModified = avatarJCRContentNode.hasProperty("jcr:data") ? avatarJCRContentNode.getProperty("jcr:lastModified").getDate() : null;
        AvatarAttachment avatar = new AvatarAttachment(null, fileName, mimeType, inputStream, null, lastModified.getTimeInMillis());
        exportTasks.add(new SpaceAvatarExportTask(space.getPrettyName(), avatar));
    }
}
Example 42
Project: aem-samples-master  File: ReferencedAssetsServlet.java View source code
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
    response.setContentType("application/json");
    try {
        JSONObject jsonOut = new JSONObject();
        Node jcrNode = request.getResource().adaptTo(Node.class);
        if (jcrNode == null) {
            // every adaptTo() can return null, so let's handle that case here 
            // although it's very unlikely
            LOG.error("cannot adapt resource {} to a node", request.getResource().getPath());
            response.getOutputStream().print(new JSONObject().toString());
            return;
        }
        // let's use the specialized assetReferenceSearch, which does all the work for us
        AssetReferenceSearch search = new AssetReferenceSearch(jcrNode, DAM_ROOT, request.getResourceResolver());
        Map<String, Asset> result = search.search();
        for (String key : result.keySet()) {
            Asset asset = result.get(key);
            JSONObject assetDetails = new JSONObject();
            assetDetails.put("path", asset.getPath());
            assetDetails.put("mimetype", asset.getMimeType());
            jsonOut.put(asset.getName(), assetDetails);
        }
        response.getOutputStream().print(jsonOut.toString(2));
    } catch (JSONException e) {
        LOG.error("Cannot serialize JSON", e);
        response.getOutputStream().print(new JSONObject().toString());
    }
}
Example 43
Project: astroboa-master  File: ContentServiceTest.java View source code
private ContentObject saveAndAssertBinaryContentIsSaved(ContentObject contentObject, String contentSource, File fileWhichContainsContent, String property, Map<String, byte[]> binaryContent) throws Exception {
    try {
        ImportConfiguration configuration = ImportConfiguration.object().persist(PersistMode.PERSIST_ENTITY_TREE).version(false).updateLastModificationTime(true).addBinaryContent(binaryContent).build();
        contentObject = importService.importContentObject(contentSource, configuration);
        //reload object 
        ContentObject object = contentService.getContentObject(contentObject.getId(), ResourceRepresentationType.CONTENT_OBJECT_INSTANCE, FetchLevel.ENTITY, CacheRegion.NONE, null, false);
        BinaryProperty imageProperty = (BinaryProperty) object.getCmsProperty(property);
        Assert.assertTrue(imageProperty.hasValues(), "No binary channel saved for " + property + " property");
        for (BinaryChannel imageBinaryChannel : imageProperty.getSimpleTypeValues()) {
            String sourceFilename = imageBinaryChannel.getSourceFilename();
            Assert.assertTrue(StringUtils.isNotBlank(sourceFilename), " BinaryChannel " + imageBinaryChannel.getName() + " does not have a source file name");
            File fileWhoseContentsAreSavedInBinaryChannel = null;
            if (sourceFilename.equals(fileWhichContainsContent.getName())) {
                fileWhoseContentsAreSavedInBinaryChannel = fileWhichContainsContent;
            } else {
                throw new Exception("BnaryChannel contains an invalid source file name " + sourceFilename);
            }
            String mimeType = new MimetypesFileTypeMap().getContentType(fileWhoseContentsAreSavedInBinaryChannel);
            if (property.contains(".")) {
                Assert.assertEquals(imageBinaryChannel.getName(), StringUtils.substringAfterLast(property, "."));
            } else {
                Assert.assertEquals(imageBinaryChannel.getName(), property);
            }
            Assert.assertEquals(imageBinaryChannel.getMimeType(), mimeType);
            Assert.assertEquals(imageBinaryChannel.getSourceFilename(), sourceFilename);
            Assert.assertEquals(imageBinaryChannel.getSize(), FileUtils.readFileToByteArray(fileWhoseContentsAreSavedInBinaryChannel).length);
            Assert.assertEquals(imageBinaryChannel.getModified().getTimeInMillis(), fileWhoseContentsAreSavedInBinaryChannel.lastModified());
            //Now test in jcr to see if the proper node is created
            Node binaryChannelNode = getSession().getNodeByIdentifier(imageBinaryChannel.getId());
            //If node is not found then exception has already been thrown
            Assert.assertEquals(binaryChannelNode.getName(), imageBinaryChannel.getName(), " Invalid name for binary data jcr node " + binaryChannelNode.getPath());
            if (property.contains(".")) {
                Assert.assertEquals(binaryChannelNode.getProperty(CmsBuiltInItem.Name.getJcrName()).getString(), StringUtils.substringAfterLast(property, "."));
            } else {
                Assert.assertEquals(binaryChannelNode.getProperty(CmsBuiltInItem.Name.getJcrName()).getString(), property);
            }
            Assert.assertEquals(binaryChannelNode.getProperty(JcrBuiltInItem.JcrMimeType.getJcrName()).getString(), mimeType);
            Assert.assertEquals(binaryChannelNode.getProperty(CmsBuiltInItem.SourceFileName.getJcrName()).getString(), sourceFilename);
            Assert.assertEquals(binaryChannelNode.getProperty(CmsBuiltInItem.Size.getJcrName()).getLong(), fileWhoseContentsAreSavedInBinaryChannel.length());
            Assert.assertEquals(binaryChannelNode.getProperty(JcrBuiltInItem.JcrLastModified.getJcrName()).getDate().getTimeInMillis(), fileWhoseContentsAreSavedInBinaryChannel.lastModified());
        }
    } catch (Exception e) {
        logger.error("Initial \n{}", contentSource);
        throw e;
    }
    return contentObject;
}
Example 44
Project: camel-master  File: JcrProducer.java View source code
public void process(Exchange exchange) throws Exception {
    TypeConverter converter = exchange.getContext().getTypeConverter();
    Session session = openSession();
    Message message = exchange.getIn();
    String operation = determineOperation(message);
    try {
        if (JcrConstants.JCR_INSERT.equals(operation)) {
            Node base = findOrCreateNode(session.getRootNode(), getJcrEndpoint().getBase(), "");
            Node node = findOrCreateNode(base, getNodeName(message), getNodeType(message));
            Map<String, Object> headers = filterComponentHeaders(message.getHeaders());
            for (String key : headers.keySet()) {
                Object header = message.getHeader(key);
                if (header != null && Object[].class.isAssignableFrom(header.getClass())) {
                    Value[] value = converter.convertTo(Value[].class, exchange, header);
                    node.setProperty(key, value);
                } else {
                    Value value = converter.convertTo(Value.class, exchange, header);
                    node.setProperty(key, value);
                }
            }
            node.addMixin("mix:referenceable");
            exchange.getOut().setBody(node.getIdentifier());
            session.save();
        } else if (JcrConstants.JCR_GET_BY_ID.equals(operation)) {
            Node node = session.getNodeByIdentifier(exchange.getIn().getMandatoryBody(String.class));
            PropertyIterator properties = node.getProperties();
            while (properties.hasNext()) {
                Property property = properties.nextProperty();
                Class<?> aClass = classForJCRType(property);
                Object value;
                if (property.isMultiple()) {
                    value = converter.convertTo(aClass, exchange, property.getValues());
                } else {
                    value = converter.convertTo(aClass, exchange, property.getValue());
                }
                message.setHeader(property.getName(), value);
            }
        } else {
            throw new RuntimeException("Unsupported operation: " + operation);
        }
    } finally {
        if (session != null && session.isLive()) {
            session.logout();
        }
    }
}
Example 45
Project: delcyon-capo-master  File: JcrResourceDescriptor.java View source code
@Override
public OutputStream getOutputStream(VariableContainer variableContainer, ResourceParameter... resourceParameters) throws Exception {
    //return the output stream we have, if it's already open
    if (this.pipedOutputStream != null) {
        return this.pipedOutputStream;
    }
    synchronized (isWriting) {
        isWriting = true;
        //If we're going to write. make sure we have a node to write to.
        if (getNode() == null) {
            performAction(variableContainer, Action.CREATE, resourceParameters);
            performAction(variableContainer, Action.COMMIT, resourceParameters);
        }
        final PipedInputStream pipedInputStream = new PipedInputStream() {

            @Override
            public void close() throws IOException {
                //System.out.println("piped input close attempt: "+System.currentTimeMillis());
                // TODO Auto-generated method stub
                super.close();
            //System.out.println("piped input closed: "+System.currentTimeMillis());
            }
        };
        PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream) {

            @Override
            public void close() throws IOException {
                //System.out.println("piped output close attempt: "+System.currentTimeMillis());
                super.close();
                //System.out.println("isWaiting = "+isWriting);
                Boolean _isWaiting = null;
                synchronized (isWriting) {
                    _isWaiting = isWriting;
                }
                //System.out.println("isWaiting = "+_isWaiting);
                while (_isWaiting == true) {
                    try {
                        //	System.out.println("waiting for pipe thread to finish");
                        Thread.sleep(100);
                        synchronized (isWriting) {
                            _isWaiting = isWriting;
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //System.out.println("piped output closed: "+System.currentTimeMillis());
                JcrResourceDescriptor.this.pipedOutputStream = null;
            }
        };
        //MimeTable mt = MimeTable.getDefaultTable();
        //String mimeType = mt.getContentTypeFor(file.getName());
        //if (mimeType == null) mimeType = "application/octet-stream";
        // Node fileNode = node.addNode("<name>", "nt:file");
        //System.out.println( fileNode.getName() );
        //final Node resNode = fileNode.addNode("jcr:content", "nt:resource");
        //resNode.setProperty("jcr:mimeType", "<mimeType>");
        //resNode.setProperty("jcr:encoding", "");
        Runnable pipe = new Runnable() {

            @Override
            public void run() {
                try {
                    MD5FilterInputStream md5FilterInputStream = new MD5FilterInputStream(pipedInputStream);
                    ContentFormatTypeFilterInputStream contentFormatTypeFilterInputStream = new ContentFormatTypeFilterInputStream(md5FilterInputStream);
                    MimeTypeFilterInputStream mimeTypeFilterInputStream = new MimeTypeFilterInputStream(contentFormatTypeFilterInputStream);
                    SizeFilterInputStream sizeFilterInputStream = new SizeFilterInputStream(mimeTypeFilterInputStream);
                    //System.out.println("pipe thread start read: "+System.currentTimeMillis());
                    synchronized (hasPipeThreadStarted) {
                        hasPipeThreadStarted.notify();
                    }
                    Binary binary = getNode().getSession().getValueFactory().createBinary(sizeFilterInputStream);
                    if (binary.getSize() != 0) {
                        getNode().setProperty("jcr:data", binary);
                        getNode().setProperty(contentFormatTypeFilterInputStream.getName(), contentFormatTypeFilterInputStream.getValue());
                        if (contentFormatTypeFilterInputStream.getContentFormatType() != ContentFormatType.BINARY) {
                            byte[] buffer = new byte[(int) binary.getSize()];
                            binary.read(buffer, 0);
                            getNode().setProperty("content", new String(buffer));
                        } else if (getNode().hasProperty("content")) {
                            getNode().getProperty("content").remove();
                        }
                        getNode().setProperty(sizeFilterInputStream.getName(), sizeFilterInputStream.getValue());
                        getNode().setProperty(mimeTypeFilterInputStream.getName(), mimeTypeFilterInputStream.getValue());
                        //getNode().setProperty("jcr:mimeType",mimeTypeFilterInputStream.getValue());
                        getNode().setProperty(md5FilterInputStream.getName(), md5FilterInputStream.getValue());
                    } else //there is no data
                    {
                        PropertyIterator propertyIterator = getNode().getProperties();
                        while (propertyIterator.hasNext()) {
                            Property property = propertyIterator.nextProperty();
                            if (property.getName().startsWith("jcr:") == false) {
                                property.remove();
                            }
                        }
                        if (getNode().hasProperty("jcr:data")) {
                            getNode().getProperty("jcr:data").remove();
                        }
                    }
                    binary.dispose();
                    //System.out.println("pipe thread done: "+System.currentTimeMillis());
                    if (getNode().getSession() != null && getNode().getSession().isLive() && getNode().getSession().hasPendingChanges()) {
                        //TODO check for autocommit setting
                        getNode().getSession().save();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //isWriting.notify();
                    synchronized (isWriting) {
                        isWriting = false;
                    }
                    //cleanup session out of thread
                    if (Thread.currentThread() instanceof ContextThread) {
                        ((ContextThread) Thread.currentThread()).setSession(null);
                    }
                }
            }
        };
        synchronized (hasPipeThreadStarted) {
            //System.err.println( "PipeWrite T="+Thread.currentThread()+" S="+session+" N="+absPath);
            ContextThread contextThread = new ContextThread(pipe, getNode().getName() + " pipeThread-" + System.currentTimeMillis());
            contextThread.setSession(getNode().getSession());
            contextThread.start();
            //Calendar lastModified = Calendar.getInstance();
            //lastModified.setTimeInMillis(file.lastModified());
            //resNode.setProperty("jcr:lastModified", lastModified);
            //Uti
            //System.out.println("waiting for pipe thread to start");
            hasPipeThreadStarted.wait(1500);
        }
        this.pipedOutputStream = pipedOutputStream;
        return pipedOutputStream;
    }
}
Example 46
Project: droolsjbpm-master  File: RulesRepository.java View source code
/**
     * Will add a node named 'nodeName' of type 'type' to 'parent' if such a
     * node does not already exist.
     *
     * @param parent
     *            the parent node to add the new node to
     * @param nodeName
     *            the name of the new node
     * @param type
     *            the type of the new node
     * @return a reference to the Node object that is created by the addition,
     *         or, if the node already existed, a reference to the pre-existant
     *         node.
     * @throws RulesRepositoryException
     */
protected static Node addNodeIfNew(Node parent, String nodeName, String type) throws RulesRepositoryException {
    Node node;
    try {
        node = parent.getNode(nodeName);
    } catch (PathNotFoundException e) {
        try {
            log.debug("Adding new node of type: {} named: {} to parent node named {}", new Object[] { type, nodeName, parent.getName() });
            node = parent.addNode(nodeName, type);
        } catch (Exception e1) {
            log.error("Caught Exception", e);
            throw new RulesRepositoryException(e1);
        }
    } catch (Exception e) {
        log.error("Caught Exception", e);
        throw new RulesRepositoryException(e);
    }
    return node;
}
Example 47
Project: ease-master  File: IndexTransfer.java View source code
@Override
public void run() {
    ResourceResolver resolver = null;
    IndexServer server = indexService.getServer();
    if (server == null) {
        if (LOG.isInfoEnabled()) {
            LOG.info("No index server available.");
        }
        return;
    }
    boolean modifiedIndex = false;
    try {
        resolver = indexService.getResolverFactory().getAdministrativeResourceResolver(null);
        VersionManager versionManager = resolver.adaptTo(Session.class).getWorkspace().getVersionManager();
        while (!this.terminated) {
            boolean modifiedQueue = false;
            modifiedIndex = false;
            Resource queueRes = resolver.getResource(IndexService.QUEUE_ROOT);
            if (queueRes != null) {
                Iterator<Resource> jobs = queueRes.listChildren();
                while (jobs.hasNext()) {
                    Resource jobRes = jobs.next();
                    try {
                        ValueMap jobData = jobRes.adaptTo(ValueMap.class);
                        String jobPath = jobData.get(IndexService.PN_PATH, String.class);
                        String jobAction = jobData.get(IndexService.PN_ACTION, String.class);
                        String jobRevision = jobData.get(IndexService.PN_REVISION, String.class);
                        if (IndexOperation.ADD.toString().equals(jobAction)) {
                            Resource targetRes = resolver.getResource(jobPath);
                            if (targetRes != null) {
                                // resolve any selected content version at this point
                                targetRes = VersioningUtil.resolveRevision(versionManager, targetRes, jobRevision);
                                if (targetRes != null) {
                                    // drill into jcr:content
                                    Resource contentRes = targetRes.getChild(JcrConstants.JCR_CONTENT);
                                    if (contentRes != null) {
                                        targetRes = contentRes;
                                    }
                                    if (indexService.getIndexer(targetRes) != null) {
                                        try {
                                            add(server, targetRes, jobPath);
                                            modifiedIndex = true;
                                            if (LOG.isDebugEnabled()) {
                                                LOG.debug("Indexed {} at node {}", jobPath, targetRes.getPath());
                                            }
                                        } catch (Exception e) {
                                            LOG.error("Error transferring item to index: " + jobPath, e);
                                        }
                                    } else {
                                        if (LOG.isDebugEnabled()) {
                                            LOG.debug("Ignoring {}", jobPath);
                                        }
                                    }
                                } else {
                                    LOG.warn("Ignoring due to failed revision resolution: {}", jobPath);
                                }
                            } else {
                                LOG.warn("Ignoring due to content not found: {}", jobPath);
                            }
                        } else if (IndexOperation.REMOVE.toString().equals(jobAction)) {
                            try {
                                server.remove(jobPath);
                            } catch (Exception e) {
                                LOG.error("Error removing item from index: " + jobPath, e);
                            }
                            modifiedIndex = true;
                        }
                        jobRes.adaptTo(Node.class).remove();
                        modifiedQueue = true;
                    } catch (Exception e) {
                        LOG.error("Error processing index job " + jobRes.getName(), e);
                    }
                }
                if (modifiedQueue) {
                    resolver.adaptTo(Session.class).save();
                }
                if (modifiedIndex) {
                    server.commit();
                }
            }
            // if no change to queue, wait until notification or timeout until next attempt
            if (!modifiedQueue) {
                try {
                    synchronized (this) {
                        this.wait(5000);
                    }
                } catch (InterruptedException e) {
                    if (!this.terminated) {
                        LOG.error("Interrupted transfer without termination flag.");
                        break;
                    }
                }
            }
        }
    } catch (LoginException e) {
        LOG.error("Error creating resource resolver.", e);
    } catch (RepositoryException e) {
        LOG.error("Error during repository access.", e);
        if (modifiedIndex) {
            try {
                server.rollback();
            } catch (Exception e1) {
                LOG.error("Error rolling back index changes.", e1);
            }
        }
    } catch (Exception e) {
        LOG.error("Error during queue processing.", e);
    } finally {
        if (resolver != null) {
            resolver.close();
        }
    }
}
Example 48
Project: exchange-extension-master  File: IntegrationService.java View source code
/**
   * 
   * @param eventId
   * @throws Exception
   */
public void updateOrCreateExchangeCalendarEvent(Node eventNode) throws Exception {
    CalendarEvent event = exoStorageService.getExoEventByNode(eventNode);
    if (isCalendarSynchronizedWithExchange(event.getCalendarId())) {
        List<CalendarEvent> calendarEventsToUpdateModifiedTime = new ArrayList<CalendarEvent>();
        updateOrCreateExchangeCalendarEvent(event, calendarEventsToUpdateModifiedTime);
        if (!calendarEventsToUpdateModifiedTime.isEmpty()) {
            for (CalendarEvent calendarEvent : calendarEventsToUpdateModifiedTime) {
                // This is done to not have a cyclic updates between eXo and Exchange
                exoStorageService.updateModifiedDateOfEvent(username, calendarEvent);
            }
        }
    }
}
Example 49
Project: fcrepo4-master  File: FedoraResourceImpl.java View source code
@Override
public void delete() {
    try {
        // Remove inbound references to this resource and, recursively, any of its children
        removeReferences(node);
        final Node parent = getNode().getDepth() > 0 ? getNode().getParent() : null;
        final String name = getNode().getName();
        // This is resolved immediately b/c we delete the node before updating an indirect container's target
        final boolean shouldUpdateIndirectResource = ldpInsertedContentProperty(node).flatMap(resourceToProperty(getSession())).filter(this::hasProperty).isPresent();
        final Optional<Node> containingNode = getContainingNode(getNode());
        node.remove();
        if (parent != null) {
            createTombstone(parent, name);
            // also update membershipResources for Direct/Indirect Containers
            containingNode.filter(UncheckedPredicate.uncheck((final Node ancestor) -> ancestor.hasProperty(LDP_MEMBER_RESOURCE) && (ancestor.isNodeType(LDP_DIRECT_CONTAINER) || shouldUpdateIndirectResource))).ifPresent( ancestor -> {
                try {
                    FedoraTypesUtils.touch(ancestor.getProperty(LDP_MEMBER_RESOURCE).getNode());
                } catch (final RepositoryException ex) {
                    throw new RepositoryRuntimeException(ex);
                }
            });
            // update the lastModified date on the parent node
            containingNode.ifPresent( ancestor -> {
                FedoraTypesUtils.touch(ancestor);
            });
        }
    } catch (final javax.jcr.AccessDeniedException e) {
        throw new AccessDeniedException(e);
    } catch (final RepositoryException e) {
        throw new RepositoryRuntimeException(e);
    }
}
Example 50
Project: jcr-springextension-master  File: JcrTemplateTest.java View source code
/*
     * Test method for 'org.springframework.extensions.jcr.JcrTemplate.dump(Node)'
     */
@Test
public void testDumpNode() throws RepositoryException {
    Node node = createNiceMock(Node.class);
    PropertyIterator iterator = createMock(PropertyIterator.class);
    NodeIterator iter = createMock(NodeIterator.class);
    expect(node.getPath()).andReturn("path");
    expect(node.getProperties()).andReturn(iterator);
    expect(iterator.hasNext()).andReturn(false);
    expect(node.getNodes()).andReturn(iter);
    expect(iter.hasNext()).andReturn(false);
    expect(session.getRootNode()).andReturn(node);
    replay(session);
    replay(sessionFactory);
    replay(node);
    jcrTemplate.dump(null);
    verify(node);
}
Example 51
Project: kylo-master  File: JcrUtil.java View source code
/**
     * Checks whether the given mixin node type is in effect for the given node.
     *
     * @param node      the node
     * @param mixinType the mixin node type
     * @return <code>true</code> when the mixin node type is present, <code>false</code> instead.
     */
public static boolean hasMixinType(Node node, String mixinType) throws RepositoryException {
    for (NodeType nodeType : node.getMixinNodeTypes()) {
        if (nodeType.getName().equals(mixinType)) {
            return true;
        }
    }
    NodeType[] types = node.getPrimaryNodeType().getSupertypes();
    if (types != null) {
        for (NodeType nt : types) {
            if (nt.getName().equals(mixinType)) {
                return true;
            }
        }
    }
    return false;
}
Example 52
Project: Magnolia-master  File: TemplatingFunctionsTest.java View source code
@Test
public void testChildrenFromNode() throws RepositoryException {
    // GIVEN
    String[] expectedNamesDepth1 = (String[]) ArrayUtils.addAll(DEPTH_2_COMPONENT_NAMES, DEPTH_2_PAGE_NAMES);
    // WHEN
    List<Node> resultChildNodes = functions.children(topPage);
    // THEN
    assertNodesListEqualStringDefinitions(expectedNamesDepth1, resultChildNodes);
}
Example 53
Project: magnolia-vanity-url-master  File: VanityUrlServiceTest.java View source code
@Before
public void setUp() throws Exception {
    ComponentsTestUtil.setInstance(I18nContentSupport.class, new DefaultI18nContentSupport());
    MockWebContext webContext = new MockWebContext();
    MockSession session = new MockSession(RepositoryConstants.WEBSITE);
    createNode(session, "/internal/forward/page").setIdentifier(TEST_UUID_FORWARD);
    createNode(session, "/internal/page").setIdentifier(TEST_UUID);
    webContext.addSession(RepositoryConstants.WEBSITE, session);
    MgnlContext.setInstance(webContext);
    _service = new VanityUrlService() {

        @Override
        protected String getLinkFromNode(final Node node) {
            String link = "";
            if (node != null) {
                try {
                    link = node.getPath() + ".html";
                } catch (RepositoryException e) {
                }
            }
            return link;
        }
    };
    VanityUrlModule vanityUrlModule = new VanityUrlModule();
    PublicUrlService publicUrlService = mock(PublicUrlService.class);
    when(publicUrlService.createTargetUrl((Node) any())).thenReturn("http://www.aperto.de/page.html");
    when(publicUrlService.createVanityUrl((Node) any())).thenReturn("http://www.aperto.de/vanity");
    vanityUrlModule.setPublicUrlService(publicUrlService);
    _service.setVanityUrlModule(vanityUrlModule);
}
Example 54
Project: manager.v3-master  File: JcrDocumentTest.java View source code
public final void testJcrDocumentFromMockRepo() throws RepositoryException {
    MockRepositoryEventList mrel = new MockRepositoryEventList("MockRepositoryEventLog3.txt");
    MockRepository r = new MockRepository(mrel);
    MockRepositoryDocument doc = r.getStore().getDocByID("doc1");
    Node node = new MockJcrNode(doc);
    Document document = new JcrDocument(node);
    countProperties(document);
}
Example 55
Project: modeshape-examples-master  File: CDIController.java View source code
/**
     * Loads the children nodes of the node located at {@link CDIController#parentPath}
     */
public void loadChildren() {
    children = new TreeSet<String>();
    if (parentPath == null || parentPath.trim().length() == 0) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("The absolute path of the parent node is required"));
    } else {
        try {
            Node parentNode = repositorySession.getNode(parentPath);
            for (NodeIterator nodeIterator = parentNode.getNodes(); nodeIterator.hasNext(); ) {
                children.add(nodeIterator.nextNode().getPath());
            }
        } catch (RepositoryException e) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(e.getMessage()));
        }
    }
}
Example 56
Project: modeshape-performance-master  File: ThreeWayJoinTestSuite.java View source code
@Override
public void beforeSuite() throws RepositoryException {
    session = newSession();
    root = session.getRootNode().addNode("testroot", "nt:unstructured");
    nodeCount = suiteConfiguration.getNodeCount();
    for (int i = 0; i < nodeCount; i++) {
        Node foo = root.addNode("node" + i, "nt:unstructured");
        foo.setProperty("foo", i);
        for (int j = 0; j < nodeCount; j++) {
            Node bar = foo.addNode("node" + j, "nt:unstructured");
            bar.setProperty("bar", j);
            for (int k = 0; k < nodeCount; k++) {
                Node baz = bar.addNode("node" + k, "nt:unstructured");
                baz.setProperty("baz", k);
            }
        }
        session.save();
    }
}
Example 57
Project: neba-master  File: ModelRegistryTest.java View source code
/**
     * Requires the {@link Node} to have been mocked before hand, e.g. usig {@link #withPrimaryType(Resource, String)}.
     */
private void withMixinTypes(Resource resource, String... mixins) throws RepositoryException {
    Node node = resource.adaptTo(Node.class);
    NodeType[] mixinTypes = new NodeType[mixins.length];
    for (int i = 0; i < mixins.length; ++i) {
        mixinTypes[i] = mock(NodeType.class);
        when(mixinTypes[i].getName()).thenReturn(mixins[i]);
    }
    when(node.getMixinNodeTypes()).thenReturn(mixinTypes);
}
Example 58
Project: omf-master  File: JcrPersistenceAdapter.java View source code
public CollectionResult getCollection(CollectionMapping collectionMapping) {
    try {
        final List<String> paths = new LinkedList<String>();
        final String location = collectionMapping.getLocation();
        if (node.hasNode(location)) {
            final Node collectionContainer = node.getNode(location);
            LOGGER.debug("Retrieving from node {}", collectionContainer.getPath());
            for (NodeIterator ni = collectionContainer.getNodes(); ni.hasNext(); ) {
                final Node child = ni.nextNode();
                // this should be configurable in some way.
                if (child.getName().equals("jcr:content"))
                    continue;
                LOGGER.trace("Adding {} to collection.", child.getPath());
                paths.add(child.getPath());
            }
        } else if (node.hasProperty(location) && node.getProperty(location).isMultiple()) {
            final Property property = node.getProperty(location);
            LOGGER.debug("Retrieving from property {}", property.getPath());
            for (Value v : property.getValues()) {
                paths.add(v.getString());
            }
        } else {
            return new MissingCollectionPersistenceResult();
        }
        return new ImmutableCollectionPersistenceResult(paths);
    } catch (RepositoryException e) {
        throw new ObjectMapperException("Could not retrieve collection from " + collectionMapping.getLocation());
    }
}
Example 59
Project: pentaho-platform-master  File: JcrRepositoryFileUtils.java View source code
public static RepositoryFile nodeToFileOld(final Session session, final PentahoJcrConstants pentahoJcrConstants, final IPathConversionHelper pathConversionHelper, final ILockHelper lockHelper, final Node node, final boolean loadMaps, IPentahoLocale pentahoLocale) throws RepositoryException {
    if (session.getRootNode().isSame(node)) {
        return getRootFolder(session);
    }
    Serializable id = null;
    String name = null;
    String path = null;
    long fileSize = 0;
    Date created = null;
    String creatorId = null;
    Boolean hidden = RepositoryFile.HIDDEN_BY_DEFAULT;
    Boolean schedulable = RepositoryFile.SCHEDULABLE_BY_DEFAULT;
    Date lastModified = null;
    boolean folder = false;
    boolean versioned = false;
    Serializable versionId = null;
    boolean locked = false;
    String lockOwner = null;
    Date lockDate = null;
    String lockMessage = null;
    String title = null;
    String description = null;
    Boolean aclNode = false;
    Map<String, Properties> localePropertiesMap = null;
    id = getNodeId(session, pentahoJcrConstants, node);
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("reading file with id '%s' and path '%s'", id, node.getPath()));
    }
    path = pathConversionHelper.absToRel((getAbsolutePath(session, pentahoJcrConstants, node)));
    name = RepositoryFile.SEPARATOR.equals(path) ? "" : getNodeName(session, pentahoJcrConstants, node);
    if (isPentahoFolder(pentahoJcrConstants, node)) {
        folder = true;
    }
    if (node.hasProperty(pentahoJcrConstants.getJCR_CREATED())) {
        Calendar tmpCal = node.getProperty(pentahoJcrConstants.getJCR_CREATED()).getDate();
        if (tmpCal != null) {
            created = tmpCal.getTime();
        }
    }
    Map<String, Serializable> metadata = getFileMetadata(session, id);
    if (metadata != null) {
        creatorId = (String) metadata.get(PentahoJcrConstants.PHO_CONTENTCREATOR);
        Serializable schedulableValue = metadata.get(RepositoryFile.SCHEDULABLE_KEY);
        if (schedulableValue instanceof String) {
            schedulable = BooleanUtils.toBoolean((String) schedulableValue);
        }
    }
    if (node.hasProperty(pentahoJcrConstants.getPHO_HIDDEN())) {
        hidden = node.getProperty(pentahoJcrConstants.getPHO_HIDDEN()).getBoolean();
    }
    if (node.hasProperty(pentahoJcrConstants.getPHO_FILESIZE())) {
        fileSize = node.getProperty(pentahoJcrConstants.getPHO_FILESIZE()).getLong();
    }
    if (node.hasProperty(pentahoJcrConstants.getPHO_ACLNODE())) {
        aclNode = node.getProperty(pentahoJcrConstants.getPHO_ACLNODE()).getBoolean();
    }
    if (isPentahoFile(pentahoJcrConstants, node)) {
        if (!node.isNodeType(pentahoJcrConstants.getNT_FROZENNODE())) {
            Calendar tmpCal = node.getProperty(pentahoJcrConstants.getPHO_LASTMODIFIED()).getDate();
            if (tmpCal != null) {
                lastModified = tmpCal.getTime();
            }
        }
    }
    // Get default locale if null
    if (pentahoLocale == null) {
        Locale currentLocale = LocaleHelper.getLocale();
        if (currentLocale != null) {
            pentahoLocale = new PentahoLocale(currentLocale);
        } else {
            pentahoLocale = new PentahoLocale();
        }
    }
    // Not needed for content generators and the like
    if (isPentahoHierarchyNode(session, pentahoJcrConstants, node)) {
        if (node.hasNode(pentahoJcrConstants.getPHO_LOCALES())) {
            // Expensive
            localePropertiesMap = getLocalePropertiesMap(session, pentahoJcrConstants, node.getNode(pentahoJcrConstants.getPHO_LOCALES()));
            // [BISERVER-8337] localize title and description
            LocalePropertyResolver lpr = new LocalePropertyResolver(name);
            LocalizationUtil localizationUtil = new LocalizationUtil(localePropertiesMap, pentahoLocale.getLocale());
            title = localizationUtil.resolveLocalizedString(lpr.resolveDefaultTitleKey(), null);
            if (org.apache.commons.lang.StringUtils.isBlank(title)) {
                title = localizationUtil.resolveLocalizedString(lpr.resolveTitleKey(), null);
                if (org.apache.commons.lang.StringUtils.isBlank(title)) {
                    title = localizationUtil.resolveLocalizedString(lpr.resolveNameKey(), title);
                }
            }
            description = localizationUtil.resolveLocalizedString(lpr.resolveDefaultDescriptionKey(), null);
            if (org.apache.commons.lang.StringUtils.isBlank(description)) {
                description = localizationUtil.resolveLocalizedString(lpr.resolveDescriptionKey(), description);
            }
        }
        // found
        if (title == null && node.hasNode(pentahoJcrConstants.getPHO_TITLE())) {
            title = getLocalizedString(session, pentahoJcrConstants, node.getNode(pentahoJcrConstants.getPHO_TITLE()), pentahoLocale);
        }
        if (description == null && node.hasNode(pentahoJcrConstants.getPHO_DESCRIPTION())) {
            description = getLocalizedString(session, pentahoJcrConstants, node.getNode(pentahoJcrConstants.getPHO_DESCRIPTION()), pentahoLocale);
        }
    }
    if (!loadMaps) {
        // remove reference, allow garbage collection
        localePropertiesMap = null;
    }
    versioned = isVersioned(session, pentahoJcrConstants, node);
    if (versioned) {
        versionId = getVersionId(session, pentahoJcrConstants, node);
    }
    locked = isLocked(pentahoJcrConstants, node);
    if (locked) {
        Lock lock = session.getWorkspace().getLockManager().getLock(node.getPath());
        lockOwner = lockHelper.getLockOwner(session, pentahoJcrConstants, lock);
        lockDate = lockHelper.getLockDate(session, pentahoJcrConstants, lock);
        lockMessage = lockHelper.getLockMessage(session, pentahoJcrConstants, lock);
    }
    RepositoryFile file = new RepositoryFile.Builder(id, name).createdDate(created).creatorId(creatorId).lastModificationDate(lastModified).folder(folder).versioned(versioned).path(path).versionId(versionId).fileSize(fileSize).locked(locked).lockDate(lockDate).hidden(hidden).schedulable(schedulable).lockMessage(lockMessage).lockOwner(lockOwner).title(title).description(description).locale(pentahoLocale.toString()).localePropertiesMap(localePropertiesMap).aclNode(aclNode).build();
    return file;
}
Example 60
Project: spring-insight-plugins-master  File: SimpleTests.java View source code
public void test() throws LoginException, RepositoryException {
    Session session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
    Assert.assertNotNull("Cannot login", session);
    try {
        Node root = session.getRootNode();
        Assert.assertNotNull("Cannot retrieve root node", root);
        // Store content
        Node hello = root.addNode("hello");
        Assert.assertNotNull("Cannot create node", hello);
        hello.setProperty("message", "Hello, World!");
        session.save();
        // Retrieve content
        Node node = root.getNode("hello");
        Assert.assertNotNull("Cannot retrieve node by path", node);
        Assert.assertEquals("Invalid node property", node.getProperty("message").getString(), "Hello, World!");
    } finally {
        session.logout();
    }
}
Example 61
Project: yarep-master  File: JCRNode.java View source code
/**
     * Indicates whether this node is of type "resource".
     * @return true if type is resource
     * @throws RepositoryException repository error
     * @see org.wyona.yarep.core.Node#isResource()
     */
public boolean isResource() throws RepositoryException {
    try {
        if (jcrNode.hasNode("jcr:content") && jcrNode.getNode("jcr:content").hasProperty("jcr:data")) {
            //if (jcrNode.hasProperty(BINARY_CONTENT_PROP_NAME)) {
            return true;
        } else {
            log.warn("Node '" + jcrNode.getPath() + "' does not seem to be of type RESOURCE");
            return false;
        }
    } catch (Exception e) {
        throw new RepositoryException(e.getMessage(), e);
    }
}
Example 62
Project: acs-aem-tools-master  File: CsvAssetImporterServlet.java View source code
/**
     * Updates the Metadata Properties of the Asset.
     *
     * @param columns          the Columns of the CSV
     * @param row              the row data
     * @param ignoreProperties Properties which to ignore when persisting property values to the Asset
     * @param asset            the Asset to persist the data to
     */
private void updateProperties(final Map<String, Column> columns, final String[] row, final String[] ignoreProperties, final Asset asset) throws RepositoryException, CsvAssetImportException {
    // Copy properties
    for (final Map.Entry<String, Column> entry : columns.entrySet()) {
        if (ArrayUtils.contains(ignoreProperties, entry.getKey())) {
            continue;
        }
        if (StringUtils.isBlank(entry.getKey())) {
            log.warn("Found a blank property name for: {}", Arrays.asList(entry.getValue()));
            continue;
        }
        final Column column = entry.getValue();
        final String valueStr = row[column.getIndex()];
        final Node metaProps = this.getMetadataProperties(asset, column.getRelPropertyPath());
        final String propName = column.getPropertyName();
        if (StringUtils.isNotBlank(valueStr)) {
            if (metaProps.hasProperty(propName)) {
                Property prop = metaProps.getProperty(propName);
                if ((prop.getType() != column.getJcrPropertyType()) || (column.isMulti() && !prop.isMultiple()) || (!column.isMulti() && prop.isMultiple())) {
                    prop.remove();
                }
            }
            if (column.isMulti()) {
                Object val = column.getMultiData(valueStr);
                JcrUtil.setProperty(metaProps, propName, val);
                log.debug("Setting multi property [ {} ~> {} ]", column.getRelPropertyPath(), Arrays.asList(column.getMultiData(valueStr)));
            } else {
                Object val = column.getData(valueStr);
                JcrUtil.setProperty(metaProps, propName, val);
                log.debug("Setting property [ {} ~> {} ]", column.getRelPropertyPath(), column.getData(valueStr));
            }
        } else {
            if (metaProps.hasProperty(propName)) {
                metaProps.getProperty(propName).remove();
                log.debug("Removing property [ {} ]", column.getRelPropertyPath());
            }
        }
    }
}
Example 63
Project: gatein-wsrp-master  File: JCRConsumerRegistryTestCase.java View source code
@Override
protected void tearDown() throws Exception {
    // remove node containing consumer informations so that we can start with a clean state
    final ChromatticPersister persister = ((JCRConsumerRegistry) registry).getPersister();
    final Session session = persister.getSession().getJCRSession();
    final Node rootNode = session.getRootNode();
    final NodeIterator nodes = rootNode.getNodes();
    while (nodes.hasNext()) {
        nodes.nextNode().remove();
    }
    // then save
    persister.closeSession(true);
}
Example 64
Project: HippoCocoonToolkit-master  File: HippoItemXMLDumper.java View source code
public void dumpHippoItem(final HCTConnManager connManager, final HippoItem item, final String itemPath, final HCTQuery hctQuery, final Locale locale) throws SAXException, RepositoryException, IOException, ObjectBeanManagerException {
    final XMLReader xmlReader = new StartEndDocumentFilter(XMLUtils.createXMLReader(saxConsumer));
    xmlReader.setContentHandler(saxConsumer);
    startHippoItem(item, itemPath);
    for (final String fieldName : hctQuery.getReturnFields()) {
        Object fieldValue = null;
        if (fieldName.contains("/")) {
            final String[] splitted = fieldName.split("/");
            final List<HippoCompoundDocument> compounds = item.getChildBeansByName(splitted[0], HippoCompoundDocument.class);
            if (!compounds.isEmpty()) {
                fieldValue = compounds.iterator().next().getProperty(splitted[1]);
            }
        } else {
            fieldValue = item.getProperty(fieldName);
        }
        if (fieldValue == null) {
            final List<HippoHtml> rtfs = item.getChildBeansByName(fieldName, HippoHtml.class);
            final List<HippoDate> dates = item.getChildBeansByName(fieldName, HippoDate.class);
            if (rtfs != null && !rtfs.isEmpty()) {
                for (HippoHtml rtf : rtfs) {
                    dumpHtml(connManager, rtf, xmlReader, hctQuery.getDateFormat(), locale);
                }
            }
            if (dates != null && !dates.isEmpty()) {
                for (HippoDate date : dates) {
                    dumpDate(fieldName, date.getCalendar(), hctQuery.getDateFormat(), locale);
                }
            }
        } else {
            dumpField(new SimpleEntry<String, Object>(fieldName, fieldValue), hctQuery.getDateFormat(), locale);
        }
    }
    if (hctQuery.isReturnTags()) {
        dumpTags((String[]) item.getProperty(TaggingNodeType.PROP_TAGS));
    }
    if (hctQuery.isReturnTaxonomies()) {
        dumpTaxonomies(TaxonomyUtils.getTaxonomies(connManager, (String[]) item.getProperty(TaxonomyNodeTypes.HIPPOTAXONOMY_KEYS)), locale);
    }
    if (hctQuery.isReturnImages()) {
        final List<HippoGalleryImageSet> images = new ArrayList<HippoGalleryImageSet>();
        for (ImageLinkBean imgLink : item.getChildBeans(ImageLinkBean.class)) {
            Node imgLinkNode = null;
            try {
                imgLinkNode = connManager.getSession().getNodeByIdentifier(imgLink.getImageSetUuid());
            } catch (RepositoryException e) {
            }
            if (imgLinkNode != null) {
                final HippoItem imgLinkItem = ObjectUtils.getHippoItem(connManager, imgLinkNode);
                if (imgLinkItem instanceof HippoGalleryImageSet) {
                    images.add((HippoGalleryImageSet) imgLinkItem);
                }
            }
        }
        dumpImages(images, Element.IMAGE.getName(), true);
    }
    if (hctQuery.isReturnRelatedDocs()) {
        final List<HippoDocument> relDocs = new ArrayList<HippoDocument>();
        for (RelatedDocs docs : item.getChildBeans(RelatedDocs.class)) {
            for (String relDocUuid : docs.getRelatedDocsUuids()) {
                final HippoDocument doc = ObjectUtils.getHippoItemByUuid(connManager, relDocUuid, HippoDocument.class);
                if (doc != null) {
                    relDocs.add(doc);
                }
            }
        }
        dumpRelatedDocs(relDocs, Element.DOCUMENT.getName(), true);
    }
    endHippoItem(item);
}
Example 65
Project: MadStore-master  File: JcrEntryRepository.java View source code
public Object doInJcr(final Session session) throws IOException, RepositoryException {
    String entryKey = entryElement.getAttribute(AtomConstants.ATOM_KEY);
    if (!contains(collectionKey, entryKey)) {
        Node collection = getCollectionNode(collectionKey, session);
        if (collection != null) {
            importNodeFromDomEntry(collectionKey, entryKey, entryElement, session);
            indexManager.index(collectionKey, entryKey, entryElement);
            session.save();
            return entryKey;
        }
    }
    return null;
}
Example 66
Project: NabaztagServer-master  File: JcrRosterManager.java View source code
@Override
protected Roster retrieveRosterInternal(Entity bareJid) {
    final Node rosterNode = retrieveRosterNode(jcrStorage, bareJid);
    MutableRoster roster = new MutableRoster();
    NodeIterator nodes = null;
    try {
        nodes = rosterNode.getNodes();
    } catch (RepositoryException e) {
        return roster;
    }
    while (nodes != null && nodes.hasNext()) {
        Node node = nodes.nextNode();
        String contactJidString = null;
        try {
            contactJidString = node.getName();
        } catch (RepositoryException e) {
            logger.warn("when loading roster for user {} cannot read node name for node id = " + node.toString());
        }
        logger.warn("try now loading contact " + contactJidString + " from node " + node.toString());
        EntityImpl contactJid = null;
        if (contactJidString != null) {
            try {
                contactJid = EntityImpl.parse(contactJidString);
            } catch (EntityFormatException e) {
                logger.warn("when loading roster for user {} parsing  contact jid {}", bareJid, contactJidString);
            }
        }
        if (contactJid == null) {
            logger.warn("when loading roster for user {}, skipping a contact due to missing or unparsable jid", bareJid);
            continue;
        }
        String name = readAttribute(node, "name");
        String typeString = readAttribute(node, "type");
        SubscriptionType subscriptionType = null;
        try {
            subscriptionType = SubscriptionType.valueOf(typeString == null ? "NONE" : typeString.toUpperCase());
        } catch (IllegalArgumentException e) {
            logger.warn("when loading roster for user " + bareJid + ", contact " + contactJid + " misses a subscription type", bareJid, contactJid);
        }
        String askTypeString = readAttribute(node, "askType");
        AskSubscriptionType askSubscriptionType = AskSubscriptionType.NOT_SET;
        try {
            if (askTypeString != null)
                askSubscriptionType = AskSubscriptionType.valueOf(askTypeString);
        } catch (IllegalArgumentException e) {
            logger.warn("when loading roster for user " + bareJid.getFullQualifiedName() + ", contact " + contactJid.getFullQualifiedName() + ", the ask subscription type is unparsable. skipping!");
            continue;
        }
        List<RosterGroup> groups = new ArrayList<RosterGroup>();
        // TODO read groups
        RosterItem item = new RosterItem(contactJid, name, subscriptionType, askSubscriptionType, groups);
        logger.info("item loaded for " + bareJid.getFullQualifiedName() + ": " + item.toString());
        roster.addItem(item);
    }
    return roster;
}
Example 67
Project: aorra-master  File: FileStoreHelper.java View source code
private void listAdminTree(Authorizable authorizable, int depth) throws RepositoryException {
    boolean isGroup = authorizable instanceof Group;
    String id = authorizable.getID();
    String email = "";
    try {
        // Get user email if user
        Node node = session.getNodeByIdentifier(id);
        email = node.getProperty("email").getValue().getString();
    } catch (Exception e) {
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < depth - 1; i++) {
        sb.append("|   ");
    }
    if (isGroup) {
        sb.append("|-+ ");
        sb.append(id);
    } else {
        sb.append("|-- ");
        if (StringUtils.isNotBlank(email)) {
            sb.append(email);
        } else {
            sb.append(id);
        }
    }
    out.println(sb);
    if (isGroup) {
        Iterator<Authorizable> aIter = ((Group) authorizable).getDeclaredMembers();
        while (aIter.hasNext()) {
            Authorizable a = aIter.next();
            listAdminTree(a, depth + 1);
        }
    }
}
Example 68
Project: archiva-master  File: JcrMetadataRepository.java View source code
@Override
public void updateArtifact(String repositoryId, String namespace, String projectId, String projectVersion, ArtifactMetadata artifactMeta) throws MetadataRepositoryException {
    updateNamespace(repositoryId, namespace);
    try {
        Node node = getOrAddArtifactNode(repositoryId, namespace, projectId, projectVersion, artifactMeta.getId());
        Calendar cal = Calendar.getInstance();
        cal.setTime(artifactMeta.getFileLastModified());
        node.setProperty(JCR_LAST_MODIFIED, cal);
        cal = Calendar.getInstance();
        cal.setTime(artifactMeta.getWhenGathered());
        node.setProperty("whenGathered", cal);
        node.setProperty("size", artifactMeta.getSize());
        node.setProperty("md5", artifactMeta.getMd5());
        node.setProperty("sha1", artifactMeta.getSha1());
        node.setProperty("version", artifactMeta.getVersion());
        // iterate over available facets to update/add/remove from the artifactMetadata
        for (String facetId : metadataFacetFactories.keySet()) {
            MetadataFacet metadataFacet = artifactMeta.getFacet(facetId);
            if (metadataFacet == null) {
                continue;
            }
            if (node.hasNode(facetId)) {
                node.getNode(facetId).remove();
            }
            if (metadataFacet != null) {
                // recreate, to ensure properties are removed
                Node n = node.addNode(facetId);
                n.addMixin(FACET_NODE_TYPE);
                for (Map.Entry<String, String> entry : metadataFacet.toProperties().entrySet()) {
                    n.setProperty(entry.getKey(), entry.getValue());
                }
            }
        }
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException(e.getMessage(), e);
    }
}
Example 69
Project: chrysalix-master  File: ModelspaceImpl.java View source code
/**
             * {@inheritDoc}
             * 
             * @see org.modelspace.internal.task.WriteTaskWithResult#run(javax.jcr.Session)
             */
@Override
public Boolean run(final Session session) throws Exception {
    final String absPath = absolutePath(path);
    if (session.nodeExists(absPath)) {
        final Node node = session.getNode(absPath);
        if (!node.isNodeType(ModelspaceLexicon.Model.MODEL_MIXIN)) {
            throw new IllegalArgumentException(ModelspaceI18n.localize(NOT_MODEL_PATH, absPath));
        }
        return true;
    }
    return false;
}
Example 70
Project: com.activecq.samples-master  File: ReverseReplicatorImpl.java View source code
private void setLastModified(final Resource resource) {
    try {
        Calendar now = Calendar.getInstance();
        Node node = resource.adaptTo(Node.class);
        node.setProperty(JcrConstants.JCR_LASTMODIFIED, now);
        node.setProperty(JcrConstants.JCR_LAST_MODIFIED_BY, resource.getResourceResolver().getUserID());
        node.getSession().save();
    } catch (ValueFormatException ex) {
        java.util.logging.Logger.getLogger(ReverseReplicatorImpl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (VersionException ex) {
        java.util.logging.Logger.getLogger(ReverseReplicatorImpl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (LockException ex) {
        java.util.logging.Logger.getLogger(ReverseReplicatorImpl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ConstraintViolationException ex) {
        java.util.logging.Logger.getLogger(ReverseReplicatorImpl.class.getName()).log(Level.SEVERE, null, ex);
    } catch (RepositoryException ex) {
        java.util.logging.Logger.getLogger(ReverseReplicatorImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Example 71
Project: com.idega.block.article-master  File: ArticleLocalizedItemBean.java View source code
protected void storeToJCR(InputStream stream, String filePath, String article) throws RepositoryException, IOException {
    //IWContext iwc = CoreUtil.getIWContext();
    Session session = getSession();
    //WebdavRootResource rootResource = session.getWebdavRootResource();
    RepositoryHelper helper = getRepositoryHelper();
    Node fileNode = null;
    //boolean success = false;
    try {
        stream = StringHandler.getStreamFromString(article);
        //Conflict fix: uri for creating but path for updating
        //Note! This is a patch to what seems to be a bug in WebDav
        //Apparently in verion below works in some cases and the other in other cases.
        //Seems to be connected to creating files in folders created in same tomcat session or similar
        //not quite clear...
        fileNode = helper.updateFileContents(session, filePath, stream);
        fileNode.setProperty(ArticleItemBean.CONTENT_TYPE_WITH_PREFIX, CoreConstants.ARTICLE_FILENAME_SCOPE);
        //rootResource.close();
        if (fileNode != null) {
            fileNode.save();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        closeInputStream(stream);
    }
/*if (success) {
			rootResource.proppatchMethod(filePath, ArticleItemBean.PROPERTY_CONTENT_TYPE,CoreConstants.ARTICLE_FILENAME_SCOPE,true);
		}
		else {
			try {
				stream = StringHandler.getStreamFromString(article);
				String fixedURL = session.getURI(filePath);
				rootResource.putMethod(fixedURL, stream);
				rootResource.proppatchMethod(fixedURL, ArticleItemBean.PROPERTY_CONTENT_TYPE,CoreConstants.ARTICLE_FILENAME_SCOPE,true);
			} catch(Exception e) {
				e.printStackTrace();
			} finally {
				closeInputStream(stream);
			}
		}*/
}
Example 72
Project: com.idega.content-master  File: ContentItemBean.java View source code
protected boolean loadFromJCR(String path) throws IOException, RemoteException, HttpException {
    //IWContext iwc = IWContext.getInstance();
    boolean returner = true;
    try {
        //IWSlideSession session = getIWSlideSession(iwuc);
        Session session = getSession();
        Node folderNode = session.getRootNode().getNode(path);
        //WebdavExtendedResource webdavResource = session.getWebdavResource(path);
        //webdavResource.setProperties();
        //here I don't use the varible 'path' since it can actually be the URI
        setResourcePath(folderNode.getPath());
        Property displayNameProp = folderNode.getProperty(DISPLAYNAME);
        if (displayNameProp != null) {
            setName(displayNameProp.getValue().getString());
        }
        //String versionName = webdavResource.getVersionName();
        /*List versions = VersionHelper.getAllVersions(webdavResource);
			if(versions!=null){
				setVersions(versions);
				String latestVersion = VersionHelper.getLatestVersionName(versions);
				setVersionName(latestVersion);
			}*/
        Property createDateProp = folderNode.getProperty(CREATIONDATE);
        if (createDateProp != null) {
            try {
                Calendar creationDate = createDateProp.getDate();
                //String sCreateDate = createDateProp.getValue().getString();
                setCreationDate(new IWTimestamp((GregorianCalendar) creationDate).getTimestamp());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Property lastmodifiedProp = folderNode.getProperty(GETLASTMODIFIED);
        if (lastmodifiedProp != null) {
            //long lLastmodified = Long.parseLong(lastmodifiedProp.getValue().getString());
            try {
                //long lLastmodified = lastmodifiedProp.getValue().getLong();
                //IWTimestamp lastModified = new IWTimestamp(lLastmodified);
                //setLastModifiedDate(lastModified.getTimestamp());
                Calendar creationDate = lastmodifiedProp.getDate();
                //String sCreateDate = createDateProp.getValue().getString();
                setLastModifiedDate(new IWTimestamp((GregorianCalendar) creationDate).getTimestamp());
            } catch (ValueFormatException vfe) {
                vfe.printStackTrace();
            }
        }
        try {
            Property categoriesProp = folderNode.getProperty(IWSlideConstants.PROPERTYNAME_CATEGORY);
            if (categoriesProp != null) {
                String categories = categoriesProp.getValue().getString();
                setCategories(categories);
            }
        } catch (PathNotFoundException pnfe) {
        }
        returner = load(folderNode);
        setExists(true);
    //	System.out.print("["+this.toString()+"]:");
    //	System.out.println("Load "+((returner)?"":"not")+" successful of path "+path);
    } catch (PathNotFoundException e) {
        setRendered(false);
        return false;
    } catch (RepositoryException e) {
        e.printStackTrace();
        setRendered(false);
        return false;
    }
    return returner;
}
Example 73
Project: com.idega.core-master  File: RepositoryHelper.java View source code
public Node updateFileContents(Session session, String absolutePath, InputStream fileContents, boolean createFile) throws RepositoryException {
    Node fileNode = null;
    try {
        fileNode = getFile(session, absolutePath);
    } catch (PathNotFoundException pfe) {
        if (createFile) {
            fileNode = createFile(session, absolutePath);
        } else {
            throw pfe;
        }
    }
    Node contentNode = fileNode.getNode(NODE_CONTENT);
    contentNode.getProperty(PROPERTY_BINARY_DATA).setValue(fileContents);
    return fileNode;
}
Example 74
Project: docx4j-master  File: SaveToJCR.java View source code
/* Save a Package to baseNode in JCR.
	 * baseNode must exist an be a suitable node type.             
	 * eg Node exampledoc1 = docs.addNode("exampledoc1.docx", "nt:file");            
          Node baseNode = exampledoc1.addNode("jcr:content", "nt:unstructured");
       Consider passing instead the folder node and desired filename.
	 *  */
public boolean save(Node baseNode) throws Docx4JException {
    try {
        log.info("Saving to" + baseNode.getPath());
        //	        // Create the ZIP file
        //	        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(filepath));
        // 3. Get [Content_Types].xml
        ContentTypeManager ctm = p.getContentTypeManager();
        org.w3c.dom.Document w3cDoc = XmlUtils.getNewDocumentBuilder().newDocument();
        ctm.marshal(w3cDoc);
        saveRawXmlPart(jcrSession, baseNode, "[Content_Types].xml", w3cDoc);
        // 4. Start with _rels/.rels
        //			<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
        //			  <Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>
        //			  <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
        //			  <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
        //			</Relationships>		
        String partName = "_rels/.rels";
        RelationshipsPart rp = p.getRelationshipsPart();
        // TODO - replace with saveRawXmlPart(baseNode, rp)
        // once we know that partName resolves correctly
        //			saveRawXmlPart(baseNode, partName, rp.getW3cDocument() );
        saveRawXmlPart(baseNode, rp);
        // 5. Now recursively 
        //			addPartsFromRelationships(baseNode, "", rp );
        addPartsFromRelationships(baseNode, rp);
        jcrSession.save();
    } catch (Exception e) {
        e.printStackTrace();
        if (e instanceof Docx4JException) {
            throw (Docx4JException) e;
        } else {
            throw new Docx4JException("Failed to save package", e);
        }
    }
    log.info("...Done!");
    return true;
}
Example 75
Project: jbpm3-seam-master  File: JcrNodeInstance.java View source code
protected void setObject(Object value) {
    Node node = (Node) value;
    if (value == null) {
        repository = null;
        workspace = null;
        path = null;
    } else {
        try {
            // repository and workspace have to correspond with a service name,
            // as described in findService, unless there is a global "jcr" service
            Session session = node.getSession();
            repository = session.getRepository().getDescriptor(Repository.REP_NAME_DESC);
            workspace = session.getWorkspace().getName();
            path = node.getPath();
            if (log.isDebugEnabled()) {
                log.debug("stored jcr node, repository '" + repository + "', workspace '" + workspace + "' and path'" + path + '\'');
            }
        } catch (RepositoryException e) {
            throw new JbpmException("problem storing JCR node '" + node + "' in the process variable '" + name + "'", e);
        }
    }
}
Example 76
Project: Leabharlann-master  File: FileContentMessageConverter.java View source code
@Override
public Object doInSessionWithNode(Session session, Node node) throws Exception {
    final Node resourceNode = node.getNode(Node.JCR_CONTENT);
    final String mimeType = jcrAccessor.getStringProperty(resourceNode, Property.JCR_MIMETYPE);
    final Calendar lastModified = jcrAccessor.getCalendarProperty(resourceNode, Property.JCR_LAST_MODIFIED);
    final Binary data = jcrAccessor.getBinaryProperty(resourceNode, Property.JCR_DATA);
    if (jcrAccessor.hasProperty(resourceNode, Property.JCR_ENCODING)) {
        final String encoding = jcrAccessor.getStringProperty(resourceNode, Property.JCR_ENCODING);
        outputMessage.getHeaders().setContentType(new MediaType(MediaType.valueOf(mimeType), Collections.singletonMap("charset", encoding)));
    } else {
        outputMessage.getHeaders().setContentType(MediaType.valueOf(mimeType));
    }
    outputMessage.getHeaders().setContentLength(data.getSize());
    if (lastModified != null) {
        outputMessage.getHeaders().setLastModified(lastModified.getTimeInMillis());
    }
    outputMessage.getHeaders().set("Content-Disposition", "attachment;filename=" + node.getName());
    IOUtils.copy(data.getStream(), outputMessage.getBody());
    return null;
}
Example 77
Project: puglieseweb.com-master  File: AbstractSingleFlowController.java View source code
/**
     * Allows for rewriting url prior to redirection.
     *
     * Implements support for redirecting to the currently rendered page using a placeholder. I.e:
     * <code>
     * view="externalRedirect:magnolia-redirect:main-content"
     * </code>
     *
     * @param url the url Spring WebFlow intends to redirect to
     * @return the rewritten url or if no change was made returns the passed in url unchanged
     */
protected String rewriteRedirectUrl(String url) throws IOException {
    try {
        if (url.equals("/" + UuidRedirectViewResolver.REDIRECT_MAIN_CONTENT_PLACEHOLDER)) {
            Node node = MgnlContext.getAggregationState().getMainContentNode();
            String workspaceName = node.getSession().getWorkspace().getName();
            String identifier = node.getIdentifier();
            url = LinkUtil.convertUUIDtoURI(identifier, workspaceName);
        }
        return url;
    } catch (RepositoryException e) {
        throw new IOException("Could not convert placeholder to link", e);
    } catch (LinkException e) {
        throw new IOException("Could not convert placeholder to link", e);
    }
}
Example 78
Project: tesb-rt-se-master  File: PersistencyJCRManager.java View source code
@Override
public void storeObject(String context, String key) throws PersistencyException {
    Session session = null;
    Node rootNode;
    Node node;
    synchronized (this) {
        try {
            session = getSession();
            rootNode = session.getRootNode();
            if (rootNode.hasNode(key)) {
                throw new ObjectAlreadyExistsException("Dublicated object with key {" + key + "}");
            }
            node = rootNode.addNode(key);
            node.setProperty(CONTEXT_DATA_PROPERTY_NAME, context);
            session.save();
        } catch (RepositoryException e) {
            LOG.log(Level.SEVERE, "Failed to sotre object. RepositoryException. Error message: " + e.getMessage());
            throw new PersistencyException("Saving object failed due to error " + e.getMessage());
        } finally {
            releaseSession(session);
        }
    }
}
Example 79
Project: wcm-io-wcm-master  File: TemplateFilterPageTreeProviderTest.java View source code
private void mockQueryResult(String... paths) {
    List<String> resultPaths = ImmutableList.copyOf(paths);
    List<Node> resultNodes = Lists.transform(resultPaths, new Function<String, Node>() {

        @Override
        public Node apply(String path) {
            return context.resourceResolver().getResource(path).adaptTo(Node.class);
        }
    });
    MockJcr.setQueryResult(context.resourceResolver().adaptTo(Session.class), resultNodes);
}
Example 80
Project: org.liveSense.misc.i18n-master  File: I18nLoader.java View source code
/**
	 * Creates or gets the {@link javax.jcr.Node Node} at the given Path.
	 *
	 * @param session The session to use for node creation
	 * @param absolutePath absolute node path
	 * @param nodeType to use for creation of the final node
	 * @return the Node at path
	 * @throws RepositoryException in case of exception accessing the Repository
	 */
private Node createPath(final Session session, final String absolutePath, final String nodeType) throws RepositoryException {
    final Node parentNode = session.getRootNode();
    String relativePath = absolutePath.substring(1);
    if (!parentNode.hasNode(relativePath)) {
        Node node = parentNode;
        int pos = relativePath.lastIndexOf('/');
        if (pos != -1) {
            final StringTokenizer st = new StringTokenizer(relativePath.substring(0, pos), "/");
            while (st.hasMoreTokens()) {
                final String token = st.nextToken();
                if (!node.hasNode(token)) {
                    try {
                        node.addNode(token, FOLDER_NODE_TYPE);
                    } catch (RepositoryException re) {
                        node.refresh(false);
                    }
                }
                node = node.getNode(token);
            }
            relativePath = relativePath.substring(pos + 1);
        }
        if (!node.hasNode(relativePath)) {
            node.addNode(relativePath, nodeType);
        }
        return node.getNode(relativePath);
    }
    return parentNode.getNode(relativePath);
}
Example 81
Project: Adobe-CQ5-Brightcove-Connector-master  File: BrcApi.java View source code
public void api(final SlingHttpServletRequest request, final SlingHttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/json;charset=UTF-8");
    PrintWriter outWriter = response.getWriter();
    int requestedAPI = 0;
    String requestedAccount = "";
    if (request.getParameter("a") != null && request.getParameter("account_id") != null && !request.getParameter("account_id").trim().isEmpty()) {
        response.setContentType("application/json");
        requestedAccount = request.getParameter("account_id");
        ConfigurationGrabber cg = ServiceUtil.getConfigurationGrabber();
        ConfigurationService cs = cg.getConfigurationService(requestedAccount);
        ServiceUtil serviceUtil = new ServiceUtil(requestedAccount);
        boolean is_authorized = false;
        Session session = request.getResourceResolver().adaptTo(Session.class);
        UserManager userManager = request.getResourceResolver().adaptTo(UserManager.class);
        /* to get the current user */
        try {
            Authorizable auth = userManager.getAuthorizable(session.getUserID());
            if (auth != null) {
                List<String> allowedGroups = cs.getAllowedGroupsList();
                Iterator<Group> groups = auth.memberOf();
                while (groups.hasNext() && !is_authorized) {
                    Group group = groups.next();
                    if (allowedGroups.contains(group.getID()))
                        is_authorized = true;
                }
            }
        } catch (RepositoryException re) {
        }
        if (is_authorized) {
            requestedAPI = Integer.parseInt(request.getParameter("a"));
            switch(requestedAPI) {
                case //no commands
                0:
                    outWriter.write("Test");
                    break;
                case 1:
                    JSONObject players = null;
                    String type = request.getParameter("players_type");
                    if ("legacy".equals(type)) {
                        players = new JSONObject();
                        try {
                            JSONArray playesArray = new JSONArray();
                            String playersPath = cs.getPlayersLoc();
                            Resource res = request.getResourceResolver().resolve(playersPath);
                            Iterator<Resource> playersItr = res.listChildren();
                            while (playersItr.hasNext()) {
                                Resource playerRes = playersItr.next().getChild("jcr:content");
                                if (playerRes != null) {
                                    Node playerNode = playerRes.adaptTo(Node.class);
                                    if (playerRes != null && "brightcove/components/page/brightcoveplayer".equals(playerRes.getResourceType())) {
                                        try {
                                            org.apache.sling.commons.json.JSONObject item = new JSONObject();
                                            String path = playerRes.getPath();
                                            String title = playerNode.hasProperty("jcr:title") ? playerNode.getProperty("jcr:title").getString() : playerNode.getName();
                                            String account = playerNode.hasProperty("account") ? playerNode.getProperty("account").getString() : playerNode.getName();
                                            if (!account.trim().isEmpty() && account.equals(requestedAccount)) {
                                                item.put("id", path);
                                                item.put("name", title);
                                                playesArray.put(item);
                                            }
                                        } catch (Exception e) {
                                        }
                                    }
                                }
                            }
                            players.put("items", playesArray);
                            players.put("item_count", playesArray.length());
                        } catch (JSONException e) {
                        }
                    } else {
                        players = serviceUtil.getPlayers();
                    }
                    outWriter.write(players.toString());
                    break;
                case 2:
                    LOGGER.debug("query: " + request.getParameter("query"));
                    if (request.getParameter("query") != null && !request.getParameter("query").trim().isEmpty()) {
                        int start = 0;
                        try {
                            start = Integer.parseInt(request.getParameter("start"));
                        } catch (NumberFormatException e) {
                            LOGGER.error("NumberFormatException", e);
                        }
                        int limit = serviceUtil.DEFAULT_LIMIT;
                        try {
                            limit = Integer.parseInt(request.getParameter("limit"));
                        } catch (NumberFormatException e) {
                            LOGGER.error("NumberFormatException", e);
                        }
                        outWriter.write(serviceUtil.getList(false, start, limit, false, request.getParameter("query")));
                    } else {
                        LOGGER.debug("getListSideMenu");
                        outWriter.write(serviceUtil.getListSideMenu(request.getParameter("limit")));
                    }
                    break;
                case 3:
                    response.setHeader("Content-type", "application/xls");
                    response.setHeader("Content-disposition", "inline; filename=Brightcove_Library_Export.csv");
                    outWriter.write(serviceUtil.getList(true, Integer.parseInt(request.getParameter("start")), Integer.parseInt(request.getParameter("limit")), true, request.getParameter("query")));
                    break;
                case 4:
                    if (request.getParameter("query") != null && !request.getParameter("query").trim().isEmpty()) {
                        outWriter.write(serviceUtil.getPlaylistByID(request.getParameter("query")).toString());
                    } else {
                        outWriter.write(serviceUtil.getListPlaylistsSideMenu(request.getParameter("limit")));
                    }
                    break;
                case 5:
                    LOGGER.debug("query: " + request.getParameter("query"));
                    if ("true".equals(request.getParameter("isID"))) {
                        LOGGER.debug("isID");
                        JSONObject items = new JSONObject();
                        JSONArray videos = new JSONArray();
                        try {
                            JSONObject video = serviceUtil.getSelectedVideo(request.getParameter("query"));
                            long totalItems = 0;
                            if (video.has("id")) {
                                totalItems = 1;
                                videos.put(video);
                            }
                            items.put("items", (JSONArray) videos);
                            items.put("totals", totalItems);
                            outWriter.write(items.toString(1));
                        } catch (JSONException je) {
                            outWriter.write("{\"items\":[],\"totals\":0}");
                        }
                    } else {
                        LOGGER.debug("NOT isID");
                        outWriter.write(serviceUtil.searchVideo(request.getParameter("query"), Integer.parseInt(request.getParameter("start")), Integer.parseInt(request.getParameter("limit"))));
                    }
                    break;
                case 6:
                    if ("true".equals(request.getParameter("isID"))) {
                        JSONObject items = new JSONObject();
                        JSONArray playlists = new JSONArray();
                        try {
                            JSONObject playlist = serviceUtil.getPlaylistByID(request.getParameter("query"));
                            long totalItems = 0;
                            if (playlist.has("id")) {
                                totalItems = 1;
                                playlists.put(playlist);
                            }
                            items.put("items", (JSONArray) playlists);
                            items.put("totals", totalItems);
                            outWriter.write(items.toString(1));
                        } catch (JSONException je) {
                            outWriter.write("{\"items\":[],\"totals\":0}");
                        }
                    } else {
                        outWriter.write(serviceUtil.getPlaylists(Integer.parseInt(request.getParameter("start")), Integer.parseInt(request.getParameter("limit")), false, false));
                    }
                    break;
                default:
                    break;
            }
        } else {
            outWriter.write("{\"items\":[],\"totals\":0}");
        }
    } else {
        outWriter.write("{\"items\":[],\"totals\":0}");
    }
}
Example 82
Project: bi-platform-v2-master  File: JcrCmsOutputHandler.java View source code
@Override
public IContentItem getFileOutputContentItem() {
    String contentName = getContentRef();
    try {
        Repository repository = getRepository();
        if (repository == null) {
            Logger.error(JcrCmsOutputHandler.class.getName(), Messages.getInstance().getString(//$NON-NLS-1$
            "JcrCmsOutputHandler.ERROR_0001_GETTING_CMSREPO"));
            return null;
        }
        Session jcrSession = getJcrSession(repository);
        if (jcrSession == null) {
            Logger.error(JcrCmsOutputHandler.class.getName(), Messages.getInstance().getString(//$NON-NLS-1$
            "JcrCmsOutputHandler.ERROR_0002_GETTING_SESSION"));
            return null;
        }
        // Use the root node as a starting point
        Node root = jcrSession.getRootNode();
        if (root == null) {
            Logger.error(JcrCmsOutputHandler.class.getName(), Messages.getInstance().getString(//$NON-NLS-1$
            "JcrCmsOutputHandler.ERROR_0003_GETTING_ROOT"));
            return null;
        }
        Node node = root;
        // parse the path
        //$NON-NLS-1$
        StringTokenizer tokenizer = new StringTokenizer(contentName, "/");
        int levels = tokenizer.countTokens();
        for (int idx = 0; idx < levels - 1; idx++) {
            String folder = tokenizer.nextToken();
            if (!node.hasNode(folder)) {
                // Create an unstructured node under which to import the XML
                //$NON-NLS-1$
                node = node.addNode(folder, "nt:folder");
            } else {
                node = node.getNodes(folder).nextNode();
            }
        }
        // we should be at the right level now
        String fileName = tokenizer.nextToken();
        Node fileNode = null;
        Node contentNode = null;
        Version version = null;
        if (node.hasNode(fileName)) {
            fileNode = node.getNode(fileName);
            //$NON-NLS-1$
            contentNode = fileNode.getNode("jcr:content");
            if (contentNode.isLocked()) {
                JcrCmsOutputHandler.logger.warn(//$NON-NLS-1$
                Messages.getInstance().getString("JcrCmsOutputHandler.ERROR_0004_NODE_LOCKED", contentName));
                return null;
            }
            if (contentNode.isCheckedOut()) {
                JcrCmsOutputHandler.logger.warn(Messages.getInstance().getString("JcrCmsOutputHandler.ERROR_0005_NODE_CHECKED_OUT", //$NON-NLS-1$
                contentName));
                return null;
            }
            contentNode.checkout();
            VersionHistory history = contentNode.getVersionHistory();
            VersionIterator iterator = history.getAllVersions();
            while (iterator.hasNext()) {
                version = iterator.nextVersion();
                JcrCmsOutputHandler.logger.trace(version.getPath() + "," + version.getName() + "," + version.getIndex() + "," + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                version.getCreated().toString());
            }
        } else {
            //$NON-NLS-1$
            fileNode = node.addNode(fileName, "nt:file");
            //$NON-NLS-1$
            fileNode.addMixin("mix:versionable");
            //                create the mandatory child node - jcr:content
            //$NON-NLS-1$ //$NON-NLS-2$
            contentNode = fileNode.addNode("jcr:content", "nt:resource");
            //$NON-NLS-1$
            contentNode.addMixin("mix:versionable");
            //$NON-NLS-1$
            contentNode.addMixin("mix:filename");
            //$NON-NLS-1$
            contentNode.setProperty("jcr:mimeType", getMimeType());
            //$NON-NLS-1$
            contentNode.setProperty("jcr:name", fileName);
            //$NON-NLS-1$
            contentNode.setProperty("jcr:encoding", LocaleHelper.getSystemEncoding());
        }
        CmsContentListener listener = new CmsContentListener(contentNode, jcrSession);
        BufferedContentItem contentItem = new BufferedContentItem(listener);
        listener.setContentItem(contentItem);
        if (false) {
            // Disable faked search for now
            //$NON-NLS-1$
            search("test", jcrSession);
        }
        return contentItem;
    } catch (LockException le) {
        Logger.error(JcrCmsOutputHandler.class.getName(), Messages.getInstance().getString("JcrCmsOutputHandler.ERROR_0006_GETTING_OUTPUTHANDLER") + contentName, le);
    } catch (NestableRuntimeException nre) {
        Logger.error(JcrCmsOutputHandler.class.getName(), Messages.getInstance().getString("JcrCmsOutputHandler.ERROR_0006_GETTING_OUTPUTHANDLER") + contentName, nre);
    } catch (RepositoryException re) {
        Logger.error(JcrCmsOutputHandler.class.getName(), Messages.getInstance().getString("JcrCmsOutputHandler.ERROR_0006_GETTING_OUTPUTHANDLER") + contentName, re);
    }
    return null;
}
Example 83
Project: com.idega.slide-master  File: SlideNode.java View source code
private void create(String nodePath, String type) throws ItemExistsException {
    try {
        //try {
        //	objectNode = structure.retrieve(token, nodePath);
        //	revisions = content.retrieve(token, nodePath);
        //	lastRevision = revisions.getLatestRevision();
        //} catch (ObjectNotFoundException e) {
        SubjectNode subject = new SubjectNode();
        // Create object
        try {
            structure.create(token, subject, nodePath);
            objectNode = structure.retrieve(token, nodePath);
        } catch (ObjectAlreadyExistsException e1) {
            throw new ItemExistsException(e1);
        }
        if (lastRevision == null) {
            lastRevision = new NodeRevisionNumber();
        } else {
            lastRevision = new NodeRevisionNumber(lastRevision, false);
        }
        // Node revision descriptor
        IWTimestamp now = IWTimestamp.RightNow();
        revisionDescriptor = new NodeRevisionDescriptor(lastRevision, NodeRevisionDescriptors.MAIN_BRANCH, new Vector(), new Hashtable());
        if (type.equals(PRIMARY_NODETYPE_FILE)) {
            revisionDescriptor.setResourceType(CoreConstants.EMPTY);
        }
        /*
				 * revisionDescriptor.setResourceType(CoreConstants.EMPTY);
				 */
        revisionDescriptor.setSource(CoreConstants.EMPTY);
        revisionDescriptor.setContentLanguage(Locale.ENGLISH.getLanguage());
        revisionDescriptor.setLastModified(now.getDate());
        revisionDescriptor.setETag(computeEtag(path, revisionDescriptor));
        revisionDescriptor.setCreationDate(now.getDate());
        if (this.type.equals(PRIMARY_NODETYPE_FOLDER)) {
            //this.setProperty(Property, "<collection/>");
            this.revisionDescriptor.setResourceType("<collection/>");
        }
        isNew = true;
    // Create content
    //revisionContent = new NodeRevisionContent();
    // revisionContent.setContent(stream);
    // Important to create NodeRevisionDescriptors separately to be
    // able to tell it to use versioning
    //if (lastRevision.toString().equals("1.0")) {
    //	content.create(token, nodePath, true);
    //}
    //content.create(token, nodePath, revisionDescriptor,
    //		revisionContent);
    } catch (ObjectNotFoundException e) {
        e.printStackTrace();
    } catch (org.apache.slide.security.AccessDeniedException e) {
        e.printStackTrace();
    } catch (LinkedObjectNotFoundException e) {
        e.printStackTrace();
    } catch (ObjectLockedException e) {
        e.printStackTrace();
    } catch (ServiceAccessException e) {
        e.printStackTrace();
    } catch (VetoException e) {
        e.printStackTrace();
    }
}
Example 84
Project: cq5-healthcheck-master  File: JcrObservationDelayProvider.java View source code
@Activate
protected void activate(ComponentContext ctx) {
    Session readWriteSession = null;
    Dictionary<?, ?> props = ctx.getProperties();
    delayWarn = PropertiesUtil.toLong(props.get(DELAY_WARN), DEFAULT_DELAY_WARN);
    delayCritical = PropertiesUtil.toLong(props.get(DELAY_CRITICAL), DEFAULT_DELAY_CRITICAL);
    schedulingInterval = PropertiesUtil.toLong(props.get(SCHEDULING_INTERVAL), DEFAULT_SCHEDULING_INTERVAL);
    category = PropertiesUtil.toString(props.get(CATEGORY), null);
    try {
        readWriteSession = repo.loginAdministrative(null);
        if (!readWriteSession.getRootNode().hasNode(tempDir.replaceFirst("/", ""))) {
            log.info("Created temp directory");
            JcrUtil.createPath(tempDir, "nt:unstructured", readWriteSession);
            readWriteSession.save();
        }
    // Node tmpNode = readWriteSession.getNode(tempDir);
    // Long now = System.currentTimeMillis();
    // NodeIterator childs = tmpNode.getNodes();
    } catch (RepositoryException e) {
        log.error("Cannot create Session for setting up temp directory:", e);
    } finally {
        if (readWriteSession != null && readWriteSession.isLive()) {
            readWriteSession.logout();
        }
    }
    try {
        listenSession = repo.loginAdministrative(null);
        startListen();
    } catch (RepositoryException e) {
        log.error("Cannot create listenSession", e);
    }
    try {
        scheduler.fireJob(new ObservationTrigger(tempDir), null);
        scheduler.addPeriodicJob(JOBNAME, new ObservationTrigger(tempDir), null, schedulingInterval, false);
    } catch (Exception e) {
        log.error("Cannot start scheduler", e);
    }
    log.info("JcrObservationDelay checker started");
}
Example 85
Project: hippo-gmaps-master  File: GmapsPlugin.java View source code
private String[] getLocation() {
    String[] location = new String[2];
    Node locationNode = (Node) getDefaultModelObject();
    try {
        if (locationNode != null) {
            location[0] = String.valueOf(locationNode.getProperty("gmaps:latitude").getDouble());
            location[1] = String.valueOf(locationNode.getProperty("gmaps:longitude").getDouble());
        } else {
            location[0] = "0.0";
            location[1] = "0.0";
        }
    } catch (RepositoryException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return location;
}
Example 86
Project: intelij-hippo-groovy-master  File: RepositoryConnector.java View source code
public boolean saveGroovyFile(final String path, final Location location, final FileDialogData data) {
    Session session = null;
    try {
        session = getSession();
        if (session.nodeExists(path)) {
            session.removeItem(path);
        }
        final Node root = session.getNode(location.getPath());
        final Node scriptNode = root.addNode(data.getScriptName(), "hipposys:updaterinfo");
        scriptNode.setProperty("hipposys:batchsize", data.getBatchSize());
        scriptNode.setProperty("hipposys:throttle", data.getThrottle());
        scriptNode.setProperty("hipposys:dryrun", data.isDryRun());
        final String queryScript = data.getQueryScript();
        if (!Strings.isNullOrEmpty(queryScript)) {
            scriptNode.setProperty("hipposys:query", queryScript);
        }
        String content = data.getContent();
        if (Strings.isNullOrEmpty(content)) {
            content = "//no script defined";
        }
        scriptNode.setProperty("hipposys:script", content);
        final String pathScript = data.getPathScript();
        if (!Strings.isNullOrEmpty(pathScript)) {
            scriptNode.setProperty("hipposys:path", pathScript);
        }
        session.save();
        return true;
    } catch (RepositoryException e) {
        GroovyEditor.error("Error saving template to hippo repository" + e.getMessage(), project);
    } finally {
        if (session != null) {
            session.logout();
        }
    }
    return false;
}
Example 87
Project: juzu-master  File: SecretServiceJCRImpl.java View source code
@Override
public List<Secret> getSecrets() {
    List<Secret> secrets = new LinkedList<Secret>();
    try {
        Node secretHome = getSecretHome();
        NodeIterator iterChild = secretHome.getNodes();
        while (iterChild.hasNext()) {
            secrets.add(buildSecret(iterChild.nextNode()));
        }
        return secrets;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Example 88
Project: Poll-Legacy-master  File: VoteAction.java View source code
// Vote action
public ActionResult doExecute(HttpServletRequest req, RenderContext renderContext, Resource resource, JCRSessionWrapper session, Map<String, List<String>> parameters, URLResolver urlResolver) throws Exception {
    String answerUUID = req.getParameter("answerUUID");
    // Poll Node management
    // Get the pollNode
    JCRNodeWrapper pollNode = session.getNodeByUUID(renderContext.getMainResource().getNode().getIdentifier());
    // Get a version manager
    VersionManager versionManager = pollNode.getSession().getWorkspace().getVersionManager();
    // Check out poll node
    if (!versionManager.isCheckedOut(pollNode.getPath()))
        versionManager.checkout(pollNode.getPath());
    // Update total of votes (poll node)
    long totalOfVotes = pollNode.getProperty("totalOfVotes").getLong();
    pollNode.setProperty("totalOfVotes", totalOfVotes + 1);
    // Answer node management
    // Get the answer node
    JCRNodeWrapper answerNode = pollNode.getSession().getNodeByUUID(answerUUID);
    // Check out answerNode
    if (!versionManager.isCheckedOut(answerNode.getPath()))
        versionManager.checkout(answerNode.getPath());
    // Increment nb votes
    long nbOfVotes = answerNode.getProperty("nbOfVotes").getLong();
    answerNode.setProperty("nbOfVotes", nbOfVotes + 1);
    // Save
    pollNode.getSession().save();
    // Check in
    versionManager.checkin(pollNode.getPath());
    // Check in poll node
    versionManager.checkin(answerNode.getPath());
    return new ActionResult(HttpServletResponse.SC_OK, null, generateJSONObject(pollNode));
}
Example 89
Project: com.idega.jackrabbit-master  File: JackrabbitRepository.java View source code
private Node uploadFile(String parentPath, String fileName, InputStream content, String mimeType, User user, AdvancedProperty... properties) throws RepositoryException {
    if (parentPath == null) {
        getLogger().warning("Parent path is not defined!");
        return null;
    }
    if (StringUtil.isEmpty(fileName)) {
        getLogger().warning("File name is not defined!");
        return null;
    }
    if (content == null) {
        getLogger().warning("Input stream is invalid!");
        return null;
    }
    if (!parentPath.endsWith(CoreConstants.SLASH)) {
        parentPath = parentPath.concat(CoreConstants.SLASH);
    }
    Binary binary = null;
    Session session = null;
    try {
        session = getSession(user);
        VersionManager versionManager = session.getWorkspace().getVersionManager();
        Node root = session.getRootNode();
        Node folder = getFolderNode(root, parentPath);
        Node file = getFileNode(folder, fileName, versionManager);
        Node resource = getResourceNode(file);
        if (resource == null) {
            resource = file.addNode(JcrConstants.JCR_CONTENT, JcrConstants.NT_RESOURCE);
        }
        mimeType = StringUtil.isEmpty(mimeType) ? MimeTypeUtil.resolveMimeTypeFromFileName(fileName) : mimeType;
        mimeType = StringUtil.isEmpty(mimeType) ? MimeTypeUtil.MIME_TYPE_APPLICATION : mimeType;
        resource.setProperty(JcrConstants.JCR_MIMETYPE, mimeType);
        resource.setProperty(JcrConstants.JCR_ENCODING, CoreConstants.ENCODING_UTF8);
        binary = ValueFactoryImpl.getInstance().createBinary(content);
        resource.setProperty(JcrConstants.JCR_DATA, binary);
        Calendar lastModified = Calendar.getInstance();
        lastModified.setTimeInMillis(System.currentTimeMillis());
        resource.setProperty(JcrConstants.JCR_LASTMODIFIED, lastModified);
        session.save();
        versionManager.checkin(file.getPath());
        return file;
    } finally {
        if (binary != null) {
            binary.dispose();
        }
        IOUtil.close(content);
        logout(session);
    }
}
Example 90
Project: linshare-core-master  File: JackRabbitFileSystem.java View source code
public Object doInJcr(Session session) throws RepositoryException {
    Node root = session.getRootNode();
    Node fileNode = null;
    Logger.debug(completePath);
    if (root.hasNode(completePath)) {
        fileNode = root.getNode(completePath);
        if (fileNode.isNodeType(JcrConstants.NT_FILE)) {
            return fileNode.getNode("jcr:content").getProperty("jcr:data").getStream();
        } else {
            Logger.error("the path node doesn't contain a file: " + completePath);
        }
    } else {
        Logger.error("the path node is invalid: " + completePath);
    }
    return null;
}
Example 91
Project: cocoon-master  File: JCRSourceFactory.java View source code
/**
     * Get the type info for a node.
     *
     * @param node the node
     * @return the type info
     * @throws RepositoryException if node type couldn't be accessed or if no type info is found
     */
public NodeTypeInfo getTypeInfo(Node node) throws RepositoryException {
    String typeName = node.getPrimaryNodeType().getName();
    NodeTypeInfo result = (NodeTypeInfo) this.typeInfos.get(typeName);
    if (result == null) {
        // TODO: build a NodeTypeInfo using introspection
        throw new RepositoryException("No type info found for node type '" + typeName + "' at " + node.getPath());
    }
    return result;
}
Example 92
Project: etk-model-master  File: TestNavigationServiceSave.java View source code
public void testDestroyNavigation() throws Exception {
    NavigationContext nav = service.loadNavigation(SiteKey.portal("destroy_navigation"));
    assertNull(nav);
    //
    mgr.getPOMService().getModel().getWorkspace().addSite(ObjectType.PORTAL_SITE, "destroy_navigation").getRootNavigation().addChild("default").addChild("a");
    //
    sync(true);
    service.clearCache();
    //
    nav = service.loadNavigation(SiteKey.portal("destroy_navigation"));
    assertNotNull(nav);
    //
    Node root = service.loadNode(Node.MODEL, nav, Scope.ALL, null).getNode();
    //
    assertTrue(service.destroyNavigation(nav));
    assertNull(nav.state);
    assertNull(nav.data);
    //
    try {
        service.destroyNavigation(nav);
    } catch (IllegalArgumentException e) {
    }
    //
    nav = service.loadNavigation(SiteKey.portal("destroy_navigation"));
    assertNull(nav);
    //
    sync(true);
    //
    nav = service.loadNavigation(SiteKey.portal("destroy_navigation"));
    assertNull(nav);
}
Example 93
Project: gatein-portal-master  File: TestNavigationServiceSave.java View source code
public void testDestroyNavigation() throws Exception {
    NavigationContext nav = service.loadNavigation(SiteKey.portal("destroy_navigation"));
    assertNull(nav);
    //
    mgr.getPOMService().getModel().getWorkspace().addSite(ObjectType.PORTAL_SITE, "destroy_navigation").getRootNavigation().addChild("default").addChild("a");
    //
    sync(true);
    service.clearCache();
    //
    nav = service.loadNavigation(SiteKey.portal("destroy_navigation"));
    assertNotNull(nav);
    //
    Node root = service.loadNode(Node.MODEL, nav, Scope.ALL, null).getNode();
    //
    assertTrue(service.destroyNavigation(nav));
    assertNull(nav.state);
    assertNull(nav.data);
    //
    try {
        service.destroyNavigation(nav);
    } catch (IllegalArgumentException e) {
    }
    //
    nav = service.loadNavigation(SiteKey.portal("destroy_navigation"));
    assertNull(nav);
    //
    sync(true);
    //
    nav = service.loadNavigation(SiteKey.portal("destroy_navigation"));
    assertNull(nav);
}
Example 94
Project: liferay-portal-master  File: JCRStore.java View source code
@Override
public void addDirectory(long companyId, long repositoryId, String dirName) {
    Session session = null;
    try {
        session = _jcrFactoryWrapper.createSession();
        Node rootNode = getRootNode(session, companyId);
        Node repositoryNode = getFolderNode(rootNode, repositoryId);
        if (repositoryNode.hasNode(dirName)) {
            return;
        }
        String[] dirNameArray = StringUtil.split(dirName, '/');
        Node dirNode = repositoryNode;
        for (String nodeName : dirNameArray) {
            if (Validator.isNotNull(nodeName)) {
                if (dirNode.hasNode(nodeName)) {
                    dirNode = dirNode.getNode(nodeName);
                } else {
                    dirNode = dirNode.addNode(nodeName, JCRConstants.NT_FOLDER);
                }
            }
        }
        session.save();
    } catch (RepositoryException re) {
        throw new SystemException(re);
    } finally {
        _jcrFactoryWrapper.closeSession(session);
    }
}
Example 95
Project: org.liveSense.service.securityManager-master  File: SecurityManagerServiceImpl.java View source code
@Override
public void createUserHome(Session session, String userName, String parentPath) throws PrincipalIsNotUserException, InternalException, PrincipalNotExistsException {
    try {
        UserManager userManager = AccessControlUtil.getUserManager(session);
        Authorizable authorizable = userManager.getAuthorizable(userName);
        if (authorizable.isGroup()) {
            throw new PrincipalIsNotUserException("Principal is not user: " + userName);
        }
        Node rootNode = session.getRootNode();
        if (StringUtils.isNotBlank(parentPath)) {
            rootNode = rootNode.getNode(parentPath);
        }
        Node home = null;
        // If home does not exists, we create it and setting access rights
        if (!rootNode.hasNode("home")) {
            // Create home
            home = rootNode.addNode("home");
            // Access rights (Read/Write disabled)
            AccessRights rights = new AccessRightsImpl();
            rights.getDenied().add(new SerializablePrivilege(SerializablePrivilege.JCR_ALL));
            setAclByName(session, "everyone", home.getPath(), rights);
        } else {
            home = rootNode.getNode("home");
        }
        // If home/user does not exists, we create it and setting access rights
        Node userNode = null;
        if (!home.hasNode(userName)) {
            userNode = home.addNode(userName);
            // Access rights (Read/Write enabled)
            AccessRights rights = new AccessRightsImpl();
            rights.getGranted().add(new SerializablePrivilege(SerializablePrivilege.JCR_ALL));
            setAclByName(session, userName, userNode.getPath(), rights);
        } else {
            userNode = home.getNode(userName);
        }
        if (session.hasPendingChanges()) {
            session.save();
        }
    } catch (RepositoryException ex) {
        throw new InternalException("Repository exception", ex);
    } catch (IllegalArgumentException ex) {
        throw new InternalException(ex);
    } finally {
    }
}
Example 96
Project: docs-samples-master  File: MyUIFilter.java View source code
/*
		* This method checks if the current node is a file.
	*/
public boolean accept(Map<String, Object> context) throws Exception {
    //Retrieve the current node from the context
    Node currentNode = (Node) context.get(Node.class.getName());
    return currentNode.isNodeType("nt:file");
}
Example 97
Project: carbon-registry-master  File: RegistryItemVisitor.java View source code
public void visit(Node node) throws RepositoryException {
}
Example 98
Project: insight-plugin-hst-master  File: DummyQuery.java View source code
public void addScopes(final Node[] scopes) {
}
Example 99
Project: magnolia-examproject-master  File: ContentLinkItem.java View source code
///////////////////////////////////////////////////////////////////////////
// public methods
@RequestMapping("/contentLinkItem")
public String render(ModelMap model, Node content) throws RepositoryException {
    LOG.trace("called.");
    return "components/content/item/contentLinkItem.jsp";
}
Example 100
Project: resin-master  File: BaseNodeIterator.java View source code
/**
   * Returns the next node.
   */
public Node nextNode() {
    if (_index < _nodes.length)
        return _nodes[_index++];
    else
        return null;
}