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

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

Introduction

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

Prototype

public static String stripEnd(String str, String stripChars) 

Source Link

Document

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

Usage

From source file:org.nuxeo.ecm.restapi.server.jaxrs.adapters.ConvertAdapter.java

@POST
public Object convert(@FormParam("converter") String converter, @FormParam("type") String type,
        @FormParam("format") String format, @FormParam("async") boolean async, @Context UriInfo uriInfo) {
    if (!async) {
        return convert(converter, type, format, uriInfo);
    }//from   w ww.j  a v a 2  s  .c  o  m

    String conversionId;
    BlobHolder bh = getBlobHolderToConvert();
    Map<String, Serializable> parameters = computeConversionParameters(uriInfo);
    ConversionService conversionService = Framework.getService(ConversionService.class);
    if (StringUtils.isNotBlank(converter)) {
        conversionId = conversionService.scheduleConversion(converter, bh, parameters);
    } else if (StringUtils.isNotBlank(type)) {
        conversionId = conversionService.scheduleConversionToMimeType(type, bh, parameters);
    } else if (StringUtils.isNotBlank(format)) {
        MimetypeRegistry mimetypeRegistry = Framework.getService(MimetypeRegistry.class);
        String mimeType = mimetypeRegistry.getMimetypeFromExtension(format);
        conversionId = conversionService.scheduleConversionToMimeType(mimeType, bh, parameters);
    } else {
        throw new IllegalParameterException("No converter, type or format parameter specified");
    }

    String serverURL = StringUtils.stripEnd(ctx.getServerURL().toString(), "/");
    String pollingURL = String.format("%s%s/conversions/%s/poll", serverURL, ctx.getModulePath(), conversionId);
    String resultURL = String.format("%s%s/conversions/%s/result", serverURL, ctx.getModulePath(),
            conversionId);
    ConversionScheduled conversionScheduled = new ConversionScheduled(conversionId, pollingURL, resultURL);
    try {
        return Response.status(Response.Status.ACCEPTED).location(new URI(pollingURL))
                .entity(conversionScheduled).build();
    } catch (URISyntaxException e) {
        throw new NuxeoException(e);
    }
}

From source file:org.obiba.mica.micaConfig.service.OpalService.java

private String getOpalProjectUrl(String opalUrl, String project) {
    String baseUrl = opalUrl == null ? getDefaultOpal() : opalUrl;

    return String.format("%s/ws/datasource/%s", StringUtils.stripEnd(baseUrl, "/"), project);
}

From source file:org.opencastproject.security.api.OrganizationParsingTest.java

private boolean compareXMLattsEqual(String in1, String in2) {
    if (in1.equals(in2)) {
        return true;
    }/* ww w .  jav a2  s .  co  m*/
    String[] strings1 = StringUtils.stripEnd(in1, " /").split(" ");
    String[] strings2 = StringUtils.stripEnd(in2, " /").split(" ");
    Arrays.sort(strings1);
    Arrays.sort(strings2);
    assertEquals("Organization XML not formed as expected - error in number of XML attributes", strings1.length,
            strings2.length);
    for (int i = 0; i < strings1.length; i++) {
        if (!(strings1[i].equals(strings2[i]))) {
            assertEquals("Organization XML not formed as expected - xml-attributes don't match",
                    "<" + in1 + ">", "<" + in2 + ">");
        }
    }
    return true;
}

From source file:org.openhab.binding.kodi.internal.protocol.KodiConnection.java

private String convertToImageUrl(JsonElement element) {
    String text = convertToText(element);
    if (!text.isEmpty()) {
        try {/*from   w w  w  . j  av  a2s  .c o  m*/
            // we have to strip ending "/" here because Kodi returns a not valid path and filename
            // "fanart":"image://http%3a%2f%2fthetvdb.com%2fbanners%2ffanart%2foriginal%2f263365-31.jpg/"
            // "thumbnail":"image://http%3a%2f%2fthetvdb.com%2fbanners%2fepisodes%2f263365%2f5640869.jpg/"
            String encodedURL = URLEncoder.encode(StringUtils.stripEnd(text, "/"), "UTF-8");
            return imageUri.resolve(encodedURL).toString();
        } catch (UnsupportedEncodingException e) {
            logger.debug("exception during encoding {}", text, e);
            return null;
        }
    }
    return null;
}

