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

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

Introduction

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

Prototype

public static String substringAfterLast(String str, String separator) 

Source Link

Document

Gets the substring after the last occurrence of a separator.

Usage

From source file:adalid.commons.velocity.VelocityEngineer.java

private static String getTemplateEncoding(String filename) {
    //      String substring = StringUtils.substringAfterLast(filename, "/");
    //      if (StringUtils.isBlank(substring)) {
    //          return VELOCITY_TEMPLATE_DEFAULT_ENCODING;
    //      }/*from   w  ww.j  a  v  a 2  s. c  o m*/
    //      String extension = StringUtils.substringAfter(substring, ".");
    String extension = StringUtils.substringAfterLast(filename, ".");
    if (StringUtils.isBlank(extension)) {
        return VELOCITY_TEMPLATE_DEFAULT_ENCODING;
    }
    String key = VELOCITY_TEMPLATE_ENCODING + "." + extension.toLowerCase();
    String property = supplementaryProperties.getProperty(key, VELOCITY_TEMPLATE_DEFAULT_ENCODING);
    String encoding = StringUtils.isBlank(property) ? VELOCITY_TEMPLATE_DEFAULT_ENCODING : property;
    return encoding;
}

From source file:com.intuit.tank.harness.functions.JexlStringFunctions.java

private String[] internalSubstringsBetween(String subject, String open, String close) {
    String[] ret = null;//from  www . j  a va  2  s . c  o  m
    if (subject != null && open == null && close != null) {
        ret = new String[] { StringUtils.substringBefore(subject, close) };
    } else if (subject != null && open != null && close == null) {
        ret = new String[] { StringUtils.substringAfterLast(subject, open) };
    } else {
        ret = StringUtils.substringsBetween(subject, open, close);
    }
    return ret != null ? ret : new String[0];
}

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);
        }//from  w  w  w  . j a v  a  2s. com
        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:edu.ku.brc.af.core.db.DBTableInfo.java

/**
 * Converts the Column Name to a field name and returns the FieldInfo
 * @param columnName the name of the column
 * @return the field info/*  w w  w  .j  a  va2s . co m*/
 */
