org.apache.jackrabbit.util.Text Java Examples

The following examples show how to use org.apache.jackrabbit.util.Text. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DavResourceImpl.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Adds a new member to this resource.
 * 
 * @see DavResource#addMember(DavResource,
 *      org.apache.jackrabbit.webdav.io.InputContext)
 */
public void addMember(DavResource member, InputContext inputContext) throws DavException {
	if (!exists()) {
		throw new DavException(DavServletResponse.SC_CONFLICT);
	}
	if (isLocked(this) || isLocked(member)) {
		throw new DavException(DavServletResponse.SC_LOCKED);
	}

	try {
		String memberName = Text.getName(member.getLocator().getResourcePath());

		ImportContext ctx = getImportContext(inputContext, memberName);

		if (!config.getIOManager().importContent(ctx, member)) {
			// any changes should have been reverted in the importer
			throw new DavException(DavServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
		}
	} catch (Exception e) {
		log.error(e.getMessage(), e);
	}
}
 
Example #2
Source File: DefaultWorkspaceFilter.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
private void dumpCoverage(javax.jcr.Node node, ProgressTracker tracker, boolean skipJcrContent)
        throws RepositoryException {
    String path = node.getPath();
    if (skipJcrContent && "jcr:content".equals(Text.getName(path))) {
        return;
    }
    boolean contained;
    if ((contained = contains(path)) || isAncestor(path)) {
        if (contained) {
            tracker.track("A", path);
        }
        NodeIterator iter = node.getNodes();
        while (iter.hasNext()) {
            dumpCoverage(iter.nextNode(), tracker, skipJcrContent);
        }

    }
}
 
Example #3
Source File: SubPackageHandling.java    From jackrabbit-filevault with Apache License 2.0 6 votes vote down vote up
/**
 * Parses a options string as described above and returns a new SubPackageHandling instance.
 * @param str the string to parse
 * @return the configuration or {@code null} if the string is malformed.
 */
public static SubPackageHandling fromString(String str) {
    if (str == null || str.isEmpty()) {
        return SubPackageHandling.DEFAULT;
    }
    SubPackageHandling sp = new SubPackageHandling();
    for (String instruction: Text.explode(str, ',')) {
        String[] opts = Text.explode(instruction.trim(), ';');
        if (opts.length >  0) {
            PackageId id = PackageId.fromString(opts[0]);
            Option opt = Option.INSTALL;
            if (opts.length > 1) {
                try {
                    opt = Option.valueOf(opts[1].toUpperCase());
                } catch (IllegalArgumentException e) {
                    // ignore
                }
            }
            sp.getEntries().add(new Entry(id.getGroup(), id.getName(), opt));
        }
    }
    return sp;
}
 
Example #4
Source File: ArchivaVirtualDavResource.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Override
public DavResource getCollection()
{
    DavResource parent = null;
    if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
    {
        String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
        if ( parentPath.equals( "" ) )
        {
            parentPath = "/";
        }
        DavResourceLocator parentloc =
            locator.getFactory().createResourceLocator( locator.getPrefix(), parentPath );
        try
        {
            // go back to ArchivaDavResourceFactory!
            parent = factory.createResource( parentloc, null );
        }
        catch ( DavException e )
        {
            // should not occur
        }
    }
    return parent;
}
 
Example #5
Source File: ArchivaDavResource.java    From archiva with Apache License 2.0 6 votes vote down vote up
@Override
public DavResource getCollection()
{
    DavResource parent = null;
    if ( getResourcePath() != null && !getResourcePath().equals( "/" ) )
    {
        String parentPath = Text.getRelativeParent( getResourcePath(), 1 );
        if ( parentPath.equals( "" ) )
        {
            parentPath = "/";
        }
        DavResourceLocator parentloc =
            locator.getFactory().createResourceLocator( locator.getPrefix(), parentPath );
        try
        {
            parent = factory.createResource( parentloc, session );
        }
        catch ( DavException e )
        {
            // should not occur
        }
    }
    return parent;
}
 
Example #6
Source File: SyncHandler.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private SyncResult syncToDisk(Session session) throws RepositoryException, IOException {
    SyncResult res = new SyncResult();
    for (String path: preparedJcrChanges) {
        boolean recursive = path.endsWith("/");
        if (recursive) {
            path = path.substring(0, path.length() - 1);
        }
        if (!contains(path)) {
            log.debug("**** rejected. filter does not include {}", path);
            continue;
        }
        File file = getFileForJcrPath(path);
        log.debug("**** about sync jcr:/{} -> file://{}", path, file.getAbsolutePath());
        Node node;
        Node parentNode;
        if (session.nodeExists(path)) {
            node = session.getNode(path);
            parentNode = node.getParent();
        } else {
            node = null;
            String parentPath = Text.getRelativeParent(path, 1);
            parentNode = session.nodeExists(parentPath)
                    ? session.getNode(parentPath)
                    : null;
        }
        TreeSync tree = createTreeSync(SyncMode.JCR2FS);
        res.merge(tree.syncSingle(parentNode, node, file, recursive));
    }
    return res;
}
 
Example #7
Source File: SyncHandler.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
private void syncToJcr(Session session, SyncResult res) throws RepositoryException, IOException {
    for (String filePath: pendingFsChanges.keySet()) {
        if (res.getByFsPath(filePath) != null) {
            log.debug("ignoring change triggered by previous JCR->FS update. {}", filePath);
            return;
        }
        File file = pendingFsChanges.get(filePath);
        String path = getJcrPathForFile(file);
        log.debug("**** about sync file:/{} -> jcr://{}", file.getAbsolutePath(), path);
        if (!contains(path)) {
            log.debug("**** rejected. filter does not include {}", path);
            continue;
        }
        Node node;
        Node parentNode;
        if (session.nodeExists(path)) {
            node = session.getNode(path);
            parentNode = node.getParent();
        } else {
            node = null;
            String parentPath = Text.getRelativeParent(path, 1);
            parentNode = session.nodeExists(parentPath)
                    ? session.getNode(parentPath)
                    : null;
        }
        TreeSync tree = createTreeSync(SyncMode.FS2JCR);
        tree.setSyncMode(SyncMode.FS2JCR);
        res.merge(tree.syncSingle(parentNode, node, file, false));
    }
}
 
Example #8
Source File: DocumentViewXmlContentHandler.java    From jackrabbit-filevault with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param filePath the relative file to the docview file (relative to the jcr_root folder)
 * @param basePath the absolute file path of the the jcr_root folder (to which {@code filePath} is relative)
 * @param rootNodePath the node path of the root node covered by this docview file
 * @param documentViewXmlValidators the validators to call for this docview file
 */
public DocumentViewXmlContentHandler(@NotNull Path filePath, @NotNull Path basePath, String rootNodePath, Map<String, DocumentViewXmlValidator> documentViewXmlValidators) {
    this.filePath = filePath;
    this.basePath = basePath;
    if (rootNodePath.equals("/")) {
        rootNodePath = "";
    }
    if (rootNodePath.endsWith("/")) {
        throw new IllegalArgumentException("rootPath must not end with \"/\" but is " + rootNodePath);
    }
    if (rootNodePath.contains("\\")) {
        throw new IllegalArgumentException("rootPath must not contain backslashes, only forward slashes should be used as separator!");
    }
    nodePathsAndLineNumbers = new HashMap<>();
    rootNodeName = Text.getName(rootNodePath);
    rootNodeParentPath = Text.getRelativeParent(rootNodePath, 1);
    if (rootNodeParentPath.equals("/")) {
        rootNodeParentPath = "";
    }

    elementNameStack = new LinkedList<>();
    nodeStack = new LinkedList<>();
    nodePathStack = new LinkedList<>();
    this.validators = documentViewXmlValidators;
    violations = new LinkedList<>();
    namespaceRegistry = new HashMap<>();
}
 
Example #9
Source File: ArchivaDavLocatorFactory.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Override
public DavResourceLocator createResourceLocator( String prefix, String href )
{
    // build prefix string and remove all prefixes from the given href.
    StringBuilder b = new StringBuilder();
    if ( prefix != null && prefix.length() > 0 )
    {
        b.append( prefix );
        if ( !prefix.endsWith( "/" ) )
        {
            b.append( '/' );
        }
        if ( href.startsWith( prefix ) )
        {
            href = href.substring( prefix.length() );
        }
    }

    // special treatment for root item, that has no name but '/' path.
    if ( href == null || "".equals( href ) )
    {
        href = "/";
    }

    final String repository = RepositoryPathUtil.getRepositoryName( href );
    return new ArchivaDavResourceLocator( b.toString(), Text.unescape( href ), repository, this );
}
 
Example #10
Source File: ArchivaVirtualDavResource.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Override
public String getDisplayName()
{
    String resPath = getResourcePath();

    return ( resPath != null ) ? Text.getName( resPath ) : resPath;
}
 
Example #11
Source File: ArchivaDavResourceLocator.java    From archiva with Apache License 2.0 5 votes vote down vote up
public ArchivaDavResourceLocator( String prefix, String resourcePath, String repositoryId,
                                  DavLocatorFactory davLocatorFactory )
{
    this.prefix = prefix;
    this.repositoryId = repositoryId;
    this.davLocatorFactory = davLocatorFactory;

    String path = resourcePath;

    if ( !resourcePath.startsWith( "/" ) )
    {
        path = "/" + resourcePath;
    }

    String escapedPath = Text.escapePath( resourcePath );
    String hrefPrefix = prefix;

    // Ensure no extra slashes when href is joined
    if ( hrefPrefix.endsWith( "/" ) && escapedPath.startsWith( "/" ) )
    {
        hrefPrefix = hrefPrefix.substring( 0, hrefPrefix.length() - 1 );
    }

    href = hrefPrefix + escapedPath;

    this.origResourcePath = path;

    //Remove trailing slashes otherwise Text.getRelativeParent fails
    if ( resourcePath.endsWith( "/" ) && resourcePath.length() > 1 )
    {
        path = resourcePath.substring( 0, resourcePath.length() - 1 );
    }

    this.resourcePath = path;
}
 
Example #12
Source File: Initializer.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
@Override
public void activate() {
    final ValueMap properties = getProperties();
    final I18n i18n = new I18n(getRequest());
    final ExpressionHelper ex = new ExpressionHelper(getSlingScriptHelper().getService(ExpressionResolver.class), getRequest());
    final CommerceBasePathsService cbps = getSlingScriptHelper().getService(CommerceBasePathsService.class);

    // configure default properties for cifcategoryfield
    String defaultRootPath = new CatalogSearchSupport(getResourceResolver()).findCatalogPathForPicker(getRequest());
    if (StringUtils.isBlank(defaultRootPath)) {
        defaultRootPath = cbps.getProductsBasePath();
    }
    final String rootPath = ex.getString(properties.get("rootPath", defaultRootPath));
    final String filter = properties.get("filter", "folderOrCategory");
    final boolean multiple = properties.get("multiple", DEFAULT_SELECTION_MULTIPLE);
    final String selectionId = properties.get("selectionId", DEFAULT_SELECTION_TYPE);
    final String defaultEmptyText = "path".equals(selectionId) ? "Category path" : "Category ID";
    final String emptyText = i18n.getVar(properties.get("emptyText", i18n.get(defaultEmptyText)));

    final String selectionCount = multiple ? "multiple" : "single";
    String pickerSrc = DEFAULT_PICKER_SRC + "?root=" + Text.escape(rootPath) + "&filter=" + Text.escape(filter) + "&selectionCount="
        + selectionCount + "&selectionId=" + Text.escape(selectionId);
    pickerSrc = properties.get("pickerSrc", pickerSrc);

    // suggestions disabled

    ValueMapResourceWrapper wrapper = new ValueMapResourceWrapper(getResource(), FIELD_SUPER_TYPE);
    ValueMap wrapperProperties = wrapper.adaptTo(ValueMap.class);
    wrapperProperties.putAll(properties);
    wrapperProperties.put("rootPath", rootPath);
    wrapperProperties.put("filter", filter);
    wrapperProperties.put("multiple", multiple);
    wrapperProperties.put("pickerSrc", pickerSrc);
    // needed to disable the default suggestions of pathfield
    wrapperProperties.put("suggestionSrc", "");
    wrapperProperties.put("emptyText", emptyText);

    wrapperProperties.put("forceselection", true);

    getSlingScriptHelper().include(wrapper);
}
 
Example #13
Source File: Initializer.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
@Override
public void activate() {
    final ValueMap properties = getProperties();
    final I18n i18n = new I18n(getRequest());
    final ExpressionHelper ex = new ExpressionHelper(getSlingScriptHelper().getService(ExpressionResolver.class), getRequest());
    final CommerceBasePathsService cbps = getSlingScriptHelper().getService(CommerceBasePathsService.class);

    // configure default properties for productfield
    String defaultRootPath = new CatalogSearchSupport(getResourceResolver()).findCatalogPathForPicker(getRequest());
    if (StringUtils.isBlank(defaultRootPath)) {
        defaultRootPath = cbps.getProductsBasePath();
    }
    final String rootPath = ex.getString(properties.get("rootPath", defaultRootPath));
    final String filter = properties.get("filter", DEFAULT_FILTER);
    final boolean multiple = properties.get("multiple", DEFAULT_SELECTION_MULTIPLE);
    final String selectionId = properties.get("selectionId", DEFAULT_SELECTION_TYPE);
    final String defaultEmptyText;
    if ("path".equals(selectionId)) {
        defaultEmptyText = "Product path";
    } else if ("sku".equals(selectionId)) {
        defaultEmptyText = "Product SKU";
    } else if ("slug".equals(selectionId)) {
        defaultEmptyText = "Product slug";
    } else if ("combinedSku".equals(selectionId)) {
        defaultEmptyText = "Product SKU(s) separated by # character";
    } else {
        defaultEmptyText = "Product ID";
    }
    final String emptyText = i18n.getVar(properties.get("emptyText", i18n.get(defaultEmptyText)));

    final String selectionCount = multiple ? "multiple" : "single";
    String pickerSrc = DEFAULT_PICKER_SRC + "?root=" + Text.escape(rootPath) + "&filter=" + Text.escape(filter) + "&selectionCount="
        + selectionCount + "&selectionId=" + Text.escape(selectionId);
    String suggestionSrc = DEFAULT_SUGGESTION_SRC + "?root=" + Text.escape(rootPath) + "&filter=product{&query}";
    pickerSrc = properties.get("pickerSrc", pickerSrc);
    suggestionSrc = properties.get("suggestionSrc", suggestionSrc);

    // suggestions disabled
    suggestionSrc = "";

    ValueMapResourceWrapper wrapper = new ValueMapResourceWrapper(getResource(), FIELD_SUPER_TYPE);
    ValueMap wrapperProperties = wrapper.adaptTo(ValueMap.class);
    wrapperProperties.putAll(properties);
    wrapperProperties.put("rootPath", rootPath);
    wrapperProperties.put("filter", filter);
    wrapperProperties.put("multiple", multiple);
    wrapperProperties.put("pickerSrc", pickerSrc);
    wrapperProperties.put("suggestionSrc", suggestionSrc);
    wrapperProperties.put("emptyText", emptyText);
    wrapperProperties.put("forceselection", true);

    getSlingScriptHelper().include(wrapper);
}
 
Example #14
Source File: MessageStoreImpl.java    From sling-samples with Apache License 2.0 4 votes vote down vote up
private void save(ResourceResolver resolver, Message msg) throws IOException, LoginException {
    // apply message processors
    for(MessageProcessor processor : getSortedMessageProcessors()) {
        logger.debug("Calling {}", processor);
        processor.processMessage(msg);
    }

    // into path: archive/domain/list/thread/message
    final Map<String, Object> msgProps = new HashMap<String, Object>();
    final List<BodyPart> attachments = new ArrayList<BodyPart>(); 

    msgProps.put(resourceTypeKey, MailArchiveServerConstants.MESSAGE_RT);

    StringBuilder plainBody = new StringBuilder();
    StringBuilder htmlBody = new StringBuilder();
    Boolean hasBody = false;

    if (!msg.isMultipart()) {
        plainBody = new StringBuilder(getTextPart(msg)); 
    } else {
        Multipart multipart = (Multipart) msg.getBody();
        recursiveMultipartProcessing(multipart, plainBody, htmlBody, hasBody, attachments);
    }

    msgProps.put(PLAIN_BODY, plainBody.toString().replaceAll("\r\n", "\n"));
    if (htmlBody.length() > 0) {
        msgProps.put(HTML_BODY, htmlBody.toString());
    }

    msgProps.putAll(getMessagePropertiesFromHeader(msg.getHeader()));
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new DefaultMessageWriter().writeHeader(msg.getHeader(), baos);
    String origHdr = baos.toString(MailArchiveServerConstants.DEFAULT_ENCODER.charset().name());
    msgProps.put(X_ORIGINAL_HEADER, origHdr);
    
    final Header hdr = msg.getHeader();
    final String listIdRaw = hdr.getField(LIST_ID).getBody();
    final String listId = listIdRaw.substring(1, listIdRaw.length()-1); // remove < and >

    final String list = getListNodeName(listId);
    final String domain = getDomainNodeName(listId);
    final String subject = (String) msgProps.get(SUBJECT);
    final String threadPath = threadKeyGen.getThreadKey(subject);
    final String threadName = removeRe(subject);

    Resource parentResource = assertEachNode(resolver, archivePath, domain, list, threadPath, threadName);

    String msgNodeName = makeJcrFriendly((String) msgProps.get(NAME));
    boolean isMsgNodeCreated = assertResource(resolver, parentResource, msgNodeName, msgProps);
    if (isMsgNodeCreated) {
        Resource msgResource = resolver.getResource(parentResource, msgNodeName);
        for (BodyPart att : attachments) {
            if (!attachmentFilter.isEligible(att)) {
                continue;
            }
            final Map<String, Object> attProps = new HashMap<String, Object>();
            parseHeaderToProps(att.getHeader(), attProps);
            Body body = att.getBody();
            if (body instanceof BinaryBody) {
                attProps.put(CONTENT, ((BinaryBody) body).getInputStream());
            } else if (body instanceof TextBody) {
                attProps.put(CONTENT, ((TextBody) body).getInputStream());
            }

            String attNodeName = Text.escapeIllegalJcrChars(att.getFilename());
            assertResource(resolver, msgResource, attNodeName, attProps);
        }

        updateThread(resolver, parentResource, msgProps);
    }
}
 
Example #15
Source File: ArchivaDavResource.java    From archiva with Apache License 2.0 4 votes vote down vote up
@Override
public String getDisplayName()
{
    String resPath = getResourcePath();
    return ( resPath != null ) ? Text.getName( resPath ) : resPath;
}
 
Example #16
Source File: DavResourceImpl.java    From document-management-software with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Returns the the last segment of the resource path.
 * <p>
 * Note that this must not correspond to the name of the underlying
 * repository item for two reasons:
 * <ul>
 * <li>SameNameSiblings have an index appended to their item name.</li>
 * <li>the resource path may differ from the item path.</li>
 * </ul>
 * Using the item name as DAV:displayname caused problems with XP built-in
 * client in case of resources representing SameNameSibling nodes.
 * 
 * @see DavResource#getDisplayName()
 */
public String getDisplayName() {
	String resPath = getResourcePath();
	return (resPath != null) ? Text.getName(resPath) : resPath;
}