From source file:org.openmrs.maven.plugins.bintray.OpenmrsBintray.java

public BintrayPackage createPackage(MavenProject mavenProject, String repository) {
    CreatePackageRequest request = new CreatePackageRequest();
    request.setName(mavenProject.getArtifactId());
    request.setDescription(mavenProject.getDescription());

    String githubUrl = mavenProject.getScm().getUrl();
    if (githubUrl.endsWith("/"))
        githubUrl = StringUtils.stripEnd(githubUrl, "/");
    String githubRepo = githubUrl.substring(githubUrl.lastIndexOf("/")).replace(".git", "");
    request.setVcsUrl(githubUrl + (githubUrl.endsWith(".git") ? "" : ".git"));
    request.setGithubRepo(OPENMRS_USERNAME + githubRepo);
    request.setWebsiteUrl("http://openmrs.org/");

    request.setIssueTrackerUrl(new DefaultJira().getJiraUrl());
    //so far all OpenMRS projects have MPL-2.0 license
    request.setLicenses(Arrays.asList("MPL-2.0"));
    return createPackage(OPENMRS_USERNAME, repository, request);
}

From source file:org.openmrs.module.chica.vendor.impl.VendorImpl.java

/**
 * DWE CHICA-861/*from   w  ww .j av  a 2s  .com*/
 * Removes the first whitespace and replaces all others with zeros
 * Also removes trailing spaces, but leaves any spaces in the middle
 * 
 * The examples observed so far always contain atleast one space, followed by more spaces that should be zeros
 * For example, "   1234" should be "001234" but comes across with 3 leading spaces. 
 * The first is removed but the others are replaced by zeros. Also remove trailing spaces.
 * If the parameter contains spaces in the middle of the value, they are left in place
 * For example, "     1234   5678   " will become "00001234   5678"
 * 
 * @param parameterName
 * @return
 */
public String removeLeadingTrailingSpacesAddLeadingZeros(String parameterName) throws Exception {
    String paramValue = request.getParameter(parameterName);

    if (paramValue != null && paramValue.length() > 0) {
        if (paramValue.charAt(0) == CHARACTER_SPACE) {
            paramValue = paramValue.substring(1); // Remove the leading space, but leave the rest of the leading spaces
        }

        paramValue = StringUtils.stripEnd(paramValue, STRING_SPACE); // Remove all trailing spaces

        if (paramValue.length() > 0 && paramValue.charAt(0) == CHARACTER_SPACE) {
            // Replace all of the remaining leading spaces with zeros. This will leave any spaces in the middle as is
            Pattern p = Pattern.compile("^(\\s*)(.+)$");
            Matcher m = p.matcher(paramValue);

            if (m.matches()) {
                paramValue = m.group(1).replaceAll(STRING_SPACE, REPLACEMENT_VALUE_ZERO) + m.group(2);
            }
        }
    }

    return paramValue;
}

From source file:org.opennms.netmgt.provision.service.dns.DnsRequisitionUrlConnection.java

/**
 * Creates an instance of the JaxB annotated RequisionNode class.
 * /* w  w  w. j av a 2  s  . c om*/
 * @param rec
 * @return a populated RequisitionNode based on defaults and data from the
 *   A record returned from a DNS zone transfer query.
 */
private RequisitionNode createRequisitionNode(Record rec) {
    String addr = null;
    if ("A".equals(Type.string(rec.getType()))) {
        ARecord arec = (ARecord) rec;
        addr = StringUtils.stripStart(arec.getAddress().toString(), "/");
    } else if ("AAAA".equals(Type.string(rec.getType()))) {
        AAAARecord aaaarec = (AAAARecord) rec;
        addr = aaaarec.rdataToString();
    } else {
        throw new IllegalArgumentException(
                "Invalid record type " + Type.string(rec.getType()) + ". A or AAAA expected.");
    }

    RequisitionNode n = new RequisitionNode();

    String host = rec.getName().toString();
    String nodeLabel = StringUtils.stripEnd(StringUtils.stripStart(host, "."), ".");

    n.setBuilding(getForeignSource());

    switch (m_foreignIdHashSource) {
    case 1:
        n.setForeignId(computeHashCode(nodeLabel));
        LOG.debug("Generating foreignId from hash of nodelabel {}", nodeLabel);
        break;
    case 2:
        n.setForeignId(computeHashCode(addr));
        LOG.debug("Generating foreignId from hash of ipAddress {}", addr);
        break;
    case 3:
        n.setForeignId(computeHashCode(nodeLabel + addr));
        LOG.debug("Generating foreignId from hash of nodelabel+ipAddress {}{}", nodeLabel, addr);
        break;
    default:
        n.setForeignId(computeHashCode(nodeLabel));
        LOG.debug("Default case: Generating foreignId from hash of nodelabel {}", nodeLabel);
        break;
    }
    n.setNodeLabel(nodeLabel);

    RequisitionInterface i = new RequisitionInterface();
    i.setDescr("DNS-" + Type.string(rec.getType()));
    i.setIpAddr(addr);
    i.setSnmpPrimary(PrimaryType.PRIMARY);
    i.setManaged(Boolean.TRUE);
    i.setStatus(Integer.valueOf(1));

    for (String service : m_services) {
        service = service.trim();
        i.insertMonitoredService(new RequisitionMonitoredService(service));
        LOG.debug("Adding provisioned service {}", service);
    }

    n.putInterface(i);

    return n;
}

