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

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

Introduction

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

Prototype

public static String removeStart(String str, String remove) 

Source Link

Document

Removes a substring only if it is at the begining of a source string, otherwise returns the source string.

Usage

From source file:org.soaplab.clients.BatchTestClient.java

/*************************************************************************
 *
 * Entry point...//  w w w  . j  ava  2 s.  co m
 *
 *************************************************************************/
public static void main(String[] args) {
    try {
        BaseCmdLine cmd = getCmdLine(args, BatchTestClient.class);

        // service location and protocol parameters
        ServiceLocator mainLocator = InputUtils.getServiceLocator(cmd);

        // file(s) with the testing data (a list of tested
        // services and their inputs)
        String[] batchFiles = null;
        String batchFile = cmd.getParam("-batchfile");
        if (batchFile != null) {
            // take it from the command-line
            batchFiles = new String[] { batchFile };
        } else {
            // take it from the client configuration file
            batchFiles = ClientConfig.get().getStringArray(ClientConfig.PROP_BATCH_TEST_FILE);
        }
        if (batchFiles == null || batchFiles.length == 0) {
            log.error("A file with a list of service to test must be given. "
                    + "Use '-batchfile' or a property '" + ClientConfig.PROP_BATCH_TEST_FILE + "'.");
            System.exit(1);
        }

        // other arguments
        boolean tableReport = (cmd.hasOption("-table")
                || ClientConfig.isEnabled(ClientConfig.PROP_BATCH_REPORT_TABLE, false));
        boolean keepResults = (cmd.hasOption("-keep")
                || ClientConfig.isEnabled(ClientConfig.PROP_BATCH_KEEP_RESULTS, false));
        int maxThreads = -1;
        String strMaxThreads = cmd.getParam("-maxthreads");
        if (strMaxThreads == null)
            maxThreads = ClientConfig.getInt(ClientConfig.PROP_BATCH_MAX_THREADS, 25);
        else
            maxThreads = getInt(strMaxThreads);
        if (maxThreads < 0)
            maxThreads = 0;
        boolean oneByOne = (maxThreads == 1);

        // get a list of available services
        // (for validation purposes later)
        Set<String> services = new HashSet<String>();
        for (String name : new SoaplabBaseClient(mainLocator).getAvailableAnalyses()) {
            services.add(name);
        }

        // loop and do it...
        List<Properties> reports = Collections.synchronizedList(new ArrayList<Properties>());
        List<Thread> threads = Collections.synchronizedList(new ArrayList<Thread>());
        int countNotAvailable = 0;

        title("Progress");
        for (String file : batchFiles) {

            log.info("Using batch file " + file);

            // treat each batch file as a property configuration
            // file - together with a usual Soaplab Client
            // configuration file; this allows handling
            // substitutions of referenced properties, etc.
            CompositeConfiguration cfg = new CompositeConfiguration();
            cfg.addConfiguration(ClientConfig.get());
            cfg.addConfiguration(Config.get());
            try {
                cfg.addConfiguration(new PropertiesConfiguration(file));
            } catch (ConfigurationException e) {
                log.error("Loading batch file from '" + file + "' failed: " + e.getMessage());
                continue;
            }

            //
            for (Iterator it = cfg.getKeys(); it.hasNext();) {
                String propertyName = (String) it.next();
                if (!propertyName.startsWith(PREFIX_SERVICE_TO_TEST))
                    continue;
                String serviceName = StringUtils.removeStart(propertyName, PREFIX_SERVICE_TO_TEST);
                if (!services.contains(serviceName)) {
                    //          log.warn (serviceName + " is not available for testing");
                    countNotAvailable += 1;
                    continue;
                }
                String[] inputs = cfg.getStringArray(propertyName);
                for (String input : inputs) {
                    MyLocator locator = new MyLocator(serviceName, mainLocator);
                    locator.enableKeepResults(keepResults);
                    locator.setInputLine(input);
                    if (oneByOne) {
                        // sequential invocation
                        qmsg(String.format("%-50s", "Running " + serviceName + "... "));
                        Properties report = callService(locator, reports);
                        qmsgln("finished: " + report.getProperty(REPORT_JOB_STATUS));

                    } else {
                        // do it in parallel
                        startService(threads, locator, reports);
                        if (maxThreads > 0) {
                            // limit the number of threads
                            // (just wait for some to finish)
                            while (threads.size() >= maxThreads) {
                                try {
                                    Thread.sleep(1000);
                                } catch (Exception e) {
                                }
                            }
                        }
                    }
                }
            }
        }

        if (!oneByOne) {
            // wait for all the threads to finish
            while (threads.size() > 0) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }
        }
        msgln("");

        // report all tests
        if (tableReport)
            createTableReport(reports);

        // report results
        int countSuccessful = 0;
        int countErrors = 0;
        for (Properties report : reports) {
            if (report.containsKey(REPORT_ERROR_MESSAGE)) {
                report.remove(REPORT_STACK_TRACE);
                countErrors += 1;
                createErrorReport(report);
            } else {
                String status = report.getProperty(REPORT_JOB_STATUS);
                if (SoaplabConstants.JOB_COMPLETED.equals(status)) {
                    countSuccessful += 1;
                } else {
                    countErrors += 1;
                    createErrorReport(report);
                }
            }
        }

        // make a summary
        title("Summary");
        msgln("Successfully:  " + countSuccessful);
        msgln("Erroneously:   " + countErrors);
        msgln("Not available: " + countNotAvailable);

        exit(0);

    } catch (Throwable e) {
        processErrorAndExit(e);
    }

}

From source file:org.sonar.api.batch.fs.internal.PathPattern.java

static String sanitizeExtension(String suffix) {
    return StringUtils.lowerCase(StringUtils.removeStart(suffix, "."));
}

