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

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

Introduction

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

Prototype

public static String substringBeforeLast(String str, String separator) 

Source Link

Document

Gets the substring before the last occurrence of a separator.

Usage

From source file:com.evolveum.midpoint.notifications.api.events.ModelEvent.java

public String getFocusTypeName() {
    if (getFocusContext() == null || getFocusContext().getObjectTypeClass() == null) {
        return null;
    }//from w  ww .ja  v a 2s.c  o m
    String simpleName = getFocusContext().getObjectTypeClass().getSimpleName();
    return StringUtils.substringBeforeLast(simpleName, "Type"); // should usually work ;)
}

From source file:gov.nih.nci.caarray.security.SecurityUtils.java

static InstanceLevelMappingElement findMappingElement(String className, String attributeName) {
    final String packageName = StringUtils.substringBeforeLast(className, ".");
    final String objectName = StringUtils.substringAfterLast(className, ".");

    for (final InstanceLevelMappingElement elt : Arrays.asList(projectMapping, sampleMapping)) {
        if (packageName.equals(elt.getObjectPackageName()) && objectName.equals(elt.getObjectName())
                && attributeName.equals(elt.getAttributeName())) {
            return elt;
        }//from www.ja va2 s .  c o  m
    }
    return null;
}

From source file:info.magnolia.cms.core.DefaultHierarchyManager.java

/**
 * Like getContent() but creates the node if not yet existing. Attention save is not called!
 * @param path the path of the node//from   ww  w.jav a  2  s  .co  m
 * @param create true if the node should get created
 * @param type the node type of the created node
 * @return the node
 * @throws AccessDeniedException
 * @throws RepositoryException
 */
@Override
public Content getContent(String path, boolean create, ItemType type)
        throws AccessDeniedException, RepositoryException {
    Content node;
    try {
        node = getContent(path);
    } catch (PathNotFoundException e) {
        if (create) {
            node = this.createContent(StringUtils.substringBeforeLast(path, "/"),
                    StringUtils.substringAfterLast(path, "/"), type.toString());
            AuditLoggingUtil.log(AuditLoggingUtil.ACTION_CREATE, getWorkspaceName(), node.getItemType(),
                    node.getHandle());
        } else {
            throw e;
        }
    }
    return node;
}

From source file:com.google.gdt.eclipse.designer.uibinder.parser.UiBinderParser.java

/**
 * @return the parent for given "child" path, may be <code>null</code> if root.
 *///from w  ww.  ja v a2s. c  o  m
private XmlObjectInfo findParent(String childPath) {
    String parentPath = StringUtils.substringBeforeLast(childPath, "/");
    for (Map.Entry<String, XmlObjectInfo> entry : m_pathToModelMap.entrySet()) {
        String path = entry.getKey();
        XmlObjectInfo parent = entry.getValue();
        if (path.equals(parentPath)) {
            return parent;
        }
    }
    if (childPath.contains("/")) {
        return findParent(parentPath);
    }
    return null;
}

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

