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:deployer.publishers.openshift.OpenShiftWebAppTest.java

private static UpstreamServerRegistration eqRegistration(final String userFacingUrlPrefix,
        final String appNamePrefix, final String upstreamHostAndPort, final String upstreamPath) {
    EasyMock.reportMatcher(new IArgumentMatcher() {

        @Override/* w w w.  jav  a 2 s  .c o  m*/
        public boolean matches(Object actual) {
            if (!(actual instanceof UpstreamServerRegistration)) {
                return false;
            }
            UpstreamServerRegistration registration = (UpstreamServerRegistration) actual;
            return StringUtils.startsWith(registration.getAppName(), appNamePrefix)
                    && StringUtils.equals(registration.getUpstreamHostAndPort(), upstreamHostAndPort)
                    && StringUtils.equals(registration.getUpstreamPath(), upstreamPath)
                    && StringUtils.equals(registration.getUserFacingUrlPrefix(), userFacingUrlPrefix);
        }

        @Override
        public void appendTo(StringBuffer buffer) {
            UpstreamServerRegistration expected = new UpstreamServerRegistration();
            expected.setUserFacingUrlPrefix(userFacingUrlPrefix);
            expected.setAppName(appNamePrefix);
            expected.setUpstreamHostAndPort(upstreamHostAndPort);
            expected.setUpstreamPath(upstreamPath);
            buffer.append(expected);
        }
    });
    return null;
}

From source file:com.adobe.acs.commons.forms.helpers.impl.PostFormHelperImpl.java

public boolean hasValidSuffix(final SlingHttpServletRequest slingRequest) {
    final String requestSuffix = slingRequest.getRequestPathInfo().getSuffix();
    if (StringUtils.equals(requestSuffix, this.getSuffix())
            || StringUtils.startsWith(requestSuffix, this.getSuffix() + "/")) {
        return true;
    }//ww  w .  j  a v  a2 s .c o m

    return false;
}

From source file:com.adobe.acs.commons.forms.helpers.impl.PostFormHelperImpl.java

/**
 * Gets the Form Selector for the form POST request
 *
 * @param slingRequest/*from  www .jav a  2 s  .com*/
 * @return
 */
public String getFormSelector(final SlingHttpServletRequest slingRequest) {
    final String requestSuffix = slingRequest.getRequestPathInfo().getSuffix();
    if (StringUtils.equals(requestSuffix, this.getSuffix())
            || !StringUtils.startsWith(requestSuffix, this.getSuffix() + "/")) {
        return null;
    }

    final int segments = StringUtils.split(this.getSuffix(), '/').length;
    if (segments < 1) {
        return null;
    }

    final String formSelector = PathInfoUtil.getSuffixSegment(slingRequest, segments);
    return StringUtils.stripToNull(formSelector);
}

From source file:com.sfs.whichdoctor.dao.PaymentDAOImpl.java

/**
 * Process a credit card payment.//from   w  w w.jav  a2  s.  co m
 *
 * @param cardNumber the card number
 * @param cardHolder the card holder
 * @param expiryMonth the expiry month
 * @param expiryYear the expiry year
 * @param securityCode the security code
 * @param totalValue the total value
 * @param description the description
 * @param purchaseComment the purchase comment
 * @return the string[] where:
 *       string[0] = success/error,
 *       string[1] = transaction reference,
 *       string[2] = error message,
 *       string[3] = extended error log
 */
public final String[] processCreditCardPayment(final String cardNumber, final String cardHolder,
        final int expiryMonth, final int expiryYear, final int securityCode, final double totalValue,
        final String description, final String purchaseComment) {

    String success = "", reference = "", message = "", logMessage = "";

    /* Perform a web service call using XFire libraries */
    try {
        Client client = new Client(new URL(this.paymentUrl));

        dataLogger.debug("Processing payment");

        Object[] result = client.invoke("process", new Object[] { accessId, secret, cardNumber, cardHolder,
                expiryMonth, expiryYear, securityCode, totalValue, 0, "", description, purchaseComment });

        dataLogger.info("Payment processing complete. Results Object[]: " + result);

        String resultString = (String) result[0];

        StringTokenizer st = new StringTokenizer(resultString, ",");
        int i = 0;
        while (st.hasMoreTokens()) {
            String token = st.nextToken();
            if (StringUtils.startsWith(token, "'")) {
                token = StringUtils.substring(token, 1, token.length());
            }
            if (StringUtils.endsWith(token, "'")) {
                token = StringUtils.substring(token, 0, token.length() - 1);
            }

            switch (i) {
            case 0:
                success = token;
                break;
            case 1:
                reference = token;
                break;
            case 2:
                message = token;
                break;
            case 3:
                logMessage = token;
                break;
            }

            i++;
        }

        dataLogger.info("Payment result: " + success + ", reference: " + reference + ", message: " + message);
    } catch (Exception e) {
        dataLogger.error("Error performing payment process web service lookup: " + e.getMessage(), e);
    }

    return new String[] { success, reference, message, logMessage };
}

