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

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

Introduction

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

Prototype

public static String strip(String str, String stripChars) 

Source Link

Document

Strips any of a set of characters from the start and end of a String.

Usage

From source file:io.hawkcd.services.FileManagementService.java

@Override
public String getPattern(String rootPath, String path) {

    String pattern = path.replace(rootPath, "");

    if (pattern.isEmpty() || pattern.equals("/") || pattern.equals("\\")) {
        pattern = "**";
    }//  ww  w. j  av  a2  s  . c o  m

    pattern = this.normalizePath(pattern);

    return StringUtils.strip(pattern, "/");
}

From source file:info.magnolia.cms.taglibs.util.SimpleSearchTag.java

/**
 * Split search terms and build an xpath query in the form:
 * <code>//*[@jcr:primaryType='mgnl:content']/\*\/\*[jcr:contains(., 'first') or jcr:contains(., 'second')]</code>
 *
 * @return valid xpath expression or null if the given query doesn't contain at least one valid search term
 *//*from  w  w w.j  av a 2 s  .  co  m*/
protected String generateXPathQuery() {

    String startPath = null;

    // search only in a specific subtree
    if (this.startLevel != 0) {
        try {
            Content activePage = Resource.getActivePage((HttpServletRequest) this.pageContext.getRequest());
            if (activePage != null) {
                startPath = StringUtils.strip(activePage.getAncestor(this.startLevel).getHandle(), "/"); //$NON-NLS-1$
            }
        } catch (RepositoryException e) {
            log.error(e.getMessage(), e);
        }
    }

    // strip reserved chars and split
    String[] tokens = StringUtils
            .split(StringUtils.lowerCase(StringUtils.replaceChars(this.query, RESERVED_CHARS, null)));

    // null input string?
    if (tokens == null) {
        return null;
    }

    StringBuffer xpath = new StringBuffer(tokens.length * 20);
    if (StringUtils.isNotEmpty(startPath)) {
        xpath.append(startPath);
    }
    xpath.append("//*[@jcr:primaryType=\'mgnl:content\']/*/*["); //$NON-NLS-1$

    String joinOperator = "and"; //$NON-NLS-1$
    boolean emptyQuery = true;

    for (int j = 0; j < tokens.length; j++) {
        String tkn = tokens[j];
        if (ArrayUtils.contains(KEYWORDS, tkn)) {
            joinOperator = tkn;
        } else {
            if (!emptyQuery) {
                xpath.append(" "); //$NON-NLS-1$
                xpath.append(joinOperator);
                xpath.append(" "); //$NON-NLS-1$
            }
            xpath.append("jcr:contains(., '"); //$NON-NLS-1$
            xpath.append(tkn);
            xpath.append("')"); //$NON-NLS-1$
            emptyQuery = false;
        }

    }

    xpath.append("]"); //$NON-NLS-1$

    // if no valid search terms are added don't return a catch-all query
    if (emptyQuery) {
        return null;
    }

    return xpath.toString();
}

From source file:com.intuit.tank.project.JobValidator.java

