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

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

Introduction

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

Prototype

public static String substringAfter(String str, String separator) 

Source Link

Document

Gets the substring after the first occurrence of a separator.

Usage

From source file:ch.cyberduck.core.UploadTransfer.java

@Override
protected void transfer(Path file) {
    log.debug("transfer:" + file);
    Permission perm = Permission.EMPTY;
    if (file.getLocal().attributes().isSymbolicLink() && this.isSymlinkSupported(file)) {
        // Make relative symbolic link
        final String target = StringUtils.substringAfter(file.getLocal().getSymlinkTarget().getAbsolute(),
                file.getLocal().getParent().getAbsolute() + Path.DELIMITER);
        if (log.isDebugEnabled()) {
            log.debug("Symlink " + file + ":" + target);
        }//  w ww  . jav  a2 s .c om
        file.symlink(target);
        file.status().setComplete(true);
    } else if (file.attributes().isFile()) {
        if (this.getSession().isUnixPermissionsSupported()) {
            if (Preferences.instance().getBoolean("queue.upload.changePermissions")) {
                if (file.exists()) {
                    // Do not overwrite permissions for existing file.
                    if (file.attributes().getPermission().equals(Permission.EMPTY)) {
                        file.readUnixPermission();
                    }
                    perm = file.attributes().getPermission();
                }
            }
        }
        String original = file.getName();
        if (Preferences.instance().getBoolean("queue.upload.file.temporary")
                && file.getSession().isRenameSupported(file)) {
            String temporary = MessageFormat.format(
                    Preferences.instance().getProperty("queue.upload.file.temporary.format"), file.getName(),
                    UUID.randomUUID().toString());
            file.setPath(file.getParent(), temporary);
        }
        // Transfer
        file.upload(bandwidth, new AbstractStreamListener() {
            @Override
            public void bytesSent(long bytes) {
                transferred += bytes;
            }
        });
        if (file.status().isComplete()) {
            if (Preferences.instance().getBoolean("queue.upload.file.temporary")
                    && file.getSession().isRenameSupported(file)) {
                file.rename(PathFactory.createPath(file.getSession(), file.getParent().getAbsolute(), original,
                        file.attributes().getType()));
                file.setPath(file.getParent(), original);
            }
        }
    } else if (file.attributes().isDirectory()) {
        if (file.getSession().isCreateFolderSupported(file)) {
            file.mkdir();
        }
    }
    if (!file.status().isCanceled() && file.status().isComplete()) {
        if (this.getSession().isAclSupported()) {
            ; // Currently handled in S3 only.
        }
        if (this.getSession().isUnixPermissionsSupported()) {
            if (Preferences.instance().getBoolean("queue.upload.changePermissions")) {
                if (perm.equals(Permission.EMPTY)) {
                    if (Preferences.instance().getBoolean("queue.upload.permissions.useDefault")) {
                        if (file.attributes().isFile()) {
                            perm = new Permission(
                                    Preferences.instance().getInteger("queue.upload.permissions.file.default"));
                        } else if (file.attributes().isDirectory()) {
                            perm = new Permission(Preferences.instance()
                                    .getInteger("queue.upload.permissions.folder.default"));
                        }
                    } else {
                        if (file.getLocal().exists()) {
                            // Read permissions from local file
                            perm = file.getLocal().attributes().getPermission();
                        }
                    }
                }
                if (perm.equals(Permission.EMPTY)) {
                    log.debug("Skip writing empty permissions for:" + this.toString());
                } else {
                    file.writeUnixPermission(perm, false);
                }
            }
        }
        if (file.attributes().isFile() && file.getSession().isTimestampSupported()) {
            if (Preferences.instance().getBoolean("queue.upload.preserveDate")) {
                // Read timestamps from local file
                file.writeTimestamp(file.getLocal().attributes().getCreationDate(),
                        file.getLocal().attributes().getModificationDate(),
                        file.getLocal().attributes().getAccessedDate());
            }
        }
    }
}

From source file:eionet.cr.web.action.admin.harvestscripts.HarvestScriptParser.java

/**
 *
 * @param str/*from   www  . j  a v a  2s  .  com*/
 * @param tokenToReplace
 * @param replacement
 * @return
 */
