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

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

Introduction

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

Prototype

public static boolean startsWith(String str, String prefix) 

Source Link

Document

Check if a String starts with a specified prefix.

Usage

From source file:org.ejbca.core.model.ra.raadmin.EndEntityProfile.java

/**
 * This function tries to match each field in the profile to a corresponding field in the DN/AN/AD-fields.
 * Can not be used for DNFieldExtractor.TYPE_SUBJECTDIRATTR yet.
 *   //from w  w w . j  a v  a  2 s .  com
 * @param fields
 * @param type One of DNFieldExtractor.TYPE_SUBJECTDN, DNFieldExtractor.TYPE_SUBJECTALTNAME
 * @param email The end entity's email address
 * @throws UserDoesntFullfillEndEntityProfile
 */
private void checkIfFieldsMatch(final DNFieldExtractor fields, final int type, final String email)
        throws UserDoesntFullfillEndEntityProfile {
    final int REQUIRED_FIELD = 2;
    final int NONMODIFYABLE_FIELD = 1;
    final int MATCHED_FIELD = -1;
    final Integer[] dnids = DNFieldExtractor.getUseFields(type);
    // For each type of field
    for (int i = 0; i < dnids.length; i++) {
        final int dnid = dnids[i].intValue();
        final int profileID = DnComponents.dnIdToProfileId(dnid);
        final int dnFieldExtractorID = DnComponents.profileIdToDnId(profileID);
        final int nof = fields.getNumberOfFields(dnFieldExtractorID);
        final int numberOfProfileFields = getNumberOfField(profileID);
        if (nof == 0 && numberOfProfileFields == 0) {
            continue; // Nothing to see here..
        }
        // Create array with all entries of that type
        final String[] subjectsToProcess = new String[nof];
        for (int j = 0; j < nof; j++) {
            String fieldValue = fields.getField(dnFieldExtractorID, j);
            // Only keep domain for comparison of RFC822NAME, DNEMAILADDRESS and UPN fields
            if (DnComponents.RFC822NAME.equals(DnComponents.dnIdToProfileName(dnid))
                    || DnComponents.DNEMAILADDRESS.equals(DnComponents.dnIdToProfileName(dnid))
                    || DnComponents.UPN.equals(DnComponents.dnIdToProfileName(dnid))) {
                if (fieldValue.indexOf('@') == -1) {
                    throw new UserDoesntFullfillEndEntityProfile(DnComponents.dnIdToProfileName(dnid)
                            + " does not seem to be in something@somethingelse format.");
                }
                //Don't split RFC822NAME addresses. 
                if (!DnComponents.RFC822NAME.equals(DnComponents.dnIdToProfileName(dnid))) {
                    fieldValue = fieldValue.split("@")[1];
                }
            } else {
                // Check that postalAddress has #der_encoding_in_hex format, i.e. a full der sequence in hex format
                if (DnComponents.POSTALADDRESS.equals(DnComponents.dnIdToProfileName(dnid))) {
                    if (!StringUtils.startsWith(fieldValue, "#30")) {
                        throw new UserDoesntFullfillEndEntityProfile(DnComponents.dnIdToProfileName(dnid) + " ("
                                + fieldValue
                                + ") does not seem to be in #der_encoding_in_hex format. See \"http://ejbca.org/userguide.html#End Entity Profile fields\" for more information about the postalAddress (2.5.4.16) field.");
                    }
                }
            }
            subjectsToProcess[j] = fieldValue;
        }
        //   Create array with profile values 3 = required and non-mod, 2 = required, 1 = non-modifiable, 0 = neither
        final int[] profileCrossOffList = new int[numberOfProfileFields];
        for (int j = 0; j < getNumberOfField(profileID); j++) {
            profileCrossOffList[j] += (isModifyable(profileID, j) ? 0 : NONMODIFYABLE_FIELD)
                    + (isRequired(profileID, j) ? REQUIRED_FIELD : 0);
        }
        // Start by matching email strings
        if (DnComponents.RFC822NAME.equals(DnComponents.dnIdToProfileName(dnid))
                || DnComponents.DNEMAILADDRESS.equals(DnComponents.dnIdToProfileName(dnid))) {
            for (int k = 3; k >= 0; k--) {
                //   For every value in profile
                for (int l = 0; l < profileCrossOffList.length; l++) {
                    if (profileCrossOffList[l] == k) {
                        //   Match with every value in field-array
                        for (int m = 0; m < subjectsToProcess.length; m++) {
                            if (subjectsToProcess[m] != null && profileCrossOffList[l] != MATCHED_FIELD) {
                                if (getUse(profileID, l) || !DnComponents.RFC822NAME
                                        .equals(DnComponents.dnIdToProfileName(dnid))) {
                                    /*
                                          * IF the component is E-Mail (not RFC822NAME) 
                                          * OR if it is RFC822NAME AND E-Mail field from DN should be used 
                                          */
                                    if (fields.getField(dnFieldExtractorID, m).equals(email)) {
                                        subjectsToProcess[m] = null;
                                        profileCrossOffList[l] = MATCHED_FIELD;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        // For every field of this type in profile (start with required and non-modifiable, 2 + 1)
        for (int k = 3; k >= 0; k--) {
            // For every value in profile
            for (int l = 0; l < profileCrossOffList.length; l++) {
                if (profileCrossOffList[l] == k) {
                    // Match with every value in field-array
                    for (int m = 0; m < subjectsToProcess.length; m++) {
                        if (subjectsToProcess[m] != null && profileCrossOffList[l] != MATCHED_FIELD) {
                            // Match actual value if required + non-modifiable or non-modifiable
                            if ((k == (REQUIRED_FIELD + NONMODIFYABLE_FIELD) || k == (NONMODIFYABLE_FIELD))) {
                                // Try to match with all possible values
                                String[] fixedValues = getValue(profileID, l).split(SPLITCHAR);
                                for (int n = 0; n < fixedValues.length; n++) {
                                    if (subjectsToProcess[m] != null
                                            && subjectsToProcess[m].equals(fixedValues[n])) {
                                        // Remove matched pair
                                        subjectsToProcess[m] = null;
                                        profileCrossOffList[l] = MATCHED_FIELD;
                                    }
                                }

                                // Otherwise just match present fields
                            } else {
                                // Remove matched pair
                                subjectsToProcess[m] = null;
                                profileCrossOffList[l] = MATCHED_FIELD;
                            }
                        }
                    }
                }
            }
        }
        // If not all fields in profile were found
        for (int j = 0; j < nof; j++) {
            if (subjectsToProcess[j] != null) {
                throw new UserDoesntFullfillEndEntityProfile(
                        "End entity profile does not contain matching field for "
                                + DnComponents.dnIdToProfileName(dnid) + " with value \"" + subjectsToProcess[j]
                                + "\".");
            }
        }
        // If not all required fields in profile were found in subject 
        for (int j = 0; j < getNumberOfField(profileID); j++) {
            if (profileCrossOffList[j] >= REQUIRED_FIELD) {
                throw new UserDoesntFullfillEndEntityProfile(
                        "Data does not contain required " + DnComponents.dnIdToProfileName(dnid) + " field.");
            }
        }
    }
}

From source file:org.ejbca.ui.web.pub.WebdistHttpTest.java

@SuppressWarnings("unchecked")
@Test/*from   w  w  w .  j  a  v  a 2  s.co  m*/
public void testPublicWebChainDownload() throws Exception {

    String httpReqPathPem = "http://" + remoteHost + ":" + httpPort
            + "/ejbca/publicweb/webdist/certdist?cmd=cachain&caid=" + testx509ca.getCAId() + "&format=pem";
    String httpReqPathJks = "http://" + remoteHost + ":" + httpPort
            + "/ejbca/publicweb/webdist/certdist?cmd=cachain&caid=" + testx509ca.getCAId() + "&format=jks";

    final WebClient webClient = new WebClient();
    WebConnection con = webClient.getWebConnection();
    WebRequestSettings settings = new WebRequestSettings(new URL(httpReqPathPem));
    WebResponse resp = con.getResponse(settings);
    assertEquals("Response code", 200, resp.getStatusCode());
    String ctype = resp.getContentType();
    assertTrue(StringUtils.startsWith(ctype, "application/octet-stream"));
    List<NameValuePair> list = resp.getResponseHeaders();
    Iterator<NameValuePair> iter = list.iterator();
    boolean found = false;
    while (iter.hasNext()) {
        NameValuePair pair = iter.next();
        log.debug(pair.getName() + ": " + pair.getValue());
        if (StringUtils.equalsIgnoreCase("Content-disposition", pair.getName())) {
            assertEquals("attachment; filename=\"TestCA-chain.pem\"", pair.getValue());
            found = true;
        }
    }
    assertTrue("Unable find TestCA in certificate chain or parsing the response wrong.", found);

    settings = new WebRequestSettings(new URL(httpReqPathJks));
    resp = con.getResponse(settings);
    assertEquals("Response code", 200, resp.getStatusCode());
    ctype = resp.getContentType();
    assertTrue(StringUtils.startsWith(ctype, "application/octet-stream"));
    list = resp.getResponseHeaders();
    iter = list.iterator();
    found = false;
    while (iter.hasNext()) {
        NameValuePair pair = (NameValuePair) iter.next();
        if (StringUtils.equalsIgnoreCase("Content-disposition", pair.getName())) {
            assertEquals("attachment; filename=\"TestCA-chain.jks\"", pair.getValue());
            found = true;
        }
    }
    assertTrue(found);
}

From source file:org.encuestame.mvc.tag.IncludeResource.java

public int doStartTag() throws JspException {
    try {/*from  ww  w.  j  a  v  a  2  s .c om*/
        final JspWriter out = pageContext.getOut();
        final StringBuffer buffer = new StringBuffer("<div");
        if (StringUtils.startsWith(type, "encuestame.org")) {
            buffer.append(" dojoType=\"");
            buffer.append(type);
            buffer.append("\">");
        } else {
            buffer.append("> ");
        }
        buffer.append(" </div>");
        out.write(buffer.toString());
    } catch (Exception e) {
        throw new JspException(e.getMessage());
    }
    return EVAL_PAGE;
}

From source file:org.executequery.datasource.ConnectionPoolImpl.java

private String nameForTransactionIsolationLevel(int isolationLevel) {

    for (Field field : Connection.class.getFields()) {

        String name = field.getName();
        if (StringUtils.startsWith(name, "TRANSACTION_")) {

            try {
                if (isolationLevel == field.getInt(null)) {

                    return name;
                }//w  ww  . ja v  a 2  s.  c o m
            } catch (IllegalArgumentException | IllegalAccessException e) {
            }

        }

    }

    return String.valueOf(isolationLevel);
}

From source file:org.fao.geonet.api.records.formatters.ImageReplacedElementFactory.java

@Override
public ReplacedElement createReplacedElement(LayoutContext layoutContext, BlockBox box,
        UserAgentCallback userAgentCallback, int cssWidth, int cssHeight) {
    org.w3c.dom.Element element = box.getElement();
    if (element == null) {
        return null;
    }/*from   ww  w. j  av  a  2 s  . c om*/

    String nodeName = element.getNodeName();
    String src = element.getAttribute("src");
    if ("img".equals(nodeName) && src.contains("region.getmap.png")) {
        StringBuilder builder = new StringBuilder(baseURL);
        try {
            if (StringUtils.startsWith(src, "http")) {
                builder = new StringBuilder();
            }
            String[] parts = src.split("\\?|&");
            builder.append(parts[0]);
            builder.append('?');
            for (int i = 1; i < parts.length; i++) {
                if (i > 1) {
                    builder.append('&');
                }
                String[] param = parts[i].split("=");
                builder.append(param[0]);
                builder.append('=');
                builder.append(URLEncoder.encode(param[1], "UTF-8"));
            }
        } catch (Exception e) {
            Log.warning(Geonet.GEONETWORK, "Error writing metadata to PDF", e);
        }
        float factor = layoutContext.getDotsPerPixel();
        return loadImage(layoutContext, box, userAgentCallback, cssWidth, cssHeight, builder.toString(),
                factor);
    } else if ("img".equals(nodeName) && isSupportedImageFormat(src)) {
        float factor = layoutContext.getDotsPerPixel();
        return loadImage(layoutContext, box, userAgentCallback, cssWidth, cssHeight, src, factor);
    }

    try {
        return superFactory.createReplacedElement(layoutContext, box, userAgentCallback, cssWidth, cssHeight);
    } catch (Throwable e) {
        return new EmptyReplacedElement(cssWidth, cssHeight);
    }
}

From source file:org.fao.geonet.kernel.SpringLocalServiceInvoker.java

public Object invoke(HttpServletRequest request, HttpServletResponse response) throws Exception {

    HandlerExecutionChain handlerExecutionChain = requestMappingHandlerMapping.getHandler(request);
    HandlerMethod handlerMethod = (HandlerMethod) handlerExecutionChain.getHandler();

    ServletInvocableHandlerMethod servletInvocableHandlerMethod = new ServletInvocableHandlerMethod(
            handlerMethod);//  w w w  .j a  v  a 2 s .c om
    servletInvocableHandlerMethod.setHandlerMethodArgumentResolvers(argumentResolvers);
    servletInvocableHandlerMethod.setHandlerMethodReturnValueHandlers(returnValueHandlers);
    servletInvocableHandlerMethod.setDataBinderFactory(webDataBinderFactory);

    Object o = servletInvocableHandlerMethod.invokeForRequest(new ServletWebRequest(request, response), null,
            new Object[0]);
    // check whether we need to further process a "forward:" response
    if (o instanceof String) {
        String checkForward = (String) o;
        if (checkForward.startsWith("forward:")) {
            //
            // if the original url ends with the first component of the fwd url, then concatenate them, otherwise
            // just invoke it and hope for the best...
            // eg. local://srv/api/records/urn:marlin.csiro.au:org:1_organisation_name
            // returns forward:urn:marlin.csiro.au:org:1_organisation_name/formatters/xml
            // so we join the original url and the forwarded url as:
            // /api/records/urn:marlin.csiro.au:org:1_organisation_name/formatters/xml and invoke it.
            //
            String fwdUrl = StringUtils.substringAfter(checkForward, "forward:");
            String lastComponent = StringUtils.substringAfterLast(request.getRequestURI(), "/");
            if (lastComponent.length() > 0 && StringUtils.startsWith(fwdUrl, lastComponent)) {
                return invoke(request.getRequestURI() + StringUtils.substringAfter(fwdUrl, lastComponent));
            } else {
                return invoke(fwdUrl);
            }
        }
    }
    return o;
}

From source file:org.flite.mock.amazonaws.sqs.AmazonSQSMock.java

public ListQueuesResult listQueues(final ListQueuesRequest request)
        throws AmazonServiceException, AmazonClientException {
    if (request == null) {
        throw new AmazonClientException("Null ListQueuesRequest");
    }//from w w  w .  ja  v a 2 s.c om
    checkStringForExceptionMarker(request.getQueueNamePrefix());

    final String effectivePrefix = QUEUE_URL_PREFIX
            + (request.getQueueNamePrefix() == null ? "" : request.getQueueNamePrefix());
    final ListQueuesResult result = new ListQueuesResult();
    for (final String url : allQueues.keySet()) {
        if (StringUtils.startsWith(url, effectivePrefix)) {
            result.withQueueUrls(url);
        }
    }
    return result;
}

From source file:org.hippoecm.frontend.plugins.richtext.jcr.RichTextFacetHelper.java

private static boolean isRelativePath(final String childNodeName) {
    return StringUtils.isNotEmpty(childNodeName) && !StringUtils.startsWith(childNodeName, "/");
}

From source file:org.hippoecm.frontend.plugins.richtext.view.PreviewLinksBehavior.java

private boolean linkExists(String linkRelPath) {
    if (StringUtils.startsWith(linkRelPath, "/")) {
        // absolute path cannot be an internal link
        return false;
    }/*  w  ww.j a  v  a2s  .c  om*/
    final Node node = model.getObject();
    try {
        if (node.hasNode(linkRelPath)) {
            final Node link = node.getNode(linkRelPath);
            final String docbase = JcrUtils.getStringProperty(link, HIPPO_DOCBASE, null);
            if (docbase != null) {
                final Node target = UserSession.get().getJcrSession().getNodeByIdentifier(docbase);
                return !target.getNode(target.getName()).isNodeType(NT_DELETED);
            }
        }
    } catch (ItemNotFoundException | NamespaceException | IllegalArgumentException ignored) {
        log.debug("Ignoring exception while checking that link '{}' exists and assume it does not exist",
                linkRelPath, ignored);
    } catch (RepositoryException e) {
        log.error("Error while checking internal link existence", e);
    }
    return false;
}

From source file:org.intermine.webservice.server.WebService.java

/**
 * If user name and password is specified in request, then it setups user
 * profile in session. User was authenticated. It uses HTTP basic access
 * authentication.//  w  w w  .j  a v a2  s .co m
 * {@link "http://en.wikipedia.org/wiki/Basic_access_authentication"}
 */
private void authenticate() {

    String authToken = request.getParameter(AUTH_TOKEN_PARAM_KEY);
    final String authString = request.getHeader(AUTHENTICATION_FIELD_NAME);
    final ProfileManager pm = im.getProfileManager();

    if (StringUtils.isEmpty(authToken) && StringUtils.isEmpty(authString)) {
        return; // Not Authenticated.
    }
    // Accept tokens passed in the Authorization header.
    if (StringUtils.isEmpty(authToken) && StringUtils.startsWith(authString, "Token ")) {
        authToken = StringUtils.removeStart(authString, "Token ");
    }

    try {
        // Use a token if provided.
        if (StringUtils.isNotEmpty(authToken)) {
            permission = pm.getPermission(authToken, im.getClassKeys());
        } else {
            // Try and read the authString as a basic auth header.
            // Strip off the "Basic" part - but don't require it.
            final String encoded = StringUtils.removeStart(authString, "Basic ");
            final String decoded = new String(Base64.decodeBase64(encoded.getBytes()));
            final String[] parts = decoded.split(":", 2);
            if (parts.length != 2) {
                throw new UnauthorizedException(
                        "Invalid request authentication. " + "Authorization field contains invalid value. "
                                + "Decoded authorization value: " + parts[0]);
            }
            final String username = StringUtils.lowerCase(parts[0]);
            final String password = parts[1];

            permission = pm.getPermission(username, password, im.getClassKeys());
        }
    } catch (AuthenticationException e) {
        throw new UnauthorizedException(e.getMessage());
    }

    LoginHandler.setUpPermission(im, permission);
}