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

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

Introduction

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

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:com.doculibre.constellio.utils.resources.WriteResourceBundleUtils.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    File binDir = ClasspathUtils.getClassesDir();
    File projectDir = binDir.getParentFile();
    File sourceDir = new File(projectDir, "source");

    String defaultLanguage;// w  ww .ja  v a2 s.  c om
    String otherLanguage;
    if (args.length > 0) {
        defaultLanguage = args[0];
        otherLanguage = args[1];
    } else {
        defaultLanguage = Locale.ENGLISH.getLanguage();
        otherLanguage = Locale.FRENCH.getLanguage();
    }

    List<File> propertiesFiles = (List<File>) FileUtils.listFiles(sourceDir, new String[] { "properties" },
            true);
    for (File propertiesFile : propertiesFiles) {
        File propertiesDir = propertiesFile.getParentFile();

        String propertiesNameWoutSuffix = StringUtils.substringBefore(propertiesFile.getName(), "_");
        propertiesNameWoutSuffix = StringUtils.substringBefore(propertiesNameWoutSuffix, ".properties");

        String noLanguageFileName = propertiesNameWoutSuffix + ".properties";
        String defaultLanguageFileName = propertiesNameWoutSuffix + "_" + defaultLanguage + ".properties";
        String otherLanguageFileName = propertiesNameWoutSuffix + "_" + otherLanguage + ".properties";

        File noLanguageFile = new File(propertiesDir, noLanguageFileName);
        File defaultLanguageFile = new File(propertiesDir, defaultLanguageFileName);
        File otherLanguageFile = new File(propertiesDir, otherLanguageFileName);

        if (defaultLanguageFile.exists() && otherLanguageFile.exists() && !noLanguageFile.exists()) {
            System.out.println(defaultLanguageFile.getPath() + " > " + noLanguageFileName);
            System.out.println(defaultLanguageFile.getPath() + " > empty file");

            defaultLanguageFile.renameTo(noLanguageFile);
            FileWriter defaultLanguageEmptyFileWriter = new FileWriter(defaultLanguageFile);
            defaultLanguageEmptyFileWriter.write("");
            IOUtils.closeQuietly(defaultLanguageEmptyFileWriter);
        }
    }
}

From source file:eu.annocultor.analyzers.SolrPropertyHitsAnalyzer.java

/**
 * @param args//  w w w.j  a va 2s .c o  m
 */
public static void main(String[] args) throws Exception {

    String solrUrl = args[0];
    SolrServer solr = new CommonsHttpSolrServer(solrUrl);

    String prefixOne = args[1];
    String prefixTwo = args[2];

    long prefixOneCount = 0;
    long prefixTwoCount = 0;

    long totalPassedCount = 0;

    for (File logLocation : FileUtils.listFiles(new File(args[3]), null, true)) {
        System.out.println("Parsing " + logLocation);

        for (String line : FileUtils.readLines(logLocation)) {
            if (StringUtils.contains(line, "FULL_RESULT_HMTL")) {
                line = StringUtils.substringAfter(line, "europeana_uri=");
                String solrDocumentId = StringUtils.substringBefore(line, ",");
                String query = extractQuery(line);
                if (StringUtils.startsWith(solrDocumentId, "http://") && isLongEnoughToCount(query)) {

                    SolrQuery solrQuery = new SolrQuery("europeana_uri:\"" + solrDocumentId + "\"");
                    QueryResponse response = solr.query(solrQuery);
                    SolrDocumentList sourceDocs = response.getResults();
                    if (sourceDocs.isEmpty()) {
                        System.out.println("Could not find object " + solrDocumentId);
                    } else {
                        SolrDocument document = sourceDocs.get(0);

                        if (hasWord(document, prefixOne, query)) {
                            prefixOneCount++;
                        } else {
                            if (hasWord(document, prefixTwo, query)) {
                                prefixTwoCount++;
                            }
                        }
                    }
                }
                totalPassedCount++;
            }
        }
        System.out.println(prefixOne + " : " + prefixOneCount + " " + prefixTwo + " : " + prefixTwoCount
                + " of total passed entries " + totalPassedCount);
    }
}

