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:com.google.enterprise.connector.sharepoint.wsclient.mock.XmlClientFactory.java

/**
 * Returns a {@link MockItem} that has the specified Url.
 *
 * @param itemUrl The Url to lookup//  www  . j ava 2 s  .c o m
 * @param username The user requesting access
 * @return a {@link MockItem} if found; null otherwise
 * @throws AxisFault when the user is not authorized
 */
public MockItem getItemFromUrl(final String itemUrl, String username) throws AxisFault {
    if (!root.hasPermission(username)) {
        throw new AxisFault(SPConstants.UNAUTHORIZED);
    }

    String path;
    try {
        final URL url = new URL(itemUrl);
        path = StringUtils.strip(url.getPath(), "/ ");
    } catch (MalformedURLException e) {
        path = "";
    }

    MockItem item = root;
    for (String part : path.split("/")) {
        item = item.getChildByName(part);
        if (null == item) {
            break;
        }
        if (!item.hasPermission(username)) {
            throw new AxisFault(SPConstants.UNAUTHORIZED);
        }
    }

    return item;
}

From source file:com.hpe.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;
                }/*  ww  w. ja  v  a  2s .co m*/
            }
            if (hpRunnerType.equals(HPRunnerType.StormRunnerLoad)) {
                logger.error("HPE 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(OctaneConstants.General.LINUX_PATH_SPLITTER,
                            OctaneConstants.General.WINDOWS_PATH_SPLITTER);
                    path = StringUtils.strip(path, OctaneConstants.General.WINDOWS_PATH_SPLITTER);

                    //split path to package and and name fields
                    if (path.contains(OctaneConstants.General.WINDOWS_PATH_SPLITTER)) {
                        int testNameStartIndex = path
                                .lastIndexOf(OctaneConstants.General.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 Set) {
                    Set createdTests = (Set) additionalContext;
                    testReportCreated = createdTests.contains(cleanedTestName);
                }

                workspace.createTextTempFile("build" + buildId + "." + cleanTestName(testName) + ".", "",
                        "Created  " + testReportCreated);
                if (testReportCreated) {
                    externalURL = jenkinsRootUrl + "job/" + jobName + "/" + buildId + "/artifact/UFTReport/"
                            + cleanTestName(testName) + "/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));
            }
        }
    }
}

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

@Override
public ReportDefinition loadDefinition(File file) throws IOException, ReportException {
    setFile(file);/*from   ww w  .j  a  v a  2  s.  co  m*/
    String jsonFileName = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf(".jrxml"))
            + ".ebr.json";
    File jsonFile;
    jsonFile = new File(jsonFileName);
    final ReportDefinition ret = super.loadDefinition(file, jsonFile);
    ret.setReportType(ReportType.JASPER);

    net.sf.jasperreports.engine.JasperReport jasperReport;
    try {
        jasperReport = (net.sf.jasperreports.engine.JasperReport) JRLoader.loadObject(compileIfRequired(file));
    } catch (JRException ex) {
        throw new ReportException(ex);
    }
    for (JRParameter param : jasperReport.getParameters()) {
        if (!param.isForPrompting() || param.isSystemDefined()) {
            continue;
        }
        ReportParam rp = new ReportParam(param.getValueClass());
        rp.setName(param.getName());
        if (param.getDefaultValueExpression() != null
                && StringUtils.isNotBlank(param.getDefaultValueExpression().getText())) {
            // FIXME alttaki deer script olabilir altrlmas gerekebilir
            String raw = StringUtils.strip(param.getDefaultValueExpression().getText(), "\"");
            if (param.getValueClass().equals(Long.class))
                raw = StringUtils.stripEnd(raw, "Ll");
            rp.setDefaultValue(Convert.to(raw, param.getValueClass()));
        }
        rp.setLabel(param.getName());
        ret.getReportParams().add(rp);
    }

    return ret;
}

From source file:au.org.ands.vocabs.toolkit.utils.ToolkitFileUtils.java

/** Apply slug conventions. In practice, this means
 * (a) replacing punctuation with hyphens,
 * (b) replacing whitespace with hyphen,
 * (c) converting to lowercase,/*from www  .  jav  a2s . c  o  m*/
 * (d) encoding as a URL,
 * (e) replacing percents with hyphens,
 * (f) coalescing multiple consecutive hyphens into one,
 * (g) removing any leading and trailing hyphens,
 * (h) trimming the result to a maximum length of
 *     MAX_SLUG_COMPONENT_LENGTH,
 * (i) removing any remaining trailing hyphen.
 * @param aString The string that is to be converted.
 * @return The value of aString with slug conventions applied.
 */
