Example usage for org.apache.commons.lang3 StringUtils left

List of usage examples for org.apache.commons.lang3 StringUtils left

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils left.

Prototype

public static String left(final String str, final int len) 

Source Link

Document

Gets the leftmost len characters of a String.

If len characters are not available, or the String is null , the String will be returned without an exception.

Usage

From source file:org.tightblog.rendering.processors.CommentProcessor.java

WeblogEntryComment createCommentFromRequest(HttpServletRequest request, WeblogPageRequest pageRequest,
        HTMLSanitizer.Level sanitizerLevel) {

    /*/*from  ww  w .  j  a v  a 2 s  . c om*/
     * Convert request parameters into a WeblogEntryComment object.  Params used:
     *   name - comment author
     *   email - comment email
     *   url - comment referring url
     *   content - comment contents
     *   notify - if commenter wants to receive notifications
     */
    WeblogEntryComment comment = new WeblogEntryComment();
    comment.setNotify(request.getParameter("notify") != null);
    comment.setName(Utilities.removeHTML(request.getParameter("name")));
    comment.setEmail(Utilities.removeHTML(request.getParameter("email")));
    comment.setWeblogEntry(pageRequest.getWeblogEntry());
    comment.setRemoteHost(request.getRemoteHost());
    comment.setPostTime(Instant.now());
    comment.setBlogger(pageRequest.getBlogger());

    String previewCheck = request.getParameter("preview");
    comment.setPreview(previewCheck != null && !"false".equalsIgnoreCase(previewCheck));

    // Validate url
    comment.setUrl(Utilities.removeHTML(request.getParameter("url")));
    String urlCheck = comment.getUrl();
    if (StringUtils.isNotBlank(urlCheck)) {
        urlCheck = urlCheck.trim().toLowerCase();
        if (!urlCheck.startsWith("http://") && !urlCheck.startsWith("https://")) {
            urlCheck = "http://" + urlCheck;
        }
        comment.setUrl(urlCheck);
    }

    // Validate content
    String rawComment = request.getParameter("content");

    if (StringUtils.isNotBlank(rawComment)) {
        comment.setContent(StringUtils.left(rawComment, 2000));

        Whitelist commentHTMLWhitelist = sanitizerLevel.getWhitelist();

        // Need to insert paragraph breaks in case commenter didn't do so.
        String commentTemp = Utilities.insertLineBreaksIfMissing(comment.getContent());

        // Remove HTML tags outside those permitted by the TightBlog admin
        comment.setContent(Jsoup.clean(commentTemp, commentHTMLWhitelist));
    }

    return comment;
}

From source file:org.wise.portal.dao.user.impl.HibernateUserDao.java

/**
 * Capitalizes the first letter of a given String
 * /*from  www. j  a v a  2 s.c  om*/
 * @param string
 * @return String
 */
private String capitalizeFirst(String string) {
    return StringUtils.upperCase(StringUtils.left(string, 1)) + StringUtils.right(string, string.length() - 1);
}

From source file:org.xwiki.messagestream.internal.DefaultMessageStream.java

/**
 * Creates an {@link Event} object with the common fields filled in: event ID, target document, application, user...
 * It also fills in the provided message body and type.
 * /*from  w  w  w .j a v  a  2 s  .c  om*/
 * @param message the message to store in the event; at most 2000 characters are stored, longer messages are
 *            automatically trimmed
 * @param messageType the type of message
 * @return the initialized event object
 */
protected Event createMessageEvent(String message, String messageType) {
    Event e = this.factory.createEvent();
    e.setApplication("MessageStream");
    e.setDocument(new DocumentReference(this.context.getCurrentEntityReference().getRoot().getName(), "XWiki",
            e.getId()));
    e.setBody(StringUtils.left(message, 2000));
    e.setType(messageType);
    return e;
}

From source file:org.zanata.dao.GlossaryDAO.java

/**
 * Perform lucene search in HGlossaryTerm in srcLocale
 * Object[0] - Float score//from   w w w .  j a v a2 s  . co m
 * Object[1] - HGlossaryTerm srcTerm
 */