From source file:com.github.fritaly.svngraph.SvnGraph.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println(String.format("%s <input-file> <output-file>", SvnGraph.class.getSimpleName()));
        System.exit(1);/*from  w ww.j  a  v  a 2 s  .  c  o  m*/
    }

    final File input = new File(args[0]);

    if (!input.exists()) {
        throw new IllegalArgumentException(
                String.format("The given file '%s' doesn't exist", input.getAbsolutePath()));
    }

    final File output = new File(args[1]);

    final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);

    final History history = new History(document);

    final Set<String> rootPaths = history.getRootPaths();

    System.out.println(rootPaths);

    for (String path : rootPaths) {
        System.out.println(path);
        System.out.println(history.getHistory(path).getRevisions());
        System.out.println();
    }

    int count = 0;

    FileWriter fileWriter = null;
    GraphMLWriter graphWriter = null;

    try {
        fileWriter = new FileWriter(output);

        graphWriter = new GraphMLWriter(fileWriter);

        final NodeStyle tagStyle = graphWriter.getNodeStyle();
        tagStyle.setFillColor(Color.WHITE);

        graphWriter.graph();

        // map associating node labels to their corresponding node id in the graph
        final Map<String, String> nodeIdsPerLabel = new TreeMap<>();

        // the node style associated to each branch
        final Map<String, NodeStyle> nodeStyles = new TreeMap<>();

        for (Revision revision : history.getSignificantRevisions()) {
            System.out.println(revision.getNumber() + " - " + revision.getMessage());

            // TODO Render also the deletion of branches
            // there should be only 1 significant update per revision (the one with action ADD)
            for (Update update : revision.getSignificantUpdates()) {
                if (update.isCopy()) {
                    // a merge is also considered a copy
                    final RevisionPath source = update.getCopySource();

                    System.out.println(String.format("  > %s %s from %s@%d", update.getAction(),
                            update.getPath(), source.getPath(), source.getRevision()));

                    final String sourceRoot = Utils.getRootName(source.getPath());

                    if (sourceRoot == null) {
                        // skip the revisions whose associated root is
                        // null (happens whether a branch was created
                        // outside the 'branches' directory for
                        // instance)
                        System.err.println(String.format("Skipped revision %d because of a null root",
                                source.getRevision()));
                        continue;
                    }

                    final String sourceLabel = computeNodeLabel(sourceRoot, source.getRevision());

                    // create a node for the source (path, revision)
                    final String sourceId;

                    if (nodeIdsPerLabel.containsKey(sourceLabel)) {
                        // retrieve the id of the existing node
                        sourceId = nodeIdsPerLabel.get(sourceLabel);
                    } else {
                        // create the new node
                        if (Utils.isTagPath(source.getPath())) {
                            graphWriter.setNodeStyle(tagStyle);
                        } else {
                            if (!nodeStyles.containsKey(sourceRoot)) {
                                final NodeStyle style = new NodeStyle();
                                style.setFillColor(randomColor());

                                nodeStyles.put(sourceRoot, style);
                            }

                            graphWriter.setNodeStyle(nodeStyles.get(sourceRoot));
                        }

                        sourceId = graphWriter.node(sourceLabel);

                        nodeIdsPerLabel.put(sourceLabel, sourceId);
                    }

                    // and another for the newly created directory
                    final String targetRoot = Utils.getRootName(update.getPath());

                    if (targetRoot == null) {
                        System.err.println(String.format("Skipped revision %d because of a null root",
                                revision.getNumber()));
                        continue;
                    }

                    final String targetLabel = computeNodeLabel(targetRoot, revision.getNumber());

                    if (Utils.isTagPath(update.getPath())) {
                        graphWriter.setNodeStyle(tagStyle);
                    } else {
                        if (!nodeStyles.containsKey(targetRoot)) {
                            final NodeStyle style = new NodeStyle();
                            style.setFillColor(randomColor());

                            nodeStyles.put(targetRoot, style);
                        }

                        graphWriter.setNodeStyle(nodeStyles.get(targetRoot));
                    }

                    final String targetId;

                    if (nodeIdsPerLabel.containsKey(targetLabel)) {
                        // retrieve the id of the existing node
                        targetId = nodeIdsPerLabel.get(targetLabel);
                    } else {
                        // create the new node
                        if (Utils.isTagPath(update.getPath())) {
                            graphWriter.setNodeStyle(tagStyle);
                        } else {
                            if (!nodeStyles.containsKey(targetRoot)) {
                                final NodeStyle style = new NodeStyle();
                                style.setFillColor(randomColor());

                                nodeStyles.put(targetRoot, style);
                            }

                            graphWriter.setNodeStyle(nodeStyles.get(targetRoot));
                        }

                        targetId = graphWriter.node(targetLabel);

                        nodeIdsPerLabel.put(targetLabel, targetId);
                    }

                    // create an edge between the 2 nodes
                    graphWriter.edge(sourceId, targetId);
                } else {
                    System.out.println(String.format("  > %s %s", update.getAction(), update.getPath()));
                }
            }

            System.out.println();

            count++;
        }

        // Dispatch the revisions per corresponding branch
        final Map<String, Set<Long>> revisionsPerBranch = new TreeMap<>();

        for (String nodeLabel : nodeIdsPerLabel.keySet()) {
            if (nodeLabel.contains("@")) {
                final String branchName = StringUtils.substringBefore(nodeLabel, "@");
                final long revision = Long.parseLong(StringUtils.substringAfter(nodeLabel, "@"));

                if (!revisionsPerBranch.containsKey(branchName)) {
                    revisionsPerBranch.put(branchName, new TreeSet<Long>());
                }

                revisionsPerBranch.get(branchName).add(revision);
            } else {
                throw new IllegalStateException(nodeLabel);
            }
        }

        // Recreate the missing edges between revisions from a same branch
        for (String branchName : revisionsPerBranch.keySet()) {
            final List<Long> branchRevisions = new ArrayList<>(revisionsPerBranch.get(branchName));

            for (int i = 0; i < branchRevisions.size() - 1; i++) {
                final String nodeLabel1 = String.format("%s@%d", branchName, branchRevisions.get(i));
                final String nodeLabel2 = String.format("%s@%d", branchName, branchRevisions.get(i + 1));

                graphWriter.edge(nodeIdsPerLabel.get(nodeLabel1), nodeIdsPerLabel.get(nodeLabel2));
            }
        }

        graphWriter.closeGraph();

        System.out.println(String.format("Found %d significant revisions", count));
    } finally {
        if (graphWriter != null) {
            graphWriter.close();
        }
        if (fileWriter != null) {
            fileWriter.close();
        }
    }

    System.out.println("Done");
}