From source file:org.owasp.jbrofuzz.core.Verifier.java

/**
 * <p>Method responsible for parsing the printable
 * String contents of the file fuzzers.jbrf to
 * the prototype HashMap.</p>/*from w w  w  . j av  a2 s.  c om*/
 * 
 * @param input the .jbrf file in String input
 */
private static void parsePrototypes(Map<String, Prototype> map, String input) {

    // Break down the file contents into lines
    final String[] fileInput = input.split("\n");

    if (fileInput.length > MAX_LINES) {
        throw new RuntimeException(ERROR_MSG + "fuzzers.jbrf has more than " + MAX_LINES + " lines.");
    }

    if (fileInput.length < 3) {
        throw new RuntimeException(ERROR_MSG + "fuzzers.jbrf does not have enough lines.");
    }

    for (int i = 0; i < fileInput.length; i++) {

        // Ignore comment lines starting with '#'
        if (fileInput[i].startsWith("#")) {
            continue;
        }

        // Ignore lines of length greater than MAX_LINE_LENGTH
        if (fileInput[i].length() > MAX_LINE_LENGTH) {
            continue;
        }

        // Check 1 indicating a likely prototype candidate
        try {
            if (fileInput[i].charAt(1) != ':') {
                continue;
            }
            if (fileInput[i].charAt(13) != ':') {
                continue;
            }

        } catch (final IndexOutOfBoundsException e1) {
            continue;
        }

        // [0] -> P || R || X
        // [1] -> "001-HTT-MTH"
        // [2] -> Uppercase HTTP Methods
        // [3] -> 8
        final String[] _fla = fileInput[i].split(":");

        // Check that there are four fields separated by :
        if (_fla.length != 4) {
            continue;
        }

        final char inputTypeChar = _fla[0].charAt(0);

        // Check [0] -> Fuzzer Type 'Z' or 'P', etc..
        if (!Prototype.isValidFuzzerType(inputTypeChar)) {
            continue;
        }

        // The Id: 009-SQL-INJ cannot be empty
        if (_fla[1].isEmpty()) {
            continue;
        }

        // The name: "SQL Injection" cannot be empty
        if (_fla[2].isEmpty()) {
            continue;
        }

        // Check the prototype name length
        if (_fla[2].length() > MAX_PROTO_NAME_LENGTH) {
            continue;
        }

        int noPayloads = 0;
        try {
            noPayloads = Integer.parseInt(_fla[3]);

        } catch (final NumberFormatException e) {
            continue;
        }

        // Check how many payloads this prototype has
        if (noPayloads > MAX_NO_OF_PAYLOADS) {
            continue;
        }

        // Allow only zero fuzzers to have no payloads
        if (noPayloads == 0) {
            continue;
        }

        // Check we have that many payloads left in file
        if (i + noPayloads > fileInput.length) {
            continue;
        }

        try {
            if (!fileInput[i + 1].startsWith(">")) {
                continue;
            }
            if (!fileInput[i + 2].startsWith(">>")) {
                continue;
            }
        } catch (final IndexOutOfBoundsException e) {
            continue;
        }

        String line2 = "";
        try {
            line2 = fileInput[i + 1].substring(1);
        } catch (final IndexOutOfBoundsException e) {
            continue;
        }

        String comment = "";
        try {
            comment = fileInput[i + 2].substring(2);
        } catch (final IndexOutOfBoundsException e) {
            continue;
        }

        // [0] -> HTTP Methods
        // [1] -> Replacive Fuzzers
        // [2] -> Uppercase Fuzzers
        final String[] _sla = line2.split("\\|");
        if (_sla.length > MAX_NO_OF_CATEGORIES) {
            continue;
        }

        // Alas! Finally create a prototype
        final Prototype proto = new Prototype(inputTypeChar, _fla[1], _fla[2]);

        // If categories do exist in the second line
        if (_sla.length > 0) {

            for (String categ_ry : _sla) {
                // add the category to the prototype
                categ_ry = StringUtils.stripEnd(categ_ry, " ");
                categ_ry = StringUtils.stripStart(categ_ry, " ");

                if (!categ_ry.isEmpty()) {
                    proto.addCategory(categ_ry);
                }

            }
        }
        // If no categories have been identified,
        // add a default category
        else {

            proto.addCategory("JBroFuzz");

        }

        // Add the comment
        proto.addComment(comment);

        // Add the values of each payload
        for (int j = 1; j <= noPayloads; j++) {
            try {

                proto.addPayload(fileInput[i + 2 + j]);

            } catch (final IndexOutOfBoundsException e) {
                continue;
            }
        }

        // Finally add the prototype to the database
        map.put(_fla[1], proto);

    }

}