private boolean copyBinaryFiles() {
    Collection<File> files = FileUtils.listFiles(projectFolder, binaryFileFilter(), binaryDirFilter());
    //      ColUtils.sort(files);
    String source, target, folder;
    for (File file : files) {
        source = file.getPath();//from  w w w .j av  a  2  s .  c o  m
        target = source.replace(projectFolderPath, velocityTemplatesTargetFolderPath);
        folder = StringUtils.substringBeforeLast(target, FS);
        FilUtils.mkdirs(folder);
        try {
            copy(source, target);
            binaryFilesCopied++;
        } catch (IOException ex) {
            writingErrors++;
            logger.fatal(ex);
            logger.fatal("\t" + source + " could not be copied ");
        }
    }
    return true;
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.conll.Conll2012Writer.java

private void convert(JCas aJCas, PrintWriter aOut) {
    Map<Token, Collection<SemanticPredicate>> predIdx = indexCovered(aJCas, Token.class,
            SemanticPredicate.class);
    Map<SemanticArgument, Collection<Token>> argIdx = indexCovered(aJCas, SemanticArgument.class, Token.class);
    Map<Token, Collection<NamedEntity>> neIdx = indexCovering(aJCas, Token.class, NamedEntity.class);
    Map<Token, Collection<WordSense>> wordSenseIdx = indexCovered(aJCas, Token.class, WordSense.class);
    Map<Token, Collection<CoreferenceLink>> corefIdx = indexCovering(aJCas, Token.class, CoreferenceLink.class);
    Map<CoreferenceLink, Integer> corefChainIdx = new HashMap<>();

    int chainId = 1;
    for (CoreferenceChain chain : select(aJCas, CoreferenceChain.class)) {
        for (CoreferenceLink link : chain.links()) {
            corefChainIdx.put(link, chainId);
        }//  www .j  a v  a 2  s  .c  o m
        chainId++;
    }

    for (Sentence sentence : select(aJCas, Sentence.class)) {
        HashMap<Token, Row> ctokens = new LinkedHashMap<Token, Row>();

        // Tokens
        List<Token> tokens = selectCovered(Token.class, sentence);

        List<SemanticPredicate> preds = selectCovered(SemanticPredicate.class, sentence);

        String[] parseFragments = null;
        List<ROOT> root = selectCovered(ROOT.class, sentence);
        if (root.size() == 1) {
            PennTreeNode rootNode = PennTreeUtils.convertPennTree(root.get(0));
            if ("ROOT".equals(rootNode.getLabel())) {
                rootNode.setLabel("TOP");
            }
            parseFragments = toPrettyPennTree(rootNode);
        }

        if (parseFragments != null && parseFragments.length != tokens.size()) {
            throw new IllegalStateException("Parse fragments do not match tokens - tokens: " + tokens
                    + " parse: " + asList(parseFragments));
        }

        for (int i = 0; i < tokens.size(); i++) {
            Row row = new Row();
            row.id = i;
            row.token = tokens.get(i);
            row.args = new SemanticArgument[preds.size()];
            row.parse = parseFragments != null ? parseFragments[i] : UNUSED;

            // If there are multiple semantic predicates for the current token, then 
            // we keep only the first
            Collection<SemanticPredicate> predsForToken = predIdx.get(row.token);
            if (predsForToken != null && !predsForToken.isEmpty()) {
                row.pred = predsForToken.iterator().next();
            }

            // If there are multiple named entities for the current token, we keep only the
            // first
            Collection<NamedEntity> neForToken = neIdx.get(row.token);
            if (neForToken != null && !neForToken.isEmpty()) {
                row.ne = neForToken.iterator().next();
            }

            // If there are multiple word senses for the current token, we keep only the
            // first
            Collection<WordSense> senseForToken = wordSenseIdx.get(row.token);
            if (senseForToken != null && !senseForToken.isEmpty()) {
                row.wordSense = senseForToken.iterator().next();
            }

            row.coref = corefIdx.get(row.token);

            ctokens.put(row.token, row);
        }

        // Semantic arguments
        for (int p = 0; p < preds.size(); p++) {
            FSArray args = preds.get(p).getArguments();
            for (SemanticArgument arg : select(args, SemanticArgument.class)) {
                for (Token t : argIdx.get(arg)) {
                    Row row = ctokens.get(t);
                    row.args[p] = arg;
                }
            }
        }

        // Write sentence in CONLL 2012 format
        for (Row row : ctokens.values()) {
            String documentId = DocumentMetaData.get(aJCas).getDocumentId();
            if (StringUtils.isBlank(documentId)) {
                documentId = UNUSED;
            }

            int partNumber = 0;

            if (documentId.contains("#")) {
                partNumber = Integer.parseInt(StringUtils.substringAfterLast(documentId, "#"));
                documentId = StringUtils.substringBeforeLast(documentId, "#");
            }

            int id = row.id;

            String form = row.token.getCoveredText();

            String lemma = UNUSED + " ";
            if (writeLemma && (row.token.getLemma() != null)) {
                lemma = row.token.getLemma().getValue();
            }

            String pos = UNUSED;
            if (writePos && (row.token.getPos() != null)) {
                POS posAnno = row.token.getPos();
                pos = posAnno.getPosValue();
            }

            String parse = row.parse;
            if (!parse.endsWith(")")) {
                // This is just the curious way that the CoNLL files are encoded...
                parse += " ";
            }

            String wordSense = UNUSED;
            if (row.wordSense != null) {
                wordSense = row.wordSense.getValue();
            }

            String speaker = UNUSED; // FIXME

            String namedEntity = ALT_UNUSED + " ";
            if (row.ne != null) {
                namedEntity = encodeMultiTokenAnnotation(row.token, row.ne, row.ne.getValue());
            }

            String pred = UNUSED;
            StringBuilder apreds = new StringBuilder();
            if (writeSemanticPredicate) {
                if (row.pred != null) {
                    pred = row.pred.getCategory();
                }

                for (SemanticArgument arg : row.args) {

                    if (apreds.length() > 0) {
                        apreds.append("             ");
                    }

                    String value;
                    if (arg == null) {
                        if (row.pred != null && row.pred.getBegin() == row.token.getBegin()
                                && row.pred.getEnd() == row.token.getEnd()) {
                            value = "(V*)";
                        } else {
                            value = ALT_UNUSED + ' ';
                        }
                    } else {
                        value = encodeMultiTokenAnnotation(row.token, arg, arg.getRole());
                    }
                    apreds.append(String.format("%10s", value));
                }
            }

            StringBuilder coref = new StringBuilder();
            if (!row.coref.isEmpty()) {
                for (CoreferenceLink link : row.coref) {
                    if (coref.length() > 0) {
                        coref.append('|');
                    }
                    coref.append(encodeMultiTokenLink(row.token, link, corefChainIdx.get(link)));
                }
            }
            if (coref.length() == 0) {
                coref.append(UNUSED);
            }

            aOut.printf("%s %3d %3d %10s %5s %13s %9s %3s %3s %10s %10s %10s %s\n", documentId, partNumber, id,
                    form, pos, parse, lemma, pred, wordSense, speaker, namedEntity, apreds, coref);
        }

        aOut.println();
    }

    aOut.println("#end document");
}

From source file:com.adobe.acs.commons.rewriter.impl.VersionedClientlibsTransformerFactory.java

private String getVersionedPath(final String originalPath, final LibraryType libraryType,
        final ResourceResolver resourceResolver) {
    try {/*from   w w  w .  j  av  a 2 s  .c  om*/
        boolean appendMinSelector = false;
        String libraryPath = StringUtils.substringBeforeLast(originalPath, ".");
        if (libraryPath.endsWith(MIN_SELECTOR_SEGMENT)) {
            appendMinSelector = true;
            libraryPath = StringUtils.substringBeforeLast(libraryPath, ".");
        }

        final HtmlLibrary htmlLibrary = getLibrary(libraryType, libraryPath, resourceResolver);

        if (htmlLibrary != null) {
            StringBuilder builder = new StringBuilder();
            builder.append(libraryPath);
            builder.append(".");

            if (appendMinSelector) {
                builder.append(MIN_SELECTOR).append(".");
            }
            if (enforceMd5) {
                builder.append(MD5_PREFIX);
            }
            builder.append(getMd5(htmlLibrary));
            builder.append(libraryType.extension);

            return builder.toString();
        } else {
            log.debug("Could not find HtmlLibrary at path: {}", libraryPath);
            return null;
        }
    } catch (Exception ex) {
        // Handle unexpected formats of the original path
        log.error("Attempting to get a versioned path for [ {} ] but could not because of: {}", originalPath,
                ex.getMessage());
        return originalPath;
    }
}

From source file:info.magnolia.cms.core.DefaultHierarchyManager.java

/**
 * get NodeData object of the requested URI.
 * @param path of the atom to be initialized
 * @return NodeData/*from  w w  w. jav  a  2s .  c om*/
 * @throws javax.jcr.PathNotFoundException
 * @throws javax.jcr.RepositoryException
 */
@Override
public NodeData getNodeData(String path)
        throws PathNotFoundException, RepositoryException, AccessDeniedException {
    if (StringUtils.isEmpty(path)) {
        return null;
    }
    final String nodePath = StringUtils.substringBeforeLast(path, "/");
    final String nodeDataName = StringUtils.substringAfterLast(path, "/");
    return getContent(nodePath).getNodeData(nodeDataName);
}

From source file:com.haulmont.yarg.reporting.Reporting.java

protected String resolveOutputFileName(Report report, ReportTemplate reportTemplate, BandData rootBand) {
    String outputNamePattern = reportTemplate.getOutputNamePattern();
    String outputName = reportTemplate.getDocumentName();
    Pattern pattern = Pattern.compile("\\$\\{([A-z0-9_]+)\\.([A-z0-9_]+)\\}");
    if (StringUtils.isNotBlank(outputNamePattern)) {
        Matcher matcher = pattern.matcher(outputNamePattern);
        if (matcher.find()) {
            String bandName = matcher.group(1);
            String paramName = matcher.group(2);

            BandData bandWithFileName = null;
            if (BandData.ROOT_BAND_NAME.equals(bandName)) {
                bandWithFileName = rootBand;
            } else {
                bandWithFileName = rootBand.findBandRecursively(bandName);
            }/*w w w  .  j  a v a2 s. co  m*/

            if (bandWithFileName != null) {
                Object fileName = bandWithFileName.getData().get(paramName);

                if (fileName == null) {
                    throw new ReportingException(format(
                            "No data in band [%s] parameter [%s] found. "
                                    + "This band and parameter is used for output file name generation.",
                            bandWithFileName, paramName));
                } else {
                    outputName = fileName.toString();
                }
            } else {
                throw new ReportingException(
                        format("No data in band [%s] found.This band is used for output file name generation.",
                                bandName));
            }
        } else {
            outputName = outputNamePattern;
        }
    }

    if (ReportOutputType.custom != reportTemplate.getOutputType()) {
        outputName = format("%s.%s", StringUtils.substringBeforeLast(outputName, "."),
                reportTemplate.getOutputType().getId());
    }

    return outputName;
}

From source file:com.lakeside.data.sqldb.PageBaseDao.java

protected String getCountSql(String originalHql) {
    QueryTranslatorImpl queryTranslator = new QueryTranslatorImpl(originalHql, originalHql,
            Collections.EMPTY_MAP, (SessionFactoryImplementor) sessionFactory);

    queryTranslator.compile(Collections.EMPTY_MAP, false);
    String fromHql = StringUtils.substringBeforeLast(queryTranslator.getSQLString(), "order by");
    return "select count(*) from (" + fromHql + ") totalcount";
}