public List<Object[]> getSearchResult(String searchText, SearchType searchType, LocaleId srcLocale,
        final int maxResult, String qualifiedName) throws ParseException {
    if (StringUtils.length(searchText) > LuceneQuery.QUERY_MAX_LENGTH) {
        throw new RuntimeException("Query string exceed max length: " + LuceneQuery.QUERY_MAX_LENGTH + "='"
                + StringUtils.left(searchText, 80) + "'");
    }

    String queryText;

    switch (searchType) {
    case RAW:
        queryText = searchText;
        break;
    case FUZZY:
        // search by N-grams
        queryText = QueryParser.escape(searchText);
        break;
    case EXACT:
        queryText = "\"" + QueryParser.escape(searchText) + "\"";
        break;
    default:
        throw new RuntimeException("Unknown query type: " + searchType);
    }
    if (StringUtils.isEmpty(queryText)) {
        return Lists.newArrayList();
    }
    QueryParser parser = new QueryParser("content", new StandardAnalyzer());
    org.apache.lucene.search.Query textQuery = parser.parse(queryText);

    TermQuery qualifiedNameQuery = new TermQuery(
            new Term(IndexFieldLabels.GLOSSARY_QUALIFIED_NAME, qualifiedName));

    BooleanQuery booleanQuery = new BooleanQuery.Builder().add(textQuery, BooleanClause.Occur.MUST)
            .add(qualifiedNameQuery, BooleanClause.Occur.MUST).build();

    FullTextQuery ftQuery = entityManager.createFullTextQuery(booleanQuery, HGlossaryTerm.class);
    ftQuery.enableFullTextFilter("glossaryLocaleFilter").setParameter("locale", srcLocale);
    ftQuery.setProjection(FullTextQuery.SCORE, FullTextQuery.THIS);
    @SuppressWarnings("unchecked")
    List<Object[]> matches = ftQuery.setMaxResults(maxResult).getResultList();
    return matches;
}

From source file:org.zanata.service.impl.GlossarySearchServiceImpl.java

@Override
public ArrayList<GlossaryResultItem> searchGlossary(@Nonnull LocaleId srcLocale, @Nonnull LocaleId transLocale,
        @Nonnull String searchText, @Nonnull SearchType searchType, int maxResults,
        @CheckForNull String projectSlug) {

    ArrayList<GlossaryResultItem> results;
    try {/*  w  w  w  . j av  a  2  s.com*/
        Map<GlossaryKey, GlossaryResultItem> matchesMap = Maps.newLinkedHashMap();

        if (projectSlug != null) {
            String projQualifiedName = ProjectService.getGlossaryQualifiedName(projectSlug);
            List<Object[]> projMatches = glossaryDAO.getSearchResult(searchText, searchType, srcLocale,
                    maxResults, projQualifiedName);
            processMatches(projMatches, matchesMap, searchText, transLocale, projQualifiedName);
        }
        List<Object[]> globalMatches = glossaryDAO.getSearchResult(searchText, searchType, srcLocale,
                maxResults, GlossaryUtil.GLOBAL_QUALIFIED_NAME);
        processMatches(globalMatches, matchesMap, searchText, transLocale, GlossaryUtil.GLOBAL_QUALIFIED_NAME);
        results = Lists.newArrayList(matchesMap.values());
    } catch (ParseException e) {
        String errorMessage;
        if (e.getCause() instanceof BooleanQuery.TooManyClauses) {
            errorMessage = "BooleanQuery.TooManyClauses, query too long to parse \'"
                    + StringUtils.left(searchText, 80) + "...\'";
        } else if (searchType == SearchType.FUZZY) {
            errorMessage = "Can not parse fuzzy query \"" + searchText + "\"";
        } else {
            errorMessage = "Can not parse query \"" + searchText + "\"";
        }
        throw new ZanataServiceException(errorMessage, e);
    }
    Collections.sort(results, COMPARATOR);
    return results;
}

From source file:org.zanata.service.impl.TranslationMemoryServiceImpl.java

/**
 * return match[0] = (float)score, match[1] = entity(HTextFlowTarget or
 * TransMemoryUnit)/*from   w ww . j av  a  2  s.c o m*/
 *
 * @param targetLocaleId
 * @param sourceLocaleId
 * @param transMemoryQuery
 * @param maxResults
 */
private Collection<Object[]> findMatchingTranslation(LocaleId targetLocaleId, LocaleId sourceLocaleId,
        TransMemoryQuery transMemoryQuery, int maxResults, Optional<Long> textFlowTargetId,
        @Nonnull Class<?>... entityTypes) {
    try {
        if (entityTypes == null || entityTypes.length == 0) {
            throw new RuntimeException(
                    "Need entity type (HTextFlowTarget.class or TransMemoryUnit.class) for TM search");
        }
        List<Object[]> matches = getSearchResult(transMemoryQuery, sourceLocaleId, targetLocaleId, maxResults,
                textFlowTargetId, entityTypes);
        // filter out invalid target
        // TODO filter by entityTypes as well
        // TODO returning a filtered collection might be overkill
        return Collections2.filter(matches, new ValidTargetFilterPredicate(targetLocaleId));
    } catch (ParseException e) {
        if (e.getCause() instanceof BooleanQuery.TooManyClauses) {
            log.warn("BooleanQuery.TooManyClauses, query too long to parse \'"
                    + StringUtils.left(transMemoryQuery.getQueries().get(0), 80) + "...\'");
        } else {
            if (transMemoryQuery.getSearchType() == HasSearchType.SearchType.RAW) {
                // TODO tell the user
                log.info("Can\'t parse raw query {}", transMemoryQuery);
            } else {
                // escaping failed!
                log.error("Can\'t parse query " + transMemoryQuery, e);
            }
        }
    } catch (RuntimeException e) {
        log.error("Runtime exception:", e);
    }
    return Lists.newArrayList();
}

