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

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

Introduction

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

Prototype

public static String substring(final String str, int start) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

A negative start position can be used to start n characters from the end of the String.

A null String will return null .

Usage

From source file:ro.dabuno.office.integration.MailMerge.java

private void applyLines(Data dataIn, XWPFDocument doc) throws XmlException, IOException {
    CTBody body = doc.getDocument().getBody();

    XmlOptions optionsOuter = new XmlOptions();
    optionsOuter.setSaveOuter();/*from  ww w .  j  ava2  s .  co  m*/

    // read the current full Body text
    String srcString = body.xmlText();

    // apply the replacements
    boolean first = true;
    List<String> headers = dataIn.getHeaders();
    for (List<String> data : dataIn.getData()) {
        log.info("Applying to template: " + data);

        String replaced = srcString;
        for (int fieldNr = 0; fieldNr < headers.size(); fieldNr++) {
            String header = headers.get(fieldNr);
            String value = data.get(fieldNr);

            // ignore columns without headers as we cannot match them
            if (header == null) {
                continue;
            }

            // use empty string for data-cells that have no value
            if (value == null) {
                value = "";
            }

            replaced = replaced.replace("${" + header + "}", value);
        }

        // check for missed replacements or formatting which interferes
        if (replaced.contains("${")) {
            log.warn("Still found template-marker after doing replacement: "
                    + StringUtils.abbreviate(StringUtils.substring(replaced, replaced.indexOf("${")), 200));
        }

        appendBody(body, replaced, first);

        first = false;
    }
}

From source file:Singletons.HeuristicsLoader.java

@PostConstruct
public void load() {
    Categories.populate();//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:software.coolstuff.springframework.owncloud.service.impl.AbstractOwncloudServiceTest.java

private String merge(String templateName, Context context) throws IOException {
    String prefixedTemplateName = templateName;
    if (!StringUtils.startsWith(templateName, VELOCITY_PATH_PREFIX)) {
        prefixedTemplateName = VELOCITY_PATH_PREFIX + templateName;
        if (StringUtils.startsWith(templateName, "/")) {
            prefixedTemplateName = VELOCITY_PATH_PREFIX + StringUtils.substring(templateName, 1);
        }/*from   www. j  a v  a 2 s.  c  om*/
    }
    Template template = velocityEngine.getTemplate(prefixedTemplateName);
    try (Writer writer = new StringWriter()) {
        template.merge(context, writer);
        writer.flush();
        return writer.toString();
    }
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceTest.java

private Path resolveRelativePath(Path relativePath) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    ResourceServiceProperties resourceProperties = properties.getResourceService();
    Path basePath = resourceProperties.getLocation().resolve(authentication.getName());
    if (relativePath.isAbsolute()) {
        String relativizedPath = StringUtils.substring(relativePath.toString(), File.pathSeparator.length());
        return basePath.resolve(relativizedPath);
    }//  w  ww. ja v  a2s.c  o  m
    return basePath.resolve(relativePath);
}

From source file:software.coolstuff.springframework.owncloud.service.impl.rest.AbstractOwncloudRestServiceImpl.java

protected String getAuthorizationUserFromHeaders(HttpHeaders headers) {
    Validate.notNull(headers);/*w w  w . j a  va  2  s . c  om*/

    List<String> authorizations = headers.get(HttpHeaders.AUTHORIZATION);
    if (CollectionUtils.isEmpty(authorizations)) {
        return null;
    }

    String encodedCredentials = authorizations.get(0);
    if (StringUtils.startsWith(encodedCredentials, AUTHORIZATION_METHOD_PREFIX)) {
        encodedCredentials = StringUtils.substring(encodedCredentials, AUTHORIZATION_METHOD_PREFIX.length());
    }
    final byte[] rawDecodedCredentials = Base64.getDecoder().decode(encodedCredentials.getBytes());
    final String decodedCredentials = new String(rawDecodedCredentials);
    if (!StringUtils.contains(decodedCredentials, ':')) {
        return null;
    }
    return StringUtils.split(decodedCredentials, ':')[0];
}

From source file:sqalibur.SQaLibur.java

/**
 * behandelt alle Anfragetypen und whlt die entsprechende Unterfunktion
 *
 * @param request  die eingehende Anfrage
 * @param response das Antwortobjekt/*ww w  .j  a v a 2s .  c o  m*/
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out;
    try {
        out = response.getWriter();
    } catch (IOException ex) {
        Logger.getLogger(SQaLibur.class.getName()).log(Level.SEVERE, null, ex);
        response.setStatus(500);
        return;
    }

    String a = request.getRequestURI();
    int b = request.getContextPath().length();
    String pathInfo = StringUtils.substring(a, b);
    String method = request.getMethod();

    try {
        Matcher matcher;
        for (int i = 0; i < restPattern.length; i++) {
            String[] pattern = restPattern[i];
            if (method == null ? pattern[0] != null : !method.equals(pattern[0])) {
                continue;
            }
            Pattern regExGetCommands = Pattern.compile(pattern[1]);
            matcher = regExGetCommands.matcher(pathInfo);
            if (matcher.find()) {
                if (restCommands[i] != null) {
                    restCommands[i].execute(getServletContext(), request, response);
                }
                return;
            }
        }

    } catch (Exception e) {
        try {
            response.sendError(409);
        } catch (IOException ex) {
            Logger.getLogger(SQaLibur.class.getName()).log(Level.SEVERE, null, ex);
            response.setStatus(500);
        }
    } finally {
        out.close();
    }
}

From source file:ubic.gemma.web.services.Gene2GoTermEndpoint.java

/**
 * @param regularIds - input collection will be unchanged
 * @return - collection of GO ids, without the "GO:" infront, only the numeric portion of the id is returned
 *//*from  w ww .j a  v a2  s.  co m*/
private Collection<String> retainNumericIds(Collection<String> regularIds) {
    Collection<String> numericIds = new ArrayList<String>();
    for (String id : regularIds) {
        numericIds.add(StringUtils.substring(id, 3));
    }
    return numericIds;

}