private void processScripts(Map<String, String> globalVariables) {
    MethodTimer mt = new MethodTimer(LOG, this.getClass(), "processScripts");
    mt.start();/*from   ww w . ja va2  s .com*/
    boolean hasLoggingKeys = false;
    for (ScriptWrapper wrapper : scripts) {
        long milis = 0;
        Script s = wrapper.script;
        boolean hasRequest = false;
        for (ScriptStep step : s.getScriptSteps()) {
            if (step.getType().equals("request")) {
                hasRequest = true;
            } else if (hasRequest && step.getType().equalsIgnoreCase("variable")) {
                bestPracticeViolations.add(
                        "&nbsp;&nbsp;Rule: Declare variables before request.<br/>&nbsp;&nbsp;&nbsp;&nbsp;Script "
                                + s.getName() + " declares variable '"
                                + step.getData().iterator().next().getKey() + "' at index "
                                + step.getStepIndex());
            }
            if (StringUtils.isNotBlank(step.getLoggingKey())) {
                hasLoggingKeys = true;
            }
            String dataFile = ScriptUtil.getDataFileUse(step);
            if (dataFile != null) {
                String stripped = StringUtils.strip(dataFile, "'\"");
                dataFiles.add(stripped);
                if (!stripped.equals(dataFile)) {
                    bestPracticeViolations.add(
                            "&nbsp;&nbsp;Rule: Do not hard Code Data File names.<br/>&nbsp;&nbsp;&nbsp;&nbsp;Script "
                                    + s.getName() + " uses a hard coded name for the data file '" + stripped
                                    + "' at index " + step.getStepIndex());
                } else if (dataFile.equalsIgnoreCase(TankConstants.DEFAULT_CSV_FILE_NAME)) {
                    bestPracticeViolations.add(
                            "&nbsp;&nbsp;Rule: Explicitly define Data File names.<br/>&nbsp;&nbsp;&nbsp;&nbsp;Script "
                                    + s.getName() + " uses the default data file 'csv-data.txt' at index "
                                    + step.getStepIndex());
                }
            }
            milis += ScriptUtil.calculateStepDuration(step, globalVariables);
            for (Entry<String, String> entry : ScriptUtil.getDeclaredVariables(step).entrySet()) {
                putVariable(this.declaredVariables, entry.getKey(), entry.getValue(), wrapper.location);
            }
            usedVariables.addAll(ScriptUtil.getUsedVariables(step));
            // if (processAssignments) {
            for (ScriptAssignment assignment : ScriptUtil.getAssignments(step)) {
                putVariable(this.assignments, assignment.getVariable(), assignment.getAssignemnt(),
                        s.getName() + "[" + assignment.getScriptIndex() + "]");
            }
            usedVariables.addAll(this.assignments.keySet());
            // }
        }
        addDuration(wrapper.groupName, wrapper.loop, milis);
    }
    if (!hasLoggingKeys) {
        bestPracticeViolations.add(
                "&nbsp;&nbsp;Rule: No Logging Keys.<br/>&nbsp;&nbsp;&nbsp;&nbsp;No Logging keys are defined");
    }
    this.orphanedVariables.addAll(usedVariables);
    for (String s : declaredVariables.keySet()) {
        orphanedVariables.remove(s);
    }
    for (String s : assignments.keySet()) {
        orphanedVariables.remove(s);
    }
    this.superfluousVariables.addAll(declaredVariables.keySet());
    this.superfluousVariables.addAll(assignments.keySet());
    for (String s : usedVariables) {
        superfluousVariables.remove(s);
    }
    mt.endAndLog();
}

From source file:com.yoncabt.ebr.executor.jasper.JasperReport.java