public static String makeSlug(final String aString) {
    String slug = StringUtils.strip(
            UriComponent.encode(aString.replaceAll("\\p{Punct}", "-").replaceAll("\\s", "-").toLowerCase(),
                    UriComponent.Type.PATH_SEGMENT).replaceAll("%", "-").replaceAll("-+", "-"),
            "-");

    return StringUtils.stripEnd(slug.substring(0, Math.min(MAX_SLUG_COMPONENT_LENGTH, slug.length())), "-");
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.EditFormControlDlg.java

/**
 * Fills in the initial values./*from w ww.ja  va2s  .c  o m*/
 */
protected void fill() {
    if (xCoord == null) {
        createUI();
    }

    Point location = inputPanel.getLocation();
    xCoord.setValue(((Double) location.getX()).intValue());
    yCoord.setValue(((Double) location.getY()).intValue());
    labelTF.setText(StringUtils.strip(inputPanel.getLabelText(), ":"));

    origLabel = inputPanel.getLabelText();
    origLocation = new Point(location.x, location.y);

    if (isTextField) {
        if (textFieldType != null) {
            fieldTypeIndex = inputPanel.getComp() instanceof JTextField ? 0 : 1;
            textFieldType.setSelectedIndex(fieldTypeIndex);
        }

        if (fieldWidth != null) {
            int cols = inputPanel.getComp() instanceof JTextField
                    ? ((JTextField) inputPanel.getComp()).getColumns()
                    : ((JTextArea) inputPanel.getComp()).getColumns();
            fieldWidth.setValue(cols);
        }

        if (numRows != null) {
            adjustTextRowsUI();
            int rows = inputPanel.getComp() instanceof JTextArea ? ((JTextArea) inputPanel.getComp()).getRows()
                    : 1;
            numRows.setValue(rows);
        }
    }
    changeTracker.clear();
}

From source file:com.tesora.dve.sql.parser.InvokeParser.java

public static ParseResult parse(byte[] line, SchemaContext pc, Charset cs) throws ParserException {
    preparse(pc);/*from ww  w .jav  a2s . c  o  m*/
    ParserOptions options = ParserOptions.NONE.setDebugLog(true).setResolve().setFailEarly();

    String lineStr = PECharsetUtils.getString(line, cs, true);
    if (lineStr != null) {
        lineStr = StringUtils.strip(lineStr, new String(Character.toString(Character.MIN_VALUE)));
        return parse(buildInputState(lineStr, pc), options, pc);
    }
    return parameterizeAndParse(pc, options, line, cs);
}

From source file:com.jgui.ttscrape.htmlunit.GridParser.java

private void parseShowContent(Show show, HtmlElement parent) {
    for (HtmlElement el : parent.getChildElements()) {
        if (el instanceof HtmlDivision) {
            parseShowContent(show, el);//from   ww w . j  av a  2s  .  c  o  m
        } else if (el instanceof HtmlSpan) {
            HtmlSpan span = (HtmlSpan) el;
            String spanClass = span.getAttribute("class");
            if ("tn".equals(span.getId())) {
                show.setTitle(span.getTextContent());
            } else if ((spanClass != null) && (spanClass.startsWith("cdt "))) {
                // this contains details about the show.
                String txt = span.asText();
                if (StringUtils.isNotEmpty(txt)) {
                    txt = txt.replace('\n', ' ');
                    txt = StringUtils.strip(txt, " \t,");
                    if (txt.startsWith("(")) {
                        parseShowSummary(show, txt);
                    } else {
                        show.setSubtitle(txt);
                    }
                }
                parseShowContent(show, el);
            } else if ((spanClass != null) && (spanClass.startsWith("hdSymbolTxt"))) {
                show.setHd(true);
            } else if (!StringUtils.isEmpty(spanClass)) {
                logger.trace("unexpected span class {} with cell text {}", spanClass, span.asText());
            }
        }
    }
}

From source file:de.lemo.apps.restws.client.AnalysisImpl.java

@Override
public String computeQFrequentPathBIDE(final Long lemoUserId, final List<Long> courseIds,
        final List<Long> userIds, final List<String> types, final Long minLength, final Long maxLength,
        final Double minSup, final Boolean sessionWise, final Long startTime, final Long endTime,
        final List<Long> gender) {
    try {//from  ww w. j a v  a2s.c o m

        if (init.defaultConnectionCheck()) {

            Response response = qFrequentPathBide.compute(lemoUserId, courseIds, userIds, types, minLength,
                    maxLength, minSup, sessionWise, startTime, endTime, gender);

            if (response.getStatus() == HttpStatus.SC_CREATED) {
                logger.debug("BIDE future result created.");

                // return the id of the result for polling
                // TODO use some random path instead of insecure user id
                @SuppressWarnings("unchecked")
                ClientResponse<String> clientResponse = (ClientResponse<String>) response;
                String resultPath = clientResponse.getEntity(String.class);

                // XXX why is this even quoted?
                resultPath = StringUtils.strip(resultPath, "\"");

                return resultPath;
            }
            // TODO do something on failure
            logger.warn("BIDE invalid response: Status code " + response.getStatus());
            return "null";
        }

    } catch (final Exception e) {
        logger.error("Bide failed", e);
    }
    logger.info("Returning empty result set.");
    return "null";
}

From source file:com.ibm.jaql.lang.expr.system.RJaqlInterface.java

/**
 * This method provides the functionality of saving simple R objects into HDFS in one of
 * the formats supported by Jaql so that it can be directly read into Jaql.
 * @param localPath//from  ww  w  .j  av  a2s .c  o  m
 * @param hdfsPath
 * @param schemaString
 * @param format
 * @param header
 * @param vector
 * @return
 */
public boolean jaqlSave(String localPath, String hdfsPath, String schemaString, String format, boolean header,
        boolean vector) {
    if (format.equalsIgnoreCase(FORMAT_DELIM)) {
        LOG.info("Format: " + FORMAT_DELIM + ", saving to HDFS loc: " + hdfsPath);
        return RUtil.saveToHDFS(localPath, hdfsPath);
    }
    try {
        JobConf conf = new JobConf();
        int DEFAULT_BUFFER_SIZE = 64 * 1024;
        int bufferSize = conf.getInt("io.file.buffer.size", DEFAULT_BUFFER_SIZE);
        BufferedReader reader = new BufferedReader(new FileReader(localPath), bufferSize);
        LongWritable key = new LongWritable(0);
        long count = 0;
        Text value = new Text();
        BufferedJsonRecord options = new BufferedJsonRecord(2);
        BufferedJsonArray headerArray = null;
        if (header) {
            String headerString = reader.readLine();
            String[] headers = splitPattern.split(headerString);
            headerArray = new BufferedJsonArray(headers.length);
            for (int i = 0; i < headers.length; i++) {
                headerArray.set(i, new JsonString(StringUtils.strip(headers[i], "\"")));
            }
            count++;
        }

        Schema schema = null;
        if (schemaString != null) {
            schema = SchemaFactory.parse(schemaString);
        }

        if (headerArray != null) {
            RecordSchema recordSchema = (RecordSchema) schema;

            // construct new matching schema
            List<Field> fields = new LinkedList<Field>();
            for (JsonValue fieldName : headerArray) {
                Field field;
                if (recordSchema == null) {
                    field = new Field((JsonString) fieldName, SchemaFactory.stringSchema(), false);
                } else {
                    field = recordSchema.getField((JsonString) fieldName);
                    if (field == null)
                        throw new NullPointerException("header field not in schema: " + fieldName);
                    // FIXME: schema fields that are not in the header are currently consider OK
                }
                fields.add(field);
            }

            // and set it
            schema = new RecordSchema(fields, null);
        }
        if (schema != null)
            options.add(DelOptionParser.SCHEMA_NAME, new JsonSchema(schema));
        KeyValueImport<LongWritable, Text> converter = null;
        if (vector) {
            converter = new FromLinesConverter();
        } else {
            converter = new FromDelConverter();
        }
        LOG.info("Initializing Converter with options: " + options);
        converter.init(options);
        Schema tmpSchema = converter.getSchema();
        tmpSchema = SchemaTransformation.removeNullability(tmpSchema);
        if (!tmpSchema.is(JsonType.ARRAY, JsonType.RECORD, JsonType.BOOLEAN, JsonType.DECFLOAT, JsonType.DOUBLE,
                JsonType.LONG, JsonType.STRING).always()) {
            throw new IOException("Unrecognized schema type: " + schema.getSchemaType());
        }
        JsonValue outValue = converter.createTarget();
        JsonHolder outKeyHolder;
        JsonHolder outValueHolder;
        if (format.equalsIgnoreCase(FORMAT_DEFAULT)) {
            HadoopSerializationDefault.register(conf);
            outKeyHolder = new JsonHolderDefault();
            outValueHolder = new JsonHolderDefault(outValue);
            LOG.info("Registered serializer for Default format.");
        } else if (format.equalsIgnoreCase(FORMAT_TEMP)) {
            // TODO: There should be a better way of doing this. HadoopSerializationTemp
            // now does it in an ugly way.
            BufferedJsonRecord tmpOptions = new BufferedJsonRecord();
            BufferedJsonRecord outOptions = new BufferedJsonRecord();
            outOptions.add(new JsonString("schema"), new JsonSchema(schema));
            tmpOptions.add(new JsonString("options"), outOptions);
            conf.set(ConfSetter.CONFOUTOPTIONS_NAME, tmpOptions.toString());
            HadoopSerializationTemp.register(conf);
            outKeyHolder = new JsonHolderTempKey(null);
            outValueHolder = new JsonHolderTempValue();
            LOG.info("Registered serializer for HadoopTemp format.");
        } else {
            throw new IOException("Unrecognized serialization format requested: " + format);
        }
        FileSystem fs = FileSystem.get(conf);
        Path outputPath = new Path(hdfsPath);
        Writer writer = SequenceFile.createWriter(fs, conf, outputPath, outKeyHolder.getClass(),
                outValueHolder.getClass());
        String line;
        while ((line = reader.readLine()) != null) {
            key.set(count++);
            value.set(line);
            outValue = converter.convert(key, value, outValue);
            outValueHolder.value = outValue;
            writer.append(outKeyHolder, outValueHolder);
        }
        LOG.info("Transferred " + count + " line(s).");
        reader.close();
        writer.close();
    } catch (IOException e) {
        LOG.info("Error in saving object.", e);
        return false;
    }
    return true;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.EditFormControlDlg.java

/**
 * Adjust the controls per the changes. 
 *///from   w  w w.  ja v a  2  s . c o  m
protected void adjustControl() {

    if (changeTracker.get(xCoord) != null || changeTracker.get(yCoord) != null) {
        inputPanel.setLocation(((Integer) xCoord.getValue()).intValue(),
                ((Integer) yCoord.getValue()).intValue());
    }

    boolean doResize = false;

    if (changeTracker.get(labelTF.getDocument()) != null) {
        if (inputPanel.getComp() instanceof ValCheckBox) {
            ((ValCheckBox) inputPanel.getComp()).setText(labelTF.getText());
        } else {
            inputPanel.getLabel().setText(StringUtils.strip(labelTF.getText(), ":") + ":");
        }
        doResize = true;
    }

    if (isTextField) {
        if (fieldTypeChanged) {
            formPane.swapTextFieldType(inputPanel, ((Integer) fieldWidth.getValue()).shortValue());

            fieldTypeChanged = false;
            fieldTypeIndex = textFieldType.getSelectedIndex();
            adjustTextRowsUI();
        }

        if (changeTracker.get(fieldWidth) != null || (numRows != null && changeTracker.get(numRows) != null)) {
            if (inputPanel.getComp() instanceof JTextField) {
                ((JTextField) inputPanel.getComp()).setColumns(((Integer) fieldWidth.getValue()).intValue());
            } else {
                ((JTextArea) inputPanel.getComp()).setColumns(((Integer) fieldWidth.getValue()).intValue());
                if (numRows != null) // shouldn't be null - defensive
                {
                    ((JTextArea) inputPanel.getComp()).setRows(((Integer) numRows.getValue()).intValue());
                }
                inputPanel.validate();
                inputPanel.repaint();
            }
        }

        doResize = true;
    }

    if (doResize) {
        inputPanel.doLayout();
        inputPanel.repaint();
    }
    changeTracker.clear();
}