From source file:org.zanata.service.impl.TranslationMemoryServiceImpl.java

private void validateQueryLength(String query) {
    if (StringUtils.length(query) > LuceneQuery.QUERY_MAX_LENGTH) {
        throw new RuntimeException("Query string exceed max length: " + LuceneQuery.QUERY_MAX_LENGTH + "=\'"
                + StringUtils.left(query, 80) + "\'");
    }/*w  ww .j  a va 2s  .c  o m*/
}

From source file:Singletons.HeuristicsLoader.java

@PostConstruct
public void load() {
    Categories.populate();//from  w ww.  j  a  va  2 s  . c  om

    Set<File> setPathResources = new TreeSet();
    //        setPathResources.addAll(FacesContext.getCurrentInstance().getExternalContext().getResourcePaths("/resources/private/"));
    //        File file = new File ("/usr/sharedfilesapps/lexicons");
    File file;
    if (Parameters.local) {
        file = new File(
                "H:\\Docs Pro Clement\\NetBeansProjects\\Umigon_mavenized\\src\\main\\webapp\\resources\\private\\");
    } else {
        file = new File("/usr/sharedfilesapps/lexicons");
    }
    File[] files = file.listFiles();
    setPathResources.addAll(Arrays.asList(files));
    //        System.out.println("folder is: " + folder.getCanonicalPath());
    mapHeuristics = new HashMap();
    setNegations = new HashSet();
    setTimeTokens = new HashSet();
    setFalsePositiveOpinions = new HashSet();
    setIronicallyPositive = new HashSet();
    setModerators = new HashSet();
    mapH1 = new HashMap();
    mapH2 = new HashMap();
    mapH4 = new HashMap();
    mapH3 = new HashMap();
    mapH5 = new HashMap();
    mapH6 = new HashMap();
    mapH7 = new HashMap();
    mapH8 = new HashMap();
    mapH9 = new HashMap();
    mapH10 = new HashMap();
    mapH11 = new HashMap();
    mapH12 = new HashMap();
    mapH13 = new HashMap();

    //        for (File file : arrayFiles) {
    for (File filezz : setPathResources) {
        try {
            InputStream inp = new FileInputStream(filezz.getPath());
            br = new BufferedReader(new InputStreamReader(inp));
            if (!filezz.getPath().contains("_")) {
                continue;
            }
            String fileName;
            if (Parameters.local) {
                fileName = StringUtils.substring(filezz.getPath(),
                        StringUtils.lastIndexOf(filezz.getPath(), "\\") + 1);
            } else {
                fileName = StringUtils.substring(filezz.getPath(),
                        StringUtils.lastIndexOf(filezz.getPath(), "/") + 1);
            }

            int map = Integer.parseInt(StringUtils.left(fileName, fileName.indexOf("_")));
            if (map == 0) {
                continue;
            }
            //            System.out.println("map: " + map);
            //            System.out.println("loading " + pathFile);
            //            System.out.println("folder is: " + folder.getCanonicalPath());

            String term = null;
            String featureString;
            String feature;
            String rule = null;
            String fields[];
            String[] parametersArray;
            String[] featuresArray;
            Set<String> featuresSet;
            Iterator<String> featuresSetIterator;
            String field0;
            String field1;
            String field2;
            //mapFeatures:
            //key: a feature
            //value: a set of parameters for the given feature
            Multimap<String, Set<String>> mapFeatures;
            while ((string = br.readLine()) != null) {
                fields = string.split("\t", -1);
                mapFeatures = HashMultimap.create();

                //sometimes the heuristics is just a term, not followed by a feature or a rule
                //in this case put a null value to these fields
                field0 = fields[0].trim();
                if (field0.isEmpty()) {
                    continue;
                }
                field1 = (fields.length < 2) ? null : fields[1].trim();
                field2 = (fields.length < 3) ? null : fields[2].trim();

                term = field0;
                featureString = field1;
                rule = field2;

                //parse the "feature" field to disentangle the feature from the parameters
                //this parsing rule will be extended to allow for multiple features
                //                if (featureString.contains("+++")) {
                //                    System.out.println("featureString containing +++ " + featureString);
                //                }
                featuresArray = featureString.split("\\+\\+\\+");
                featuresSet = new HashSet(Arrays.asList(featuresArray));
                featuresSetIterator = featuresSet.iterator();
                while (featuresSetIterator.hasNext()) {
                    featureString = featuresSetIterator.next();
                    //                    System.out.println("featureString: " + featureString);
                    //                    if (featureString.contains("///")) {
                    //                        System.out.println("featureString containing ||| " + featureString);
                    //                    }
                    if (featureString.contains("///")) {
                        parametersArray = StringUtils.substringAfter(featureString, "///").split("\\|");
                        feature = StringUtils.substringBefore(featureString, "///");
                        mapFeatures.put(feature, new HashSet(Arrays.asList(parametersArray)));
                    } else {
                        mapFeatures.put(featureString, null);
                    }
                }

                //                if (term.equals("I was wondering")){
                //                    System.out.println("HERE!!!!");
                //                }
                //                System.out.println("feature: "+feature);
                heuristic = new Heuristic();
                heuristic.generateNewHeuristic(term, mapFeatures, rule);
                mapHeuristics.put(term, heuristic);
                //positive
                if (map == 1) {
                    mapH1.put(term, heuristic);
                    continue;
                }
                //negative
                if (map == 2) {
                    mapH2.put(term, heuristic);
                    continue;
                }
                //strong
                if (map == 3) {
                    mapH3.put(term, heuristic);
                    continue;
                }
                //time
                if (map == 4) {
                    mapH4.put(term, heuristic);
                    continue;
                }
                //question
                if (map == 5) {
                    mapH5.put(term, heuristic);
                    continue;
                }
                //subjective
                if (map == 6) {
                    mapH6.put(term, heuristic);
                    continue;
                }
                //address
                if (map == 7) {
                    mapH7.put(term, heuristic);
                    continue;
                }
                //humor
                if (map == 8) {
                    mapH8.put(term, heuristic);
                    continue;
                }
                //commercial offer
                if (map == 9) {
                    mapH9.put(term, heuristic);
                    continue;
                }
                //negations
                if (map == 10) {
                    setNegations.add(term);
                    continue;
                }
                //hints difficulty
                if (map == 11) {
                    mapH11.put(term, heuristic);
                    continue;
                }
                //time indications
                if (map == 12) {
                    setTimeTokens.add(term);
                    continue;
                }
                //time indications
                if (map == 13) {
                    mapH13.put(term, heuristic);
                    continue;
                }
                //set of terms which look like opinions but are false postives
                if (map == 12) {
                    setFalsePositiveOpinions.add(term);
                    continue;
                }
                //set of terms which look like opinions but are false postives
                if (map == 15) {
                    setIronicallyPositive.add(term);
                    continue;
                }

                //set of moderators
                if (map == 16) {
                    setModerators.add(term);
                    continue;
                }

            }
            br.close();
        } //        System.out.println(
          //                "total number heuristics used: " + mapHeuristics.keySet().size());
          //        System.out.println(
          //                "--------------------------------------------");
          //
          //        System.out.println(
          //                "positive tone: " + mapH1.keySet().size());
          //        System.out.println(
          //                "negative tone: " + mapH2.keySet().size());
          //        System.out.println(
          //                "strength of opinion: " + mapH3.keySet().size());
          //        System.out.println(
          //                "time related: " + mapH4.keySet().size());
          //        System.out.println(
          //                "question: " + mapH5.keySet().size());
          //        System.out.println(
          //                "self turned: " + mapH6.keySet().size());
          //        System.out.println(
          //                "humor or light: " + mapH8.keySet().size());
          //        System.out.println(
          //                "direct address: " + mapH7.keySet().size());
          //        System.out.println(
          //                "commercial offer: " + mapH9.keySet().size());
        catch (IOException ex) {
            Logger.getLogger(HeuristicsLoader.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

From source file:storybook.toolkit.swing.SwingUtil.java

public static String getShortenString(String str, int length) {
    if (str.length() > length)
        return StringUtils.left(str, length) + " ...";
    return str;/*from   www.  j  a va2s . co  m*/
}

From source file:storybook.toolkit.TextUtil.java

public static String truncateString(String str, int length) {
    if (str == null) {
        return "";
    }/*from  w  w w . j a va  2  s. co  m*/
    if (str.length() > length) {
        return StringUtils.left(str, length) + " ...";
    }
    return str;
}