private static File compile(File jrxmlFile) throws JRException {
    logManager.info(jrxmlFile + " compile");
    File jasperFile = new File(jrxmlFile.getAbsolutePath().replace(".jrxml", ".jasper"));
    jasperFile.getParentFile().mkdirs();
    if (jrxmlFile.lastModified() > jasperFile.lastModified()) {
        JasperDesign jasperDesign = JRXmlLoader.load(jrxmlFile.getAbsolutePath());
        net.sf.jasperreports.engine.JasperReport jasperReport = JasperCompileManager
                .compileReport(jasperDesign);
        JRSaver.saveObject(jasperReport, jasperFile.getAbsolutePath());
        //toLog("Saving compiled report to: " + jasperFile.getAbsolutePath());
        //Compile sub reports
        JRElementsVisitor.visitReport(jasperReport, new JRVisitor() {

            @Override//from w w  w. j  av a  2  s.  c  o  m
            public void visitBreak(JRBreak breakElement) {
            }

            @Override
            public void visitChart(JRChart chart) {
            }

            @Override
            public void visitCrosstab(JRCrosstab crosstab) {
            }

            @Override
            public void visitElementGroup(JRElementGroup elementGroup) {
            }

            @Override
            public void visitEllipse(JREllipse ellipse) {
            }

            @Override
            public void visitFrame(JRFrame frame) {
            }

            @Override
            public void visitImage(JRImage image) {
            }

            @Override
            public void visitLine(JRLine line) {
            }

            @Override
            public void visitRectangle(JRRectangle rectangle) {
            }

            @Override
            public void visitStaticText(JRStaticText staticText) {
            }

            @Override
            public void visitSubreport(JRSubreport subreport) {
                String subReportName = subreport.getExpression().getText().replace("repo:", "");
                subReportName = StringUtils.strip(subReportName, "\"");
                //uzant jrxml olduuna emin olalm
                subReportName = FilenameUtils.removeExtension(subReportName) + ".jrxml";
                File subReportFile = new File(jrxmlFile.getParentFile(), subReportName);
                //Sometimes the same subreport can be used multiple times, but
                //there is no need to compile multiple times
                // burada tam path bulmak gerekebilir
                File compiledSubReportFile = compileIfRequired(subReportFile.getAbsoluteFile());
                File destSubReportFile = new File(
                        EBRConf.INSTANCE.getValue("report.subreport.path",
                                "/home/eastblue/apache-tomcat-8.0.28/webapps/ebr/WEB-INF/classes"),
                        compiledSubReportFile.getName());
                try {
                    // copy to classpoath
                    FileUtils.copyFile(compiledSubReportFile, destSubReportFile);
                } catch (IOException ex) {
                    throw new ReportException(ex);
                }
            }

            @Override
            public void visitTextField(JRTextField textField) {
            }

            @Override
            public void visitComponentElement(JRComponentElement componentElement) {
            }

            @Override
            public void visitGenericElement(JRGenericElement element) {
            }

        });
        JasperCompileManager.compileReportToFile(jrxmlFile.getAbsolutePath(), jasperFile.getAbsolutePath());
    }
    return jasperFile;
}

From source file:com.reizes.shiva.utils.AddrUtil.java

/**
 * addr2? ?   ? ./*  w  w w.ja v a2  s. c  o m*/
 * @param addr2
 * @return
 */
public static String getAddr3FromAddr2(String addr2) {
    if (addr2 != null) {
        Matcher matcher2 = PATTERN_ADDR2_2.matcher(addr2);
        if (matcher2.find()) {
            return StringUtil.normalize(StringUtils.strip(matcher2.replaceAll(""), " ,/.\t-_"));
        } else {
            Matcher matcher = PATTERN_ADDR2_1.matcher(addr2);
            if (matcher.find()) {
                return StringUtil.normalize(StringUtils.strip(matcher.replaceAll(""), " ,/.\t-_"));
            }
            return StringUtil.normalize(addr2);
        }
    }

    return null;
}

From source file:jp.co.tis.gsp.tools.dba.s2jdbc.gen.ViewAnalyzer.java

public String getTableName() {
    // MySQL??????????
    return StringUtils.strip(tableName, "`");
}

From source file:com.opengamma.elsql.ElSqlParser.java