private static String replaceToken(String str, String tokenToReplace, String replacement) {

    if (str == null || str.trim().length() == 0 || tokenToReplace == null
            || tokenToReplace.trim().length() == 0) {
        return str;
    }

    StringTokenizer st = new StringTokenizer(str, " \t\n\r\f", true);
    ArrayList<String> originalTokens = new ArrayList<String>();
    ArrayList<String> upperCaseTokens = new ArrayList<String>();
    while (st.hasMoreTokens()) {
        String nextToken = st.nextToken();
        originalTokens.add(nextToken);
        upperCaseTokens.add(nextToken.toUpperCase());
    }

    StringBuilder buf = new StringBuilder();
    for (String token : originalTokens) {

        if (token.equalsIgnoreCase(tokenToReplace)) {
            buf.append(replacement);
        } else if (StringUtils.startsWithIgnoreCase(token, tokenToReplace)) {
            if (!Character.isLetterOrDigit(token.charAt(tokenToReplace.length()))) {
                buf.append(replacement).append(StringUtils.substringAfter(token, tokenToReplace));
            } else {
                buf.append(token);
            }
        } else {
            buf.append(token);
        }
    }
    return buf.toString();
}

From source file:adalid.util.velocity.BaseBuilder.java

private void createTextFilePropertiesFile(String source, String target) {
    boolean java = StringUtils.endsWithIgnoreCase(source, ".java");
    boolean bundle = StringUtils.endsWithIgnoreCase(source, ".properties");
    File sourceFile = new File(source);
    String sourceFileName = sourceFile.getName();
    String sourceFileSimpleName = StringUtils.substringBeforeLast(sourceFileName, ".");
    String sourceFolderName = sourceFile.getParentFile().getName();
    String sourceFolderSimpleName = StringUtils.substringBeforeLast(sourceFolderName, ".");
    String sourceEntityName = getOptionalEntityName(sourceFileSimpleName, sourceFolderSimpleName);
    String properties = source.replace(projectFolderPath, velocityPlatformsTargetFolderPath) + ".properties";
    String folder = StringUtils.substringBeforeLast(properties, FS);
    String template = StringUtils.substringAfter(target, velocityFolderPath + FS).replace(FS, "/");
    String path = StringUtils.substringBeforeLast(StringUtils.substringAfter(source, projectFolderPath), FS)
            .replace(FS, "/").replace(project, PROJECT_ALIAS).replace("eclipse.settings", ".settings");
    path = replaceAliasWithRootFolderName(path);
    String pack = null;// www.jav  a 2 s.  c o m
    if (java || bundle) {
        String s1 = StringUtils.substringAfter(path, SRC);
        if (StringUtils.contains(s1, PROJECT_ALIAS)) {
            String s2 = StringUtils.substringBefore(s1, PROJECT_ALIAS);
            String s3 = SRC + s2;
            String s4 = StringUtils.substringBefore(path, s3) + s3;
            String s5 = StringUtils.substringAfter(s1, PROJECT_ALIAS).replace("/", ".");
            path = StringUtils.removeEnd(s4, "/");
            pack = ROOT_PACKAGE_NAME + s5;
        }
    }
    path = finalisePath(path);
    String file = StringUtils.substringAfterLast(source, FS).replace(project, PROJECT_ALIAS)
            .replace("eclipse.project", ".project");
    List<String> lines = new ArrayList<>();
    lines.add("template = " + template);
    //      lines.add("template-type = velocity");
    lines.add("path = " + path);
    if (StringUtils.isNotBlank(pack)) {
        lines.add("package = " + pack);
    }
    lines.add("file = " + file);
    if (sourceFileSimpleName.equals("eclipse") || sourceFolderSimpleName.equals("eclipse")
            || sourceFolderSimpleName.equals("nbproject")) {
        lines.add("disabled = true");
    } else if (sourceEntityName != null) {
        lines.add("disabled-when-missing = " + sourceEntityName);
    }
    if (source.endsWith(".css") || source.endsWith(".jrtx")) {
        lines.add("preserve = true");
    } else if (ArrayUtils.contains(preservableFiles, sourceFileName)) {
        lines.add("preserve = true");
    }
    lines.add("dollar.string = $");
    lines.add("pound.string = #");
    lines.add("backslash.string = \\\\");
    FilUtils.mkdirs(folder);
    if (write(properties, lines, WINDOWS_CHARSET)) {
        propertiesFilesCreated++;
    }
}

From source file:com.amalto.core.delegator.IItemCtrlDelegator.java