From source file:com.datasalt.utils.commons.URLUtils.java

public static String getBase(String url) {
    return StringUtils.substringBefore(url, "?");
}

From source file:eu.annocultor.data.destinations.RdfGraphSwapNames.java

private static String generateIdPrefix(String datasetId, String datasetModifier) {
    return StringUtils.substringBefore(datasetId, "_") + "_" + datasetModifier;
}

From source file:com.jsqlboxdemo.dispatcher.Dispatcher.java

public static void dispach(PageContext pageContext) throws Exception {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    String uri = StringUtils.substringBefore(request.getRequestURI(), ".");
    String contextPath = request.getContextPath();

    if (!StringUtils.isEmpty(contextPath))
        uri = StringUtils.substringAfter(uri, contextPath);
    if (StringUtils.isEmpty(uri) || "/".equals(uri))
        uri = "/home";

    String[] paths = StringUtils.split(uri, "/");
    String[] pathParams;/*from  ww  w.  ja  v a2  s. c  om*/
    String resource = null;
    String operation = null;

    if (paths.length >= 2) {// /team/add/100...
        resource = paths[0];
        operation = paths[1];
        pathParams = new String[paths.length - 2];
        for (int i = 2; i < paths.length; i++)
            pathParams[i - 2] = paths[i];
    } else { // /home_default
        resource = paths[0];
        pathParams = new String[0];
    }

    if (operation == null)
        operation = "default";
    StringBuilder controller = new StringBuilder("com.jsqlboxdemo.controller.").append(resource).append("$")
            .append(resource).append("_").append(operation);
    if ("POST".equals(request.getMethod()))
        controller.append("_post");

    WebBox box;
    try {
        Class boxClass = Class.forName(controller.toString());
        box = BeanBox.getPrototypeBean(boxClass);
    } catch (Exception e) {
        throw new ClassNotFoundException("There is no WebBox classs '" + controller + "' found.");
    }
    request.setAttribute("pathParams", pathParams);
    box.show(pageContext);
}

From source file:com.doculibre.constellio.utils.WebappUtils.java

public static URL getContextPathURL(HttpServletRequest httpRequest) {
    StringBuffer requestURL = httpRequest.getRequestURL();
    String contextPath = httpRequest.getContextPath();
    String requestURI = httpRequest.getRequestURI();
    String beforeContextPath = StringUtils.substringBefore(requestURL.toString(), requestURI);
    try {/*from   www  . jav  a 2  s  . c  om*/
        return new URL(beforeContextPath + contextPath);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.edm.app.auth.Auth.java

public static void robot(String robotPath) {
    BufferedReader reader = null;
    try {/*w  ww . ja v  a2s  .com*/
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(robotPath), "UTF-8"));
        String line = null;

        while ((line = reader.readLine()) != null) {
            if (StringUtils.isBlank(line)) {
                continue;
            }
            String key = StringUtils.substringBefore(line, "=");
            String val = StringUtils.substringAfter(line, "=");
            boolean r = StringUtils.equals(md5.encode(StringUtils.upperCase(key)),
                    "cebb21b542877339c40e7e8ecc96796e");
            if (StringUtils.isNotBlank(key) && r) {
                if (StringUtils.isNotBlank(val)) {
                    ROBOT = StringUtils.lowerCase(val);
                    break;
                }
            }
        }
    } catch (Exception e) {
        logger.error("(Auth:robot) error: ", e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
        }
    }
}

From source file:com.dianping.squirrel.client.util.CacheMonitorUtil.java

/**
 * ?hawk//  w  w w  .j  a va 2 s.com
 * 
 * @param errorMsg
 * @param throwable
 */
public static void logCacheError(String errorMsg, Throwable throwable) {
    String factorName = StringUtils.substringBefore(errorMsg, "[");
    int logFactorNew = getNewLogFactor(factorName);
    if (logFactorNew % logInterval == 0) {
        logger.error("Operate cache error: " + errorMsg, throwable);
    }
}

From source file:it.av.eatt.ocm.util.DateUtil.java

/**
 * Return the period passed between the actual time and the given time
 * <p>The period is approximated to the biggest field:
 * Example if the period is 2 days and 3 hours the results is: 2 days 
 * /*w w  w.  j  a  v a 2 s .  c o m*/
 * @param time
 * @return the period
 */
public static String getPeriod(long time) {
    Period period = new Period(time, System.currentTimeMillis());
    //get the substring before the first "$" separator
    return StringUtils.substringBefore(DateUtil.standard().print(period), "$");
}