private void parseContainerSection(ContainerSqlFragment container, ListIterator<Line> lineIterator,
        int indent) {
    while (lineIterator.hasNext()) {
        Line line = lineIterator.next();
        if (line.isComment()) {
            lineIterator.remove();//from w  ww . j a va  2  s .co m
            continue;
        }
        if (line.indent() <= indent) {
            lineIterator.previous();
            return;
        }
        String trimmed = line.lineTrimmed();
        if (trimmed.startsWith("@NAME")) {
            Matcher nameMatcher = NAME_PATTERN.matcher(trimmed);
            if (nameMatcher.matches() == false) {
                throw new IllegalArgumentException("@NAME found with invalid format: " + line);
            }
            NameSqlFragment nameFragment = new NameSqlFragment(nameMatcher.group(1));
            parseContainerSection(nameFragment, lineIterator, line.indent());
            if (nameFragment.getFragments().size() == 0) {
                throw new IllegalArgumentException("@NAME found with no subsequent indented lines: " + line);
            }
            container.addFragment(nameFragment);
            _namedFragments.put(nameFragment.getName(), nameFragment);

        } else if (indent < 0) {
            throw new IllegalArgumentException(
                    "Invalid fragment found at root level, only @NAME is permitted: " + line);

        } else if (trimmed.startsWith("@PAGING")) {
            Matcher pagingMatcher = PAGING_PATTERN.matcher(trimmed);
            if (pagingMatcher.matches() == false) {
                throw new IllegalArgumentException("@PAGING found with invalid format: " + line);
            }
            PagingSqlFragment whereFragment = new PagingSqlFragment(pagingMatcher.group(1),
                    pagingMatcher.group(2));
            parseContainerSection(whereFragment, lineIterator, line.indent());
            if (whereFragment.getFragments().size() == 0) {
                throw new IllegalArgumentException("@PAGING found with no subsequent indented lines: " + line);
            }
            container.addFragment(whereFragment);

        } else if (trimmed.startsWith("@WHERE")) {
            if (trimmed.equals("@WHERE") == false) {
                throw new IllegalArgumentException("@WHERE found with invalid format: " + line);
            }
            WhereSqlFragment whereFragment = new WhereSqlFragment();
            parseContainerSection(whereFragment, lineIterator, line.indent());
            if (whereFragment.getFragments().size() == 0) {
                throw new IllegalArgumentException("@WHERE found with no subsequent indented lines: " + line);
            }
            container.addFragment(whereFragment);

        } else if (trimmed.startsWith("@AND")) {
            Matcher andMatcher = AND_PATTERN.matcher(trimmed);
            if (andMatcher.matches() == false) {
                throw new IllegalArgumentException("@AND found with invalid format: " + line);
            }
            AndSqlFragment andFragment = new AndSqlFragment(andMatcher.group(1),
                    StringUtils.strip(andMatcher.group(2), " ="));
            parseContainerSection(andFragment, lineIterator, line.indent());
            if (andFragment.getFragments().size() == 0) {
                throw new IllegalArgumentException("@AND found with no subsequent indented lines: " + line);
            }
            container.addFragment(andFragment);

        } else if (trimmed.startsWith("@OR")) {
            Matcher orMatcher = OR_PATTERN.matcher(trimmed);
            if (orMatcher.matches() == false) {
                throw new IllegalArgumentException("@OR found with invalid format: " + line);
            }
            OrSqlFragment orFragment = new OrSqlFragment(orMatcher.group(1),
                    StringUtils.strip(orMatcher.group(2), " ="));
            parseContainerSection(orFragment, lineIterator, line.indent());
            if (orFragment.getFragments().size() == 0) {
                throw new IllegalArgumentException("@OR found with no subsequent indented lines: " + line);
            }
            container.addFragment(orFragment);

        } else if (trimmed.startsWith("@IF")) {
            Matcher ifMatcher = IF_PATTERN.matcher(trimmed);
            if (ifMatcher.matches() == false) {
                throw new IllegalArgumentException("@IF found with invalid format: " + line);
            }
            IfSqlFragment ifFragment = new IfSqlFragment(ifMatcher.group(1),
                    StringUtils.strip(ifMatcher.group(2), " ="));
            parseContainerSection(ifFragment, lineIterator, line.indent());
            if (ifFragment.getFragments().size() == 0) {
                throw new IllegalArgumentException("@IF found with no subsequent indented lines: " + line);
            }
            container.addFragment(ifFragment);

        } else {
            parseLine(container, line);
        }
    }
}

From source file:jp.co.tis.gsp.tools.dba.s2jdbc.gen.ViewAnalyzer.java