public ArrayList<String> getItems(DataClusterPOJOPK dataClusterPOJOPK, String conceptName, IWhereItem whereItem,
        int spellThreshold, String orderBy, String direction, int start, int limit,
        boolean totalCountOnFirstRow) throws XtentisException {
    isExistDataCluster(dataClusterPOJOPK);
    Server server = ServerContext.INSTANCE.get();
    StorageAdmin storageAdmin = server.getStorageAdmin();
    String dataContainerName = dataClusterPOJOPK.getUniqueId();
    Storage storage = storageAdmin.get(dataContainerName, storageAdmin.getType(dataContainerName));
    MetadataRepository repository = storage.getMetadataRepository();
    ComplexTypeMetadata type = repository.getComplexType(conceptName);
    if (type == null) {
        throw new IllegalArgumentException("Type '" + conceptName + "' does not exist in data cluster '" //$NON-NLS-1$ //$NON-NLS-2$
                + dataContainerName + "'."); //$NON-NLS-1$
    }/* w  ww. java  2s.c o m*/
    UserQueryBuilder qb = UserQueryBuilder.from(type);
    // Condition and paging
    qb.where(UserQueryHelper.buildCondition(qb, whereItem, repository));
    qb.start(start < 0 ? 0 : start); // UI can send negative start index
    qb.limit(limit);
    // Order by
    if (orderBy != null) {
        String orderByFieldName = StringUtils.substringAfter(orderBy, "/"); //$NON-NLS-1$
        List<TypedExpression> fields = UserQueryHelper.getFields(type, orderByFieldName);
        if (fields == null) {
            throw new IllegalArgumentException("Field '" + orderBy + "' does not exist."); //$NON-NLS-1$ //$NON-NLS-2$
        }
        OrderBy.Direction queryDirection;
        if ("ascending".equals(direction) //$NON-NLS-1$
                || "NUMBER:ascending".equals(direction) //$NON-NLS-1$
                || "ASC".equals(direction)) { //$NON-NLS-1$
            queryDirection = OrderBy.Direction.ASC;
        } else {
            queryDirection = OrderBy.Direction.DESC;
        }
        for (TypedExpression typedExpression : fields) {
            qb.orderBy(typedExpression, queryDirection);
        }
    }
    // Get records
    ArrayList<String> resultsAsString = new ArrayList<String>();
    StorageResults results;
    try {
        storage.begin();
        if (totalCountOnFirstRow) {
            results = storage.fetch(qb.getSelect());
            resultsAsString.add("<totalCount>" + results.getCount() + "</totalCount>"); //$NON-NLS-1$ //$NON-NLS-2$
        }
        results = storage.fetch(qb.getSelect());
        DataRecordWriter writer = new DataRecordXmlWriter(type);
        writer.setSecurityDelegator(SecuredStorage.getDelegator());
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        for (DataRecord result : results) {
            try {
                if (totalCountOnFirstRow) {
                    output.write("<result>".getBytes()); //$NON-NLS-1$
                }
                writer.write(result, output);
                if (totalCountOnFirstRow) {
                    output.write("</result>".getBytes()); //$NON-NLS-1$
                }
            } catch (IOException e) {
                throw new XtentisException(e);
            }
            String document = new String(output.toByteArray());
            resultsAsString.add(document);
            output.reset();
        }
        storage.commit();
    } catch (Exception e) {
        storage.rollback();
        throw new XtentisException(e);
    }
    return resultsAsString;
}

From source file:eionet.cr.web.action.factsheet.FactsheetActionBean.java

/**
 * Helper method for updating dcterms:modified if the given subject has been updated (i.e. triples added or deleted).
 *
 * @param currSubj The subject's DTO as it is currently in the repository.
 * @param types The subject's RDF types.
 * @param sourceUri The graph URI where the dcterms:modified should be updated.
 * @throws DAOException if any sort of DB error happens
 *//* ww  w  .j av a 2 s .c  o  m*/
private void updateDctModified(SubjectDTO currSubj, Collection<String> types, String sourceUri)
        throws DAOException {

    if (currSubj == null || StringUtils.isBlank(sourceUri)) {
        return;
    }

    String dctModifiedSubjectUri = null;

    if (types.contains(Subjects.DATACUBE_DATA_SET)) {
        dctModifiedSubjectUri = uri;
    } else if (types.contains(Subjects.DATACUBE_OBSERVATION)) {
        if (currSubj != null) {
            List<String> datasetUris = currSubj.getObjectValues(Predicates.DATACUBE_DATA_SET);
            if (datasetUris != null && !datasetUris.isEmpty()) {
                dctModifiedSubjectUri = datasetUris.iterator().next();
            }
        }
    } else if (uri.contains(CODELIST_SUBSTRING)) {
        String tail = StringUtils.substringAfter(uri, CODELIST_SUBSTRING);
        int i = tail.indexOf('/');
        if (i < 0) {
            dctModifiedSubjectUri = uri;
        } else {
            dctModifiedSubjectUri = StringUtils.substringBefore(uri, CODELIST_SUBSTRING) + CODELIST_SUBSTRING
                    + tail.substring(0, i);
        }
    }

    if (StringUtils.isNotBlank(dctModifiedSubjectUri)) {
        DAOFactory.get().getDao(ScoreboardSparqlDAO.class).updateDcTermsModified(dctModifiedSubjectUri,
                new Date(), sourceUri);
    }
}