From source file:org.sonar.api.resources.Directory.java

public static String parseKey(String key) {
    if (StringUtils.isBlank(key)) {
        return ROOT;
    }//from   w  ww .java  2  s.  c o  m

    key = key.replace('\\', '/');
    key = StringUtils.trim(key);
    key = StringUtils.removeStart(key, Directory.SEPARATOR);
    key = StringUtils.removeEnd(key, Directory.SEPARATOR);
    return key;
}

From source file:org.sonar.api.resources.Resource.java

@CheckForNull
protected static String normalize(@Nullable String path) {
    if (StringUtils.isBlank(path)) {
        return null;
    }//from w w  w.j  a  v  a  2 s.com
    String normalizedPath = path;
    normalizedPath = normalizedPath.replace('\\', '/');
    normalizedPath = StringUtils.trim(normalizedPath);
    if (Directory.SEPARATOR.equals(normalizedPath)) {
        return Directory.SEPARATOR;
    }
    normalizedPath = StringUtils.removeStart(normalizedPath, Directory.SEPARATOR);
    normalizedPath = StringUtils.removeEnd(normalizedPath, Directory.SEPARATOR);
    return normalizedPath;
}

From source file:org.sonar.api.utils.WildcardPattern.java

/**
 * Returns true if specified value matches this pattern.
 *//*from   w  ww .  j  a  v a2 s.c o m*/
public boolean match(String value) {
    value = StringUtils.removeStart(value, "/");
    value = StringUtils.removeEnd(value, "/");
    return pattern.matcher(value).matches();
}

From source file:org.sonar.core.persistence.DefaultDatabase.java

public Properties getHibernateProperties() {
    Properties props = new Properties();

    List<String> hibernateKeys = settings.getKeysStartingWith("sonar.hibernate.");
    for (String hibernateKey : hibernateKeys) {
        props.put(StringUtils.removeStart(hibernateKey, "sonar."), settings.getString(hibernateKey));
    }//from ww w. ja  v  a2s . c o  m
    props.put(Environment.DIALECT, getDialect().getHibernateDialectClass().getName());
    props.put("hibernate.generate_statistics",
            settings.getBoolean(DatabaseProperties.PROP_HIBERNATE_GENERATE_STATISTICS));
    props.put("hibernate.hbm2ddl.auto", "validate");
    props.put(Environment.CONNECTION_PROVIDER, CustomHibernateConnectionProvider.class.getName());

    String schema = getSchema();
    if (StringUtils.isNotBlank(schema)) {
        props.put("hibernate.default_schema", schema);
    }
    return props;
}

From source file:org.sonar.core.persistence.DefaultDatabase.java

@VisibleForTesting
static Properties extractCommonsDbcpProperties(Properties properties) {
    Properties result = new Properties();
    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
        String key = (String) entry.getKey();
        if (StringUtils.startsWith(key, "sonar.jdbc.")) {
            result.setProperty(StringUtils.removeStart(key, "sonar.jdbc."), (String) entry.getValue());
        }//from w w  w  .  j a  v a2s.  c o m
    }

    // This property is required by the Ruby Oracle enhanced adapter.
    // It directly uses the Connection implementation provided by the Oracle driver
    result.setProperty("accessToUnderlyingConnectionAllowed", "true");
    return result;
}

From source file:org.sonar.db.DefaultDatabase.java

@VisibleForTesting
static Properties extractCommonsDbcpProperties(Properties properties) {
    Properties result = new Properties();
    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
        String key = (String) entry.getKey();
        if (StringUtils.startsWith(key, SONAR_JDBC)) {
            result.setProperty(StringUtils.removeStart(key, SONAR_JDBC), (String) entry.getValue());
        }/*  w  w  w . java 2 s . co m*/
    }
    return result;
}

From source file:org.sonar.dotnet.tools.commons.visualstudio.VisualStudioProject.java

/**
 * Gets the relative path of a file contained in the project. <br>
 * For example, if the visual studio project is C:/MySolution/MyProject/MyProject.csProj and the file is
 * C:/MySolution/MyProject/Dummy/Foo.cs, then the result is Dummy/Foo.cs
 * /*w ww  . j ava2  s .c  om*/
 * @param file
 *          the file whose relative path is to be computed
 * @return the relative path, or <code>null</code> if the file is not in the project subdirectories
 */
public String getRelativePath(File file) {
    File canonicalDirectory;
    try {
        canonicalDirectory = directory.getCanonicalFile();

        File canonicalFile = file.getCanonicalFile();

        String filePath = canonicalFile.getPath();
        String directoryPath = canonicalDirectory.getPath();
        if (!filePath.startsWith(directoryPath)) {
            // The file is not in the directory
            return null;
        }
        return StringUtils.removeStart(StringUtils.removeStart(filePath, directoryPath), "\\");
    } catch (IOException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("io exception with file " + file, e);
        }
        return null;
    }
}

From source file:org.sonar.ide.eclipse.core.internal.resources.ResourceUtils.java

@CheckForNull
private static String normalize(@Nullable String path) {
    if (StringUtils.isBlank(path)) {
        return null;
    }//w  ww  .  j  a  va  2s. co  m
    String normalizedPath = path;
    normalizedPath = normalizedPath.replace('\\', '/');
    normalizedPath = StringUtils.trim(normalizedPath);
    if (PATH_SEPARATOR.equals(normalizedPath)) {
        return PATH_SEPARATOR;
    }
    normalizedPath = StringUtils.removeStart(normalizedPath, PATH_SEPARATOR);
    normalizedPath = StringUtils.removeEnd(normalizedPath, PATH_SEPARATOR);
    return normalizedPath;
}