From source file:hudson.plugins.clearcase.ClearCaseUcmSCM.java

private String shortenStreamName(String longStream) {
    if (StringUtils.startsWith(longStream, STREAM_PREFIX)) {
        return StringUtils.substringAfter(longStream, STREAM_PREFIX);
    } else {/*from   w  w  w  .  jav a  2 s . c o  m*/
        return longStream;
    }
}

From source file:com.widen.valet.Route53Driver.java

private void checkDomainName(String name) {
    Defense.notBlank(name, "name");

    if (StringUtils.startsWith(name, ".") || !StringUtils.endsWith(name, ".")) {
        throw new IllegalArgumentException("Domain name '" + name
                + "' is invalid. Name can not start with a period and must end with a period.");
    }/*  www .  j a v  a 2s  .  c o m*/
}

From source file:de.hybris.platform.accountsummaryaddon.document.dao.impl.DefaultPagedB2BDocumentDaoTest.java

@Test
public void shouldGetErrorCriteriaNotFound() {

    final AccountSummaryDocumentQuery query = new B2BDocumentQueryBuilder(0, 10, B2BDocumentModel.OPENAMOUNT,
            true).addCriteria("unknowcriteria", "any").build();

    try {/*from  w  w  w .  j a v  a 2 s .  c  om*/
        pagedB2BDocumentDao.findDocuments(query);
        TestCase.fail();
    } catch (final FlexibleSearchException e) {
        //Success
        TestCase.assertTrue(StringUtils.startsWith(e.getMessage(), "cannot search unknown field"));
    }
}

From source file:com.nridge.ds.content.ds_content.ContentExtractor.java

/**
 * This method will extract the textual content from the input file
 * and write it to the writer stream.  If a bag instance has been
 * registered with the class, then meta data fields will dynamically
 * be assigned as they are discovered.//from   w  w  w.j  a  va2  s  . c o m
 *
 * @param anInFile Input file instance.
 * @param aWriter Output writer stream.
 *
 * @throws NSException Thrown when IOExceptions are detected.
 */