From source file:com.opengamma.component.ComponentManager.java

/**
 * Intelligently sets the property which is a component reference.
 * <p>/*  w  w  w .j  a v a 2 s. co m*/
 * The double colon is used in the format {@code Type::Classifier}.
 * If the type is omitted, this method will try to infer it.
 * 
 * @param bean  the bean, not null
 * @param mp  the property, not null
 * @param value  the configured value containing double colon, not null
 */
protected void setPropertyComponentRef(Bean bean, MetaProperty<?> mp, String value) {
    Class<?> propertyType = mp.propertyType();
    String type = StringUtils.substringBefore(value, "::");
    String classifier = StringUtils.substringAfter(value, "::");
    if (type.length() == 0) {
        try {
            // infer type
            mp.set(bean, getRepository().getInstance(propertyType, classifier));
            return;
        } catch (RuntimeException ex) {
            throw new OpenGammaRuntimeException(
                    "Unable to set property " + mp + " of type " + propertyType.getName(), ex);
        }
    }
    ComponentInfo info = getRepository().findInfo(type, classifier);
    if (info == null) {
        throw new OpenGammaRuntimeException(
                "Unable to find component reference '" + value + "' while setting property " + mp);
    }
    if (ComponentInfo.class.isAssignableFrom(propertyType)) {
        mp.set(bean, info);
    } else {
        mp.set(bean, getRepository().getInstance(info));
    }
}

From source file:com.prowidesoftware.swift.model.field.Field.java

/**
 * Finds the first component starting with the given codeword between slashes, and returns the component subvalue.
 * For example, for the following field value<br />
 * /ACC/BLABLABLA CrLf<br />/* www. jav  a2  s .c  o m*/
 * //BLABLABLA CrLf<br />
 * /INS/CITIUS33MIA CrLf<br />
 * //BLABLABLA CrLf<br />
 * A call to this method with parameter "INS" will return "CITIUS33MIA"
 *
 * @param codeword
 * @see #findComponentStartingWith(String)
 * @return the found value or <code>null</code> if not found
 */
public String getValueByCodeword(final String codeword) {
    final String key = "/" + codeword + "/";
    final String c = findComponentStartingWith(key);
    if (c != null) {
        return StringUtils.substringAfter(c, key);
    }
    return null;
}

From source file:com.cubusmail.mail.imap.IMAPMailbox.java

/**
 * @throws MessagingException//  w  ww .  j av a2s .c  o  m
 */
private void loadMailFolder() throws MessagingException {

    logger.debug("loading folder tree...");
    long millis = System.currentTimeMillis();
    this.mailFolderMap.clear();
    this.mailFolderList.clear();
    Folder defaultFolder = this.store.getDefaultFolder();
    this.folderSeparator = defaultFolder.getSeparator();

    // read all folders to a map
    List<String> topFolderNames = new ArrayList<String>();
    Folder[] allFolders = defaultFolder.list("*");
    if (allFolders != null && allFolders.length > 0) {
        for (Folder folder : allFolders) {
            this.mailFolderMap.put(folder.getFullName(), createMailFolder(folder));
            if (SessionManager.get().getPreferences().getInboxFolderName().equals(folder.getFullName())) {
                topFolderNames.add(0, SessionManager.get().getPreferences().getInboxFolderName());
            } else {
                String folderName = folder.getFullName();
                if (!StringUtils.isEmpty(this.personalNameSpace)
                        && folderName.startsWith(this.personalNameSpace)) {
                    folderName = StringUtils.substringAfter(folderName, this.personalNameSpace);
                }
                if (StringUtils.countMatches(folderName, String.valueOf(getFolderSeparator())) == 0) {
                    topFolderNames.add(folder.getFullName());
                }
            }
        }
    }

    // build the tree structure
    for (String folderName : topFolderNames) {
        IMailFolder mailFolder = this.mailFolderMap.get(folderName);
        this.mailFolderList.add(mailFolder);
        if (!SessionManager.get().getPreferences().getInboxFolderName().equals(folderName)
                && mailFolder.hasChildren()) {
            mailFolder.setSubfolders(getSubfolders(mailFolder));
        }
    }

    logger.debug("...finish: " + (System.currentTimeMillis() - millis) + "ms");
}

From source file:com.hangum.tadpole.mongodb.core.query.MongoDBQuery.java