public DBFieldInfo getFieldByColumnName(final String columnName, final boolean suppressError) {
    String fName = columnName.indexOf('.') > -1 ? StringUtils.substringAfterLast(columnName, ".") : columnName; //$NON-NLS-1$
    String fieldName = fName.substring(0, 1).toLowerCase() + fName.substring(1, fName.length());
    DBFieldInfo fi = getFieldByName(fieldName);
    if (fi == null) {
        if (!suppressError && !fieldName.endsWith("ID")) //$NON-NLS-1$
        {
            log.error("Couldn't find FieldName[" + fieldName + "] in table [" + getTitle() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }
    }
    return fi;
}

From source file:com.mediaworx.intellij.opencmsplugin.opencms.OpenCmsModule.java

/**
 * checks if the given path is under the local VFS root
 *
 * @param path the path to check/*from w  w  w  .j a  va 2 s.  c o m*/
 * @return <code>true</code> if the path is contained in the local VFS root, <code>false</code> otherwise
 */
public boolean isPathInVFSPath(String path) {
    String filename = StringUtils.substringAfterLast(path, "/");
    if (VfsFileAnalyzer.fileOrPathIsIgnored(plugin.getPluginConfiguration(), path, filename)) {
        return false;
    }
    return path.startsWith(localVfsRoot);
}

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  .  j  av a 2  s  .c  o m*/
 * @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.adobe.acs.commons.wcm.impl.PropertyMergePostProcessor.java

/**
 * Merges the values found in the the source properties into the destination
 * property as a multi-value. The values of the source properties and
 * destination properties must all be the same property type.
 *
 * The unique set of properties will be stored in
 *
 * @param resource the resource to look for the source and destination
 * properties on/*from w  w w  .j ava2 s  . c  o  m*/
 * @param destination the property to store the collected properties.
 * @param sources the properties to collect values from for merging
 * @param typeHint the data type that should be used when reading and
 * storing the data
 * @param allowDuplicates true to allow duplicates values in the destination
 * property; false to make values unique
 * @return Optional resource updated, if any
 */
protected final <T> Optional<Resource> merge(final Resource resource, final String destination,
        final Collection<String> sources, final Class<T> typeHint, final boolean allowDuplicates)
        throws PersistenceException {

    ResourceResolver rr = resource.getResourceResolver();

    // Create an empty array of type T
    @SuppressWarnings("unchecked")
    final T[] emptyArray = (T[]) Array.newInstance(typeHint, 0);

    Collection<T> collectedValues;

    if (allowDuplicates) {
        collectedValues = new ArrayList<>();
    } else {
        collectedValues = new LinkedHashSet<>();
    }

    for (final String source : sources) {
        Resource sourceProperties = resource;
        String sourceParam = source;
        if (source.contains("/")) {
            sourceParam = StringUtils.substringAfterLast(source, "/");
            sourceProperties = rr.getResource(resource, StringUtils.substringBeforeLast(source, "/"));
        }
        T[] tmp = sourceProperties.adaptTo(ModifiableValueMap.class).get(sourceParam, emptyArray);
        collectedValues.addAll(Arrays.asList(tmp));
    }

    Resource targetResource = resource;
    String targetProperty = destination;
    if (destination.contains("/")) {
        targetProperty = StringUtils.substringAfterLast(destination, "/");
        targetResource = rr.getResource(resource, StringUtils.substringBeforeLast(destination, "/"));
    }
    ModifiableValueMap targetProperties = targetResource.adaptTo(ModifiableValueMap.class);

    final T[] currentValues = targetProperties.get(targetProperty, emptyArray);

    if (!collectedValues.equals(Arrays.asList(currentValues))) {
        targetProperties.put(targetProperty, collectedValues.toArray(emptyArray));

        return Optional.of(targetResource);
    } else {
        return Optional.empty();
    }
}

From source file:eionet.gdem.dcm.business.QAScriptManager.java

/**
 * Update script properties.//from  w w w. j a va 2s.  c  o m
 *
 * @param user logged in user name.
 * @param scriptId QA script Id.
 * @param shortName QA script short name.
 * @param schemaId XML Schema Id.
 * @param resultType QA script execution result type (XML, HTML, ...).
 * @param descr QA script textual description.
 * @param scriptType QA script type (XQUERY, XSL, XGAWK).
 * @param curFileName QA script file name.
 * @param content File content
 * @param updateContent Update content
 * @throws DCMException If an error occurs.
 */
public void update(String user, String scriptId, String shortName, String schemaId, String resultType,
        String descr, String scriptType, String curFileName, String upperLimit, String url, String content,
        boolean updateContent) throws DCMException {
    try {
        if (!SecurityUtil.hasPerm(user, "/" + Names.ACL_QUERIES_PATH, "u")) {
            throw new DCMException(BusinessConstants.EXCEPTION_AUTORIZATION_QASCRIPT_UPDATE);
        }
    } catch (DCMException e) {
        throw e;
    } catch (Exception e) {
        LOGGER.error("Error updating QA script", e);
        throw new DCMException(BusinessConstants.EXCEPTION_GENERAL);
    }

    if (Utils.isNullStr(scriptId) || Utils.isNullStr(schemaId)) {
        LOGGER.error("Cannot update QA script. Script ID or schema ID is empty.");
        throw new DCMException(BusinessConstants.EXCEPTION_GENERAL);
    }

    try {
        if (!Utils.isNullStr(curFileName) && !Utils.isNullStr(content)
                && content.indexOf(Constants.FILEREAD_EXCEPTION) == -1 && updateContent) {

            // create backup of existing file
            BackupManager bum = new BackupManager();
            bum.backupFile(Properties.queriesFolder, curFileName, scriptId, user);

            Utils.saveStrToFile(Properties.queriesFolder + File.separator + curFileName, content, null);
        }

        // If the script type is 'FME' update the 'fileName'
        if (XQScript.SCRIPT_LANG_FME.equals(scriptType)) {
            curFileName = StringUtils.substringAfterLast(url, "/");
        }

        queryDao.updateQuery(scriptId, schemaId, shortName, descr, curFileName, resultType, scriptType,
                upperLimit, url);
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("Error updating QA script", e);
        throw new DCMException(BusinessConstants.EXCEPTION_GENERAL);
    }

}

From source file:com.doculibre.constellio.wicket.panels.results.DefaultSearchResultPanel.java

public DefaultSearchResultPanel(String id, SolrDocument doc, final SearchResultsDataProvider dataProvider) {
    super(id);//from  w  ww .ja v  a2s  . c o  m

    RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordServices recordServices = ConstellioSpringUtils.getRecordServices();
    SearchInterfaceConfigServices searchInterfaceConfigServices = ConstellioSpringUtils
            .getSearchInterfaceConfigServices();

    String collectionName = dataProvider.getSimpleSearch().getCollectionName();

    RecordCollection collection = collectionServices.get(collectionName);
    Record record = recordServices.get(doc);
    if (record != null) {
        SearchInterfaceConfig searchInterfaceConfig = searchInterfaceConfigServices.get();

        IndexField uniqueKeyField = collection.getUniqueKeyIndexField();
        IndexField defaultSearchField = collection.getDefaultSearchIndexField();
        IndexField urlField = collection.getUrlIndexField();
        IndexField titleField = collection.getTitleIndexField();

        if (urlField == null) {
            urlField = uniqueKeyField;
        }
        if (titleField == null) {
            titleField = urlField;
        }

        final String recordURL = record.getUrl();
        final String displayURL;

        if (record.getDisplayUrl().startsWith("/get?file=")) {
            HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest();
            displayURL = ContextUrlUtils.getContextUrl(req) + record.getDisplayUrl();

        } else {
            displayURL = record.getDisplayUrl();
        }

        String title = record.getDisplayTitle();

        final String protocol = StringUtils.substringBefore(displayURL, ":");
        boolean linkEnabled = isLinkEnabled(protocol);

        // rcupration des champs highlight  partir de la cl unique
        // du document, dans le cas de Nutch c'est l'URL
        QueryResponse response = dataProvider.getQueryResponse();
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        Map<String, List<String>> fieldsHighlighting = highlighting.get(recordURL);

        String titleHighlight = getTitleFromHighlight(titleField.getName(), fieldsHighlighting);
        if (titleHighlight != null) {
            title = titleHighlight;
        }

        String excerpt = null;
        String description = getDescription(record);
        String summary = getSummary(record);

        if (StringUtils.isNotBlank(description) && searchInterfaceConfig.isDescriptionAsExcerpt()) {
            excerpt = description;
        } else {
            excerpt = getExcerptFromHighlight(defaultSearchField.getName(), fieldsHighlighting);
            if (excerpt == null) {
                excerpt = description;
            }
        }

        toggleSummaryLink = new WebMarkupContainer("toggleSummaryLink");
        add(toggleSummaryLink);
        toggleSummaryLink.setVisible(StringUtils.isNotBlank(summary));
        toggleSummaryLink.add(new AttributeModifier("onclick", new LoadableDetachableModel() {
            @Override
            protected Object load() {
                return "toggleSearchResultSummary('" + summaryLabel.getMarkupId() + "')";
            }
        }));

        summaryLabel = new Label("summary", summary);
        add(summaryLabel);
        summaryLabel.setOutputMarkupId(true);
        summaryLabel.setVisible(StringUtils.isNotBlank(summary));

        ExternalLink titleLink;
        if (displayURL.startsWith("file://")) {
            HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest();
            String newDisplayURL = ContextUrlUtils.getContextUrl(req) + "app/getSmbFile?"
                    + SmbServletPage.RECORD_ID + "=" + record.getId() + "&" + SmbServletPage.COLLECTION + "="
                    + collectionName;
            titleLink = new ExternalLink("titleLink", newDisplayURL);
        } else {
            titleLink = new ExternalLink("titleLink", displayURL);
        }

        final RecordModel recordModel = new RecordModel(record);
        AttributeModifier computeClickAttributeModifier = new AttributeModifier("onmousedown", true,
                new LoadableDetachableModel() {
                    @Override
                    protected Object load() {
                        Record record = recordModel.getObject();
                        SimpleSearch simpleSearch = dataProvider.getSimpleSearch();
                        WebRequest webRequest = (WebRequest) RequestCycle.get().getRequest();
                        HttpServletRequest httpRequest = webRequest.getHttpServletRequest();
                        return ComputeSearchResultClickServlet.getCallbackJavascript(httpRequest, simpleSearch,
                                record);
                    }
                });
        titleLink.add(computeClickAttributeModifier);
        titleLink.setEnabled(linkEnabled);

        boolean resultsInNewWindow;
        PageParameters params = RequestCycle.get().getPageParameters();
        if (params != null && params.getString(POPUP_LINK) != null) {
            resultsInNewWindow = params.getBoolean(POPUP_LINK);
        } else {
            resultsInNewWindow = searchInterfaceConfig.isResultsInNewWindow();
        }
        titleLink.add(new SimpleAttributeModifier("target", resultsInNewWindow ? "_blank" : "_self"));

        // Add title
        title = StringUtils.remove(title, "\n");
        title = StringUtils.remove(title, "\r");
        if (StringUtils.isEmpty(title)) {
            title = StringUtils.defaultString(displayURL);
            title = StringUtils.substringAfterLast(title, "/");
            title = StringUtils.substringBefore(title, "?");
            try {
                title = URLDecoder.decode(title, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (title.length() > 120) {
                title = title.substring(0, 120) + " ...";
            }
        }

        Label titleLabel = new Label("title", title);
        titleLink.add(titleLabel.setEscapeModelStrings(false));
        add(titleLink);

        Label excerptLabel = new Label("excerpt", excerpt);
        add(excerptLabel.setEscapeModelStrings(false));
        // add(new ExternalLink("url", url,
        // url).add(computeClickAttributeModifier).setEnabled(linkEnabled));
        if (displayURL.startsWith("file://")) {
            // Creates a Windows path for file URLs
            String urlLabel = StringUtils.substringAfter(displayURL, "file:");
            urlLabel = StringUtils.stripStart(urlLabel, "/");
            urlLabel = "\\\\" + StringUtils.replace(urlLabel, "/", "\\");
            try {
                urlLabel = URLDecoder.decode(urlLabel, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            add(new Label("url", urlLabel));
        } else {
            add(new Label("url", displayURL));
        }

        final ReloadableEntityModel<RecordCollection> collectionModel = new ReloadableEntityModel<RecordCollection>(
                collection);
        add(new ListView("searchResultFields", new LoadableDetachableModel() {
            @Override
            protected Object load() {
                RecordCollection collection = collectionModel.getObject();
                return collection.getSearchResultFields();
            }

            /**
             * Detaches from the current request. Implement this method with
             * custom behavior, such as setting the model object to null.
             */
            protected void onDetach() {
                recordModel.detach();
                collectionModel.detach();
            }
        }) {
            @Override
            protected void populateItem(ListItem item) {
                SearchResultField searchResultField = (SearchResultField) item.getModelObject();
                IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices();
                Record record = recordModel.getObject();
                IndexField indexField = searchResultField.getIndexField();
                Locale locale = getLocale();
                String indexFieldTitle = indexField.getTitle(locale);
                if (StringUtils.isBlank(indexFieldTitle)) {
                    indexFieldTitle = indexField.getName();
                }
                StringBuffer fieldValueSb = new StringBuffer();
                List<Object> fieldValues = indexFieldServices.extractFieldValues(record, indexField);
                Map<String, String> defaultLabelledValues = indexFieldServices
                        .getDefaultLabelledValues(indexField, locale);
                for (Object fieldValue : fieldValues) {
                    if (fieldValueSb.length() > 0) {
                        fieldValueSb.append("\n");
                    }
                    String fieldValueLabel = indexField.getLabelledValue("" + fieldValue, locale);
                    if (fieldValueLabel == null) {
                        fieldValueLabel = defaultLabelledValues.get("" + fieldValue);
                    }
                    if (fieldValueLabel == null) {
                        fieldValueLabel = "" + fieldValue;
                    }
                    fieldValueSb.append(fieldValueLabel);
                }

                item.add(new Label("indexField", indexFieldTitle));
                item.add(new MultiLineLabel("indexFieldValue", fieldValueSb.toString()));
                item.setVisible(fieldValueSb.length() > 0);
            }

            @SuppressWarnings("unchecked")
            @Override
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    List<SearchResultField> searchResultFields = (List<SearchResultField>) getModelObject();
                    visible = !searchResultFields.isEmpty();
                }
                return visible;
            }
        });

        // md5
        ConstellioSession session = ConstellioSession.get();
        ConstellioUser user = session.getUser();
        // TODO Provide access to unauthenticated users ?
        String md5 = "";
        if (user != null) {
            IntelliGIDServiceInfo intelligidServiceInfo = ConstellioSpringUtils.getIntelliGIDServiceInfo();
            if (intelligidServiceInfo != null) {
                Collection<Object> md5Coll = doc.getFieldValues(IndexField.MD5);
                if (md5Coll != null) {
                    for (Object md5Obj : md5Coll) {
                        try {
                            String md5Str = new String(Hex.encodeHex(Base64.decodeBase64(md5Obj.toString())));
                            InputStream is = HttpClientHelper
                                    .get(intelligidServiceInfo.getIntelligidUrl() + "/connector/checksum",
                                            "md5=" + URLEncoder.encode(md5Str, "ISO-8859-1"),
                                            "username=" + URLEncoder.encode(user.getUsername(), "ISO-8859-1"),
                                            "password=" + URLEncoder.encode(Base64.encodeBase64String(
                                                    ConstellioSession.get().getPassword().getBytes())),
                                            "ISO-8859-1");
                            try {
                                Document xmlDocument = new SAXReader().read(is);
                                Element root = xmlDocument.getRootElement();
                                for (Iterator<Element> it = root.elementIterator("fichier"); it.hasNext();) {
                                    Element fichier = it.next();
                                    String url = fichier.attributeValue("url");
                                    md5 += "<a href=\"" + url + "\">" + url + "</a> ";
                                }
                            } finally {
                                IOUtils.closeQuietly(is);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        Label md5Label = new Label("md5", md5) {
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    visible = StringUtils.isNotBlank(this.getModelObjectAsString());
                }
                return visible;
            }
        };
        md5Label.setEscapeModelStrings(false);
        add(md5Label);

        add(new ElevatePanel("elevatePanel", record, dataProvider.getSimpleSearch()));
    } else {
        setVisible(false);
    }
}

From source file:adalid.commons.velocity.VelocityEngineer.java

private static String getDocumentEncoding(String filename) {
    //      String substring = StringUtils.substringAfterLast(filename, FILE_SEPARATOR);
    //      if (StringUtils.isBlank(substring)) {
    //          return VELOCITY_DOCUMENT_DEFAULT_ENCODING;
    //      }//from   ww  w . ja v a 2 s  . co m
    //      String extension = StringUtils.substringAfter(substring, ".");
    String extension = StringUtils.substringAfterLast(filename, ".");
    if (StringUtils.isBlank(extension)) {
        return VELOCITY_DOCUMENT_DEFAULT_ENCODING;
    }
    String key = VELOCITY_DOCUMENT_ENCODING + "." + extension.toLowerCase();
    String property = supplementaryProperties.getProperty(key, VELOCITY_DOCUMENT_DEFAULT_ENCODING);
    String encoding = StringUtils.isBlank(property) ? VELOCITY_DOCUMENT_DEFAULT_ENCODING : property;
    return encoding;
}