@SuppressWarnings("deprecation")
public void process(File anInFile, Writer aWriter) throws NSException {
    Logger appLogger = mAppMgr.getLogger(this, "process");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (isFileValid(anInFile)) {
        appLogger.debug(String.format("[%s] %s", detectType(anInFile), anInFile.getAbsolutePath()));

        ForkParser forkParser = null;
        Metadata tikaMetaData = new Metadata();
        tikaMetaData.set(Metadata.RESOURCE_NAME_KEY, anInFile.getName());
        int contentLimit = getCfgInteger("content_limit", Content.CONTENT_LIMIT_DEFAULT);

        InputStream inputStream = null;
        try {
            Parser tikaParser;
            ParseContext parseContext;

            inputStream = TikaInputStream.get(anInFile.toPath());
            if (isCfgStringTrue("tika_fork_parser")) {
                forkParser = new ForkParser(ContentExtractor.class.getClassLoader(), new AutoDetectParser());
                String javaCmdStr = getCfgString("tika_fork_java_cmd");
                if (StringUtils.isNotEmpty(javaCmdStr))
                    forkParser.setJavaCommand(javaCmdStr);
                int poolSize = getCfgInteger("tika_fork_pool_size", 5);
                if (poolSize > 0)
                    forkParser.setPoolSize(poolSize);
                tikaParser = forkParser;
                parseContext = new ParseContext();
            } else {
                tikaParser = new AutoDetectParser();
                parseContext = new ParseContext();
                Parser recursiveMetadataParser = new RecursiveMetadataParser(tikaParser);
                parseContext.set(Parser.class, recursiveMetadataParser);
            }

            WriteOutContentHandler writeOutContentHandler = new WriteOutContentHandler(aWriter, contentLimit);
            tikaParser.parse(inputStream, writeOutContentHandler, tikaMetaData, parseContext);
        } catch (Exception e) {
            String eMsg = e.getMessage();
            String msgStr = String.format("%s: %s", anInFile.getAbsolutePath(), eMsg);

            /* The following logic checks to see if this exception was triggered simply because
            the total character limit threshold was hit.  If that is all it was, then return true. */

            if (StringUtils.startsWith(eMsg, "Your document contained more than"))
                appLogger.warn(msgStr);
            else
                throw new NSException(msgStr);
        } finally {
            if (inputStream != null)
                IOUtils.closeQuietly(inputStream);
        }

        if ((mBag != null) && (isCfgStringTrue("content_metadata"))) {
            String mdValue;
            String[] metaDataNames = tikaMetaData.names();
            for (String mdName : metaDataNames) {
                mdValue = tikaMetaData.get(mdName);
                if (StringUtils.isNotEmpty(mdValue))
                    addAssignField(Content.CONTENT_FIELD_METADATA + mdName, mdValue);
            }
        }

        if (forkParser != null)
            forkParser.close();
    } else {
        String msgStr = String.format("%s: Does not exist or is empty.", anInFile.getAbsolutePath());
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:gobblin.config.store.hdfs.SimpleHadoopFilesystemConfigStore.java

/**
 * A helper to resolve System properties and Environment variables in includes paths
 * The method loads the list of unresolved <code>includes</code> into an in-memory {@link Config} object and reolves
 * with a fallback on {@link ConfigFactory#defaultOverrides()}
 *
 * @param includes list of unresolved includes
 * @return a list of resolved includes/*from   www  .  j av a  2 s.  co m*/
 */
@VisibleForTesting
public static List<String> resolveIncludesList(List<String> includes, Optional<Config> runtimeConfig) {

    // Create a TypeSafe Config object with Key INCLUDES_KEY_NAME and value an array of includes
    StringBuilder includesBuilder = new StringBuilder();
    for (String include : includes) {
        // Skip comments
        if (StringUtils.isNotBlank(include) && !StringUtils.startsWith(include, "#")) {
            includesBuilder.append(INCLUDES_KEY_NAME).append("+=").append(include).append("\n");
        }
    }

    // Resolve defaultOverrides and environment variables.
    if (includesBuilder.length() > 0) {
        if (runtimeConfig.isPresent()) {
            return ConfigFactory.parseString(includesBuilder.toString())
                    .withFallback(ConfigFactory.defaultOverrides())
                    .withFallback(ConfigFactory.systemEnvironment()).withFallback(runtimeConfig.get()).resolve()
                    .getStringList(INCLUDES_KEY_NAME);
        } else {
            return ConfigFactory.parseString(includesBuilder.toString())
                    .withFallback(ConfigFactory.defaultOverrides())
                    .withFallback(ConfigFactory.systemEnvironment()).resolve().getStringList(INCLUDES_KEY_NAME);
        }
    }

    return Collections.emptyList();
}

From source file:com.adobe.acs.commons.errorpagehandler.impl.ErrorPageHandlerImpl.java

/**
 * Find the JCR full path to the most appropriate Error Page.
 *
 * @param request//from  w ww. j  a  v a  2  s .c o m
 * @param errorResource
 * @return
 */
@Override
@SuppressWarnings("squid:S3776")
public String findErrorPage(SlingHttpServletRequest request, Resource errorResource) {
    if (!isEnabled()) {
        return null;
    }

    final String errorsPath = findErrorsPath(request, errorResource);

    Resource errorPage = null;
    if (StringUtils.isNotBlank(errorsPath)) {
        final ResourceResolver resourceResolver = errorResource.getResourceResolver();
        final String errorPath = errorsPath + "/" + getErrorPageName(request);
        errorPage = getResource(resourceResolver, errorPath);

        if (errorPage == null && StringUtils.isNotBlank(errorsPath)) {
            log.trace(
                    "No error-specific errorPage could be found, use the 'default' error errorPage for the Root content path");
            errorPage = resourceResolver.resolve(errorsPath);
        }
    }

    String errorPagePath = null;
    if (errorPage == null || ResourceUtil.isNonExistingResource(errorPage)) {
        log.trace("no custom error page could be found");
        if (this.hasSystemErrorPage()) {
            errorPagePath = this.getSystemErrorPagePath();
            log.trace("using system error page [ {} ]", errorPagePath);
        }
    } else {
        errorPagePath = errorPage.getPath();
    }

    if (errorImagesEnabled && this.isImageRequest(request)) {

        if (StringUtils.startsWith(this.errorImagePath, "/")) {
            // Absolute path
            return this.errorImagePath;
        } else if (StringUtils.isNotBlank(errorPagePath)) {
            // Selector or Relative path; compute path based off found error page

            if (StringUtils.startsWith(this.errorImagePath, ".")) {
                final String selectorErrorImagePath = errorPagePath + this.errorImagePath;
                log.debug("Using selector-based error image: {}", selectorErrorImagePath);
                return selectorErrorImagePath;
            } else {
                final String relativeErrorImagePath = errorPagePath + "/"
                        + StringUtils.removeStart(this.errorImagePath, "/");
                log.debug("Using relative path-based error image: {}", relativeErrorImagePath);
                return relativeErrorImagePath;
            }
        } else {
            log.warn("Error image path found, but no error page could be found so relative path cannot "
                    + "be applied: {}", this.errorImagePath);
        }
    } else if (StringUtils.isNotBlank(errorPagePath)) {
        errorPagePath = StringUtils.stripToNull(applyExtension(errorPagePath));
        log.debug("Using resolved error page: {}", errorPagePath);
        return errorPagePath;
    } else {
        log.debug("ACS AEM Commons Error Page Handler is enabled but mis-configured. A valid error image"
                + " handler nor a valid error page could be found.");
    }
    return null;
}