/**
 * list index//www. j av a2s . co  m
 * 
 * @param userDB
 * @throws Exception
 */
public static List<MongoDBIndexDAO> listAllIndex(UserDBDAO userDB) throws Exception {
    List<MongoDBIndexDAO> listReturnIndex = new ArrayList<MongoDBIndexDAO>();

    DB mongoDB = MongoConnectionManager.getInstance(userDB);
    for (String col : mongoDB.getCollectionNames()) {

        if (!isSystemCollection(col)) {
            List<DBObject> listIndexObj = mongoDB.getCollection(col).getIndexInfo();
            for (DBObject dbObject : listIndexObj) {
                MongoDBIndexDAO indexDao = new MongoDBIndexDAO();

                indexDao.setV(dbObject.get("v").toString());
                Map<String, Object> objMap = (Map) dbObject.get("key");
                for (String strKey : objMap.keySet()) {
                    indexDao.getListIndexField()
                            .add(new MongoDBIndexFieldDAO(strKey, objMap.get(strKey).toString()));
                }

                if (dbObject.containsField("unique")) {
                    indexDao.setUnique(Boolean.valueOf(dbObject.get("unique").toString()));
                }
                String strNs = dbObject.get("ns").toString();
                strNs = StringUtils.substringAfter(strNs, userDB.getDb() + ".");

                indexDao.setNs(strNs);
                indexDao.setName(dbObject.get("name").toString());

                listReturnIndex.add(indexDao);
            }
        }
    }

    return listReturnIndex;
}

From source file:adalid.util.velocity.SecondBaseBuilder.java

private void createTextFilePropertiesFile(String source, String target) {
    boolean java = StringUtils.endsWithIgnoreCase(source, ".java");
    boolean bundle = StringUtils.endsWithIgnoreCase(source, ".properties");
    File sourceFile = new File(source);
    String sourceFileName = sourceFile.getName();
    String sourceFileSimpleName = StringUtils.substringBeforeLast(sourceFileName, ".");
    String sourceFolderName = sourceFile.getParentFile().getName();
    String sourceFolderSimpleName = StringUtils.substringBeforeLast(sourceFolderName, ".");
    String sourceEntityName = getOptionalEntityName(sourceFileSimpleName, sourceFolderSimpleName);
    String properties = source.replace(projectFolderPath, velocityPlatformsTargetFolderPath) + ".properties";
    String folder = StringUtils.substringBeforeLast(properties, FS);
    String template = StringUtils.substringAfter(target, velocityFolderPath + FS).replace(FS, "/");
    String path = StringUtils.substringBeforeLast(StringUtils.substringAfter(source, projectFolderPath), FS)
            .replace(FS, "/").replace(project, PROJECT_ALIAS).replace("eclipse.settings", ".settings");
    path = replaceAliasWithRootFolderName(path);
    String pack = null;/*  ww  w .j a v a  2s. co m*/
    if (java || bundle) {
        String s1 = StringUtils.substringAfter(path, SRC);
        if (StringUtils.contains(s1, PROJECT_ALIAS)) {
            String s2 = StringUtils.substringBefore(s1, PROJECT_ALIAS);
            String s3 = SRC + s2;
            String s4 = StringUtils.substringBefore(path, s3) + s3;
            String s5 = StringUtils.substringAfter(s1, PROJECT_ALIAS).replace("/", ".");
            path = StringUtils.removeEnd(s4, "/");
            pack = ROOT_PACKAGE_NAME + s5;
        }
    }
    path = finalisePath(path);
    String file = StringUtils.substringAfterLast(source, FS).replace(project, PROJECT_ALIAS)
            .replace("eclipse.project", ".project");
    List<String> lines = new ArrayList<>();
    lines.add("template = " + template);
    //      lines.add("template-type = velocity");
    lines.add("path = " + path);
    if (StringUtils.isNotBlank(pack)) {
        lines.add("package = " + pack);
    }
    lines.add("file = " + file);
    if (sourceFileSimpleName.equals("eclipse") || sourceFolderSimpleName.equals("eclipse")
            || sourceFolderSimpleName.equals("nbproject")) {
        lines.add("disabled = true");
    } else if (sourceEntityName != null) {
        lines.add("disabled-when-missing = " + sourceEntityName);
    }
    if (preservable(sourceFile)) {
        lines.add("preserve = true");
    }
    lines.add("dollar.string = $");
    lines.add("pound.string = #");
    lines.add("backslash.string = \\\\");
    FilUtils.mkdirs(folder);
    if (write(properties, lines, WINDOWS_CHARSET)) {
        propertiesFilesCreated++;
    }
}