@Override
public void visit(SelectExpressionItem item) {
    ColumnParser columnParser = new ColumnParser();
    item.getExpression().accept(columnParser);
    if (columnParser.isSimple()) {
        String columnName = columnParser.getColumnName();
        simpleColumnNames.add(columnName);
        aliases.put(columnName, StringUtils.strip(item.getAlias().getName(), "`").toUpperCase());
    }//from  w w  w.j  av a2 s  .co  m
}

From source file:br.com.ingenieux.jenkins.plugins.awsebdeployment.Deployer.java

private static String strip(String str) {
    return StringUtils.strip(str, "/ ");
}

From source file:com.microfocus.application.automation.tools.octane.tests.junit.JUnitXmlIterator.java

@Override
protected void onEvent(XMLEvent event) throws XMLStreamException, IOException, InterruptedException {
    if (event instanceof StartElement) {
        StartElement element = (StartElement) event;
        String localName = element.getName().getLocalPart();
        if ("file".equals(localName)) { // NON-NLS
            String path = readNextValue();
            for (ModuleDetection detection : moduleDetection) {
                moduleName = detection.getModule(new FilePath(new File(path)));
                if (moduleName != null) {
                    break;
                }/*www.  j a  v a 2s .c  o m*/
            }
            if (hpRunnerType.equals(HPRunnerType.StormRunnerLoad)) {
                logger.error("ALM Octane Runner: " + hpRunnerType);
                externalURL = getStormRunnerURL(path);
            }
        } else if ("id".equals(localName)) {
            id = readNextValue();
        } else if ("case".equals(localName)) { // NON-NLS
            packageName = "";
            className = "";
            testName = "";
            duration = 0;
            status = TestResultStatus.PASSED;
            stackTraceStr = "";
            errorType = "";
            errorMsg = "";
        } else if ("className".equals(localName)) { // NON-NLS
            String fqn = readNextValue();
            int p = fqn.lastIndexOf('.');
            className = fqn.substring(p + 1);
            if (p > 0) {
                packageName = fqn.substring(0, p);
            } else {
                packageName = "";
            }
        } else if ("testName".equals(localName)) { // NON-NLS
            testName = readNextValue();

            if (hpRunnerType.equals(HPRunnerType.UFT)) {
                String myPackageName = packageName;
                String myClassName = className;
                String myTestName = testName;
                packageName = "";
                className = "";

                if (testName.startsWith(workspace.getRemote())) {
                    // if workspace is prefix of the method name, cut it off
                    // currently this handling is needed for UFT tests
                    int testStartIndex = workspace.getRemote().length()
                            + (sharedCheckOutDirectory == null ? 0 : (sharedCheckOutDirectory.length() + 1));
                    String path = testName.substring(testStartIndex);
                    path = path.replace(SdkConstants.FileSystem.LINUX_PATH_SPLITTER,
                            SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER);
                    path = StringUtils.strip(path, SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER);

                    //split path to package and and name fields
                    if (path.contains(SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER)) {
                        int testNameStartIndex = path
                                .lastIndexOf(SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER);

                        testName = path.substring(testNameStartIndex + 1);
                        packageName = path.substring(0, testNameStartIndex);
                    } else {
                        testName = path;
                    }
                }

                String cleanedTestName = cleanTestName(testName);
                boolean testReportCreated = true;
                if (additionalContext != null && additionalContext instanceof List) {
                    //test folders are appear in the following format GUITest1[1], while [1] number of test. It possible that tests with the same name executed in the same job
                    //by adding [1] or [2] we can differentiate between different instances.
                    //We assume that test folders are sorted so in this section, once we found the test folder, we remove it from collection , in order to find the second instance in next iteration
                    List<String> createdTests = (List<String>) additionalContext;
                    String searchFor = cleanedTestName + "[";
                    Optional<String> optional = createdTests.stream().filter(str -> str.startsWith(searchFor))
                            .findFirst();
                    if (optional.isPresent()) {
                        cleanedTestName = optional.get();
                        createdTests.remove(cleanedTestName);

                    }
                    testReportCreated = optional.isPresent();
                }

                workspace.createTextTempFile("build" + buildId + "." + cleanTestName(testName) + ".", "",
                        "Created  " + testReportCreated);
                if (testReportCreated) {
                    externalURL = jenkinsRootUrl + "job/" + jobName + "/" + buildId + "/artifact/UFTReport/"
                            + cleanedTestName + "/run_results.html";
                } else {
                    //if UFT didn't created test results page - add reference to Jenkins test results page
                    externalURL = jenkinsRootUrl + "job/" + jobName + "/" + buildId + "/testReport/"
                            + myPackageName + "/" + jenkinsTestClassFormat(myClassName) + "/"
                            + jenkinsTestNameFormat(myTestName) + "/";
                }
            } else if (hpRunnerType.equals(HPRunnerType.PerformanceCenter)) {
                externalURL = jenkinsRootUrl + "job/" + jobName + "/" + buildId
                        + "/artifact/performanceTestsReports/pcRun/Report.html";
            } else if (hpRunnerType.equals(HPRunnerType.StormRunnerFunctional)) {
                if (StringUtils.isNotEmpty(id) && additionalContext != null
                        && additionalContext instanceof Map) {
                    Map<String, String> testId2Url = (Map) additionalContext;
                    if (testId2Url.containsKey(id))
                        externalURL = testId2Url.get(id);
                }
            } else if (hpRunnerType.equals(HPRunnerType.StormRunnerLoad)) {
                //console contains link to report
                //link start with "View Report:"
                String VIEW_REPORT_PREFIX = "View Report: ";
                if (additionalContext != null && additionalContext instanceof Collection) {
                    for (Object str : (Collection) additionalContext) {
                        if (str != null && str instanceof String
                                && ((String) str).startsWith(VIEW_REPORT_PREFIX)) {
                            externalURL = str.toString().replace(VIEW_REPORT_PREFIX, "");
                        }
                    }
                }
            }
        } else if ("duration".equals(localName)) { // NON-NLS
            duration = parseTime(readNextValue());
        } else if ("skipped".equals(localName)) { // NON-NLS
            if ("true".equals(readNextValue())) { // NON-NLS
                status = TestResultStatus.SKIPPED;
            }
        } else if ("failedSince".equals(localName)) { // NON-NLS
            if (!"0".equals(readNextValue()) && !TestResultStatus.SKIPPED.equals(status)) {
                status = TestResultStatus.FAILED;
            }
        } else if ("errorStackTrace".equals(localName)) { // NON-NLS
            status = TestResultStatus.FAILED;
            stackTraceStr = "";
            if (peek() instanceof Characters) {
                stackTraceStr = readNextValue();
                int index = stackTraceStr.indexOf("at ");
                if (index >= 0) {
                    errorType = stackTraceStr.substring(0, index);
                }
            }
        } else if ("errorDetails".equals(localName)) { // NON-NLS
            status = TestResultStatus.FAILED;
            errorMsg = readNextValue();
            int index = stackTraceStr.indexOf(':');
            if (index >= 0) {
                errorType = stackTraceStr.substring(0, index);
            }

        }
    } else if (event instanceof EndElement) {
        EndElement element = (EndElement) event;
        String localName = element.getName().getLocalPart();

        if ("case".equals(localName)) { // NON-NLS
            TestError testError = new TestError(stackTraceStr, errorType, errorMsg);
            if (stripPackageAndClass) {
                //workaround only for UFT - we do not want packageName="All-Tests" and className="&lt;None>" as it comes from JUnit report
                addItem(new JUnitTestResult(moduleName, "", "", testName, status, duration, buildStarted,
                        testError, externalURL));
            } else {
                addItem(new JUnitTestResult(moduleName, packageName, className, testName, status, duration,
                        buildStarted, testError, externalURL));
            }
        }
    }
}