From source file:org.owasp.jbrofuzz.headers.HeaderLoader.java

/**
 * <p>/*from  ww  w  . ja  va  2 s .c o  m*/
 * Private, recursive method used at construction to populate the master
 * <code>HeaderTreeNode</code> that can be accessed via the
 * <code>getMasterTreeNode</code> method.
 * </p>
 * <p>
 * In accessing this method, do not forget to reset the
 * <code>globalCounter</code> as if it reaches a value of
 * <code>MAX_RECURSION
 * </code> this method will simply return.
 * </p>
 * 
 * @param categoriesArray
 *            The array of nodes to be added.
 * @param headerTreeNode
 *            The tree node on which to be added.
 * 
 * @see #getMasterHeader()
 * @author subere@uncon.org
 * @version 1.3
 * @since 1.2
 */
private void addNodes(final String[] categoriesArray, final HeaderTreeNode headerTreeNode) {

    if (categoriesArray.length == 0) {
        return;
    }
    if (globalCounter > MAX_RECURSION) {
        return;
    }
    globalCounter++;
    // Find the first element
    final String firstElement = StringUtils.stripStart(StringUtils.stripEnd(categoriesArray[0], " "), " ");
    // Use the index to know its position
    int index = 0;
    boolean exists = false;
    for (final Enumeration<HeaderTreeNode> e = extracted(headerTreeNode); e.hasMoreElements() && !exists;) {

        final String currentElement = e.nextElement().toString();

        if (currentElement.equalsIgnoreCase(firstElement)) {

            exists = true;

        } else {
            // If firstElement not current, increment
            index++;

        }
    }

    // Does the first element exist?
    if (!exists) {

        headerTreeNode.add(new HeaderTreeNode(firstElement));
    }

    // Remove the first element, start again
    final String[] temp = (String[]) ArrayUtils.subarray(categoriesArray, 1, categoriesArray.length);
    final HeaderTreeNode nemp = (HeaderTreeNode) headerTreeNode.getChildAt(index);

    addNodes(temp, nemp);

}

From source file:org.rapidcontext.core.storage.Path.java

/**
 * Creates a new path from a parent and a child string
 * representation (similar to a file system path).
 *
 * @param parent         the parent index path
 * @param path           the string path to parse
 *//*from  w w w .ja  v  a 2s . c om*/
public Path(Path parent, String path) {
    this.parts = (parent == null) ? ArrayUtils.EMPTY_STRING_ARRAY : parent.parts;
    path = StringUtils.stripStart(path, "/");
    this.index = path.equals("") || path.endsWith("/");
    path = StringUtils.stripEnd(path, "/");
    if (!path.equals("")) {
        String[] child = path.split("/");
        String[] res = new String[this.parts.length + child.length];
        for (int i = 0; i < this.parts.length; i++) {
            res[i] = this.parts[i];
        }
        for (int i = 0; i < child.length; i++) {
            res[this.parts.length + i] = child[i];
        }
        this.parts = res;
    }
}