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:it.openutils.mgnlaws.magnolia.datastore.S3DataStore.java

/**
 * {@inheritDoc}//from   w  w w .  j a  v a2  s  .c o m
 */
public void init(String homeDir) throws RepositoryException {
    // init S3 client
    amazonS3 = new AmazonS3Client(new BasicAWSCredentials(awsAccessKey, awsSecretKey));
    // set endpoint
    if (StringUtils.isNotBlank(endpoint)) {
        amazonS3.setEndpoint(endpoint);
    }
    // init transfer manager
    transferManager = new TransferManager(amazonS3);

    // initialize tmp directory
    if (StringUtils.isNotBlank(tmpPath)) {
        tmpDirectory = new File(tmpPath);
        if (!tmpDirectory.exists()) {
            tmpDirectory.mkdirs();
        }
    }
    if (tmpDirectory == null || !tmpDirectory.isDirectory()) {
        tmpDirectory = new File(System.getProperty("java.io.tmpdir"));
    }

    if (useCache) {
        // initialize cache directory
        if (StringUtils.isNotBlank(cacheDirectoryPath)) {
            cacheDirectory = new File(cacheDirectoryPath);
            if (!cacheDirectory.exists()) {
                cacheDirectory.mkdirs();
            }
        }
        if (cacheDirectory == null || !cacheDirectory.isDirectory()) {
            cacheDirectory = new File(System.getProperty("java.io.tmpdir"), cacheName);
            if (!cacheDirectory.exists()) {
                cacheDirectory.mkdirs();
            }
        }

        // create cache manager
        CacheManager cacheManager;
        if (StringUtils.startsWith(cacheConfigFile, "classpath:")) {
            URL configurationFileURL = getClass()
                    .getResource(StringUtils.substringAfter(cacheConfigFile, "classpath:"));
            cacheManager = CacheManager.newInstance(configurationFileURL);
        } else {
            cacheManager = CacheManager.newInstance(cacheConfigFile);
        }
        // get cache
        cache = cacheManager.getCache(cacheName);
        // register cache listener
        cache.getCacheEventNotificationService().registerListener(new S3CacheListener(cacheDirectory));
    }
}

From source file:gda.device.detector.addetector.filewriter.SingleImagePerFileWriter.java

/**
 * Returns a single NXDetectorDataAppender for the current image with each call. If isWaitForFileArrival is true,
 * then waits for the file to become visible before returning the appender.
 */// w w w . j a  v  a  2  s .  c  o m
protected NXDetectorDataAppender readNXDetectorDataAppender() throws NoSuchElementException, DeviceException {

    String filepath;
    boolean returnPathIsRelative = isReturnPathRelativeToDatadir();
    try {
        if (returnPathIsRelative) {
            if (!StringUtils.startsWith(getFilePathTemplate(), "$datadir$")) {
                throw new IllegalStateException(
                        "If configured to return a path relative to the datadir, the configured filePathTemplate must begin wiht $datadir$. It is :'"
                                + getFilePathTemplate() + "'");
            }
            filepath = getRelativeFilePath();
        } else {
            filepath = getFullFileName();
        }
    } catch (Exception e) {
        throw new DeviceException(e);
    }
    lastExpectedFullFilepath = returnPathIsRelative ? getAbsoluteFilePath(filepath) : filepath;
    checkErrorStatus();
    if (isWaitForFileArrival()) {
        // Now check that the file exists
        waitForFile(lastExpectedFullFilepath);
    }
    NXDetectorDataFileAppenderForSrs nxDetectorDataFileAppenderForSrs;
    if (firstReadoutInScan) {
        nxDetectorDataFileAppenderForSrs = new NXDetectorDataFileAppenderForSrs(filepath,
                getInputStreamNames().get(0), getxPixelSize(), getyPixelSize(), getxPixelSizeUnit(),
                getyPixelSizeUnit());
        firstReadoutInScan = false;
    } else {
        nxDetectorDataFileAppenderForSrs = new NXDetectorDataFileAppenderForSrs(filepath,
                getInputStreamNames().get(0));
    }

    // Multiple filewriters require different file writer names and extra names
    return nxDetectorDataFileAppenderForSrs;

}

From source file:com.steeleforge.aem.ironsites.wcm.WCMUtil.java

/**
 * For non HTTPS fully qualified URLs, ensure HTTPS
 * //from  w w w .  j ava2  s . c o m
 * @param fullyQualifiedURL
 * @return
 */
public static String getSecureURL(String fullyQualifiedURL) {
    if (!StringUtils.startsWith(fullyQualifiedURL, WCMConstants.HTTPS)) {
        return WCMConstants.HTTPS + WCMConstants.DELIMITER_PORT
                + StringUtils.substringAfter(fullyQualifiedURL, WCMConstants.PROTOCOL_RELATIVE);
    }
    return fullyQualifiedURL;
}

From source file:at.pagu.soldockr.core.query.Criteria.java

private String processCriteriaEntry(String key, Object value) {
    if (value == null) {
        return null;
    }/*from  w  w  w. j a v a2 s. c  o  m*/

    // do not filter espressions
    if (StringUtils.equals(OperationKey.EXPRESSION.getKey(), key)) {
        return value.toString();
    }

    if (StringUtils.equals(OperationKey.BETWEEN.getKey(), key)) {
        Object[] args = (Object[]) value;
        String rangeFragment = "[";
        rangeFragment += args[0] != null ? filterCriteriaValue(args[0]) : WILDCARD;
        rangeFragment += RANGE_OPERATOR;
        rangeFragment += args[1] != null ? filterCriteriaValue(args[1]) : WILDCARD;
        rangeFragment += "]";
        return rangeFragment;
    }

    Object filteredValue = filterCriteriaValue(value);
    if (StringUtils.equals(OperationKey.CONTAINS.getKey(), key)) {
        return WILDCARD + filteredValue + WILDCARD;
    }
    if (StringUtils.equals(OperationKey.STARTS_WITH.getKey(), key)) {
        return filteredValue + WILDCARD;
    }
    if (StringUtils.equals(OperationKey.ENDS_WITH.getKey(), key)) {
        return WILDCARD + filteredValue;
    }
    if (StringUtils.equals(OperationKey.IS_NOT.getKey(), key)) {
        return "-" + filteredValue;
    }

    if (StringUtils.startsWith(key, "$fuzzy")) {
        String sDistance = StringUtils.substringAfter(key, "$fuzzy#");
        float distance = Float.NaN;
        if (StringUtils.isNotBlank(sDistance)) {
            distance = Float.parseFloat(sDistance);
        }
        return filteredValue + "~" + (Float.isNaN(distance) ? "" : sDistance);
    }

    return filteredValue.toString();
}

From source file:com.adobe.acs.tools.test_page_generator.impl.TestPageGeneratorServlet.java

private Object eval(final ScriptEngine scriptEngine, final Object value) {

    if (scriptEngine == null) {
        log.warn("ScriptEngine is null; cannot evaluate");
        return value;
    } else if (value instanceof String[]) {
        final List<String> scripts = new ArrayList<String>();
        final String[] values = (String[]) value;

        for (final String val : values) {
            scripts.add(String.valueOf(this.eval(scriptEngine, val)));
        }//from ww w  . j a v a  2 s .  c  o m

        return scripts.toArray(new String[scripts.size()]);
    } else if (!(value instanceof String)) {
        return value;
    }

    final String stringValue = StringUtils.stripToEmpty((String) value);

    String script;
    if (StringUtils.startsWith(stringValue, "{{") && StringUtils.endsWith(stringValue, "}}")) {

        script = StringUtils.removeStart(stringValue, "{{");
        script = StringUtils.removeEnd(script, "}}");
        script = StringUtils.stripToEmpty(script);

        try {
            return scriptEngine.eval(script);
        } catch (ScriptException e) {
            log.error("Could not evaluation the test page property ecma [ {} ]", script);
        }
    }

    return value;
}

From source file:com.sonicle.webtop.core.app.shiro.WTRealm.java

private boolean isSysAdminImpersonate(String username) {
    return StringUtils.startsWith(StringUtils.lowerCase(username), "admin!");
}

From source file:com.sonicle.webtop.core.app.shiro.WTRealm.java

private boolean isDomainAdminImpersonate(String username) {
    return StringUtils.startsWith(StringUtils.lowerCase(username), "admin$");
}

From source file:com.adobe.acs.commons.workflow.bulk.removal.impl.WorkflowInstanceRemoverImpl.java

/**
 * {@inheritDoc}//w ww.  ja  v a2s . co m
 */
@SuppressWarnings({ "squid:S3776", "squid:S1141" })
public int removeWorkflowInstances(final ResourceResolver resourceResolver, final Collection<String> modelIds,
        final Collection<String> statuses, final Collection<Pattern> payloads, final Calendar olderThan,
        final int batchSize, final int maxDurationInMins) throws PersistenceException, WorkflowRemovalException,
        InterruptedException, WorkflowRemovalForceQuitException {

    final long start = System.currentTimeMillis();
    long end = -1;

    int count = 0;
    int checkedCount = 0;
    int workflowRemovedCount = 0;

    if (maxDurationInMins > 0) {
        // Max duration has been requested (greater than 0)

        // Convert minutes to milliseconds
        long maxDurationInMs = maxDurationInMins * MS_IN_ONE_MINUTE;

        // Compute the end time
        end = start + maxDurationInMs;
    }

    try {
        this.start(resourceResolver);

        final List<Resource> containerFolders = this.getWorkflowInstanceFolders(resourceResolver);

        for (Resource containerFolder : containerFolders) {
            log.debug("Checking [ {} ] for workflow instances to remove", containerFolder.getPath());

            final Collection<Resource> sortedFolders = this.getSortedAndFilteredFolders(containerFolder);

            for (final Resource folder : sortedFolders) {

                int remaining = 0;

                for (final Resource instance : folder.getChildren()) {

                    if (this.forceQuit.get()) {
                        throw new WorkflowRemovalForceQuitException();
                    } else if (end > 0 && System.currentTimeMillis() >= end) {
                        throw new WorkflowRemovalMaxDurationExceededException();
                    }

                    final ValueMap properties = instance.getValueMap();

                    if (!StringUtils.equals(NT_CQ_WORKFLOW,
                            properties.get(JcrConstants.JCR_PRIMARYTYPE, String.class))) {

                        // Only process cq:Workflow's
                        remaining++;
                        continue;
                    }

                    checkedCount++;

                    final String instanceStatus = getStatus(instance);
                    final String model = properties.get(PN_MODEL_ID, String.class);
                    final Calendar startTime = properties.get(PN_STARTED_AT, Calendar.class);
                    final String payload = properties.get(PAYLOAD_PATH, String.class);

                    if (StringUtils.isBlank(payload)) {
                        log.warn("Unable to find payload for Workflow instance [ {} ]", instance.getPath());
                        remaining++;
                        continue;
                    } else if (CollectionUtils.isNotEmpty(statuses) && !statuses.contains(instanceStatus)) {
                        log.trace("Workflow instance [ {} ] has non-matching status of [ {} ]",
                                instance.getPath(), instanceStatus);
                        remaining++;
                        continue;
                    } else if (CollectionUtils.isNotEmpty(modelIds) && !modelIds.contains(model)) {
                        log.trace("Workflow instance [ {} ] has non-matching model of [ {} ]",
                                instance.getPath(), model);
                        remaining++;
                        continue;
                    } else if (olderThan != null && startTime != null && startTime.before(olderThan)) {
                        log.trace("Workflow instance [ {} ] has non-matching start time of [ {} ]",
                                instance.getPath(), startTime);
                        remaining++;
                        continue;
                    } else {

                        if (CollectionUtils.isNotEmpty(payloads)) {
                            // Only evaluate payload patterns if they are provided

                            boolean match = false;

                            if (StringUtils.isNotEmpty(payload)) {
                                for (final Pattern pattern : payloads) {
                                    if (payload.matches(pattern.pattern())) {
                                        // payload matches a pattern
                                        match = true;
                                        break;
                                    }
                                }

                                if (!match) {
                                    // Not a match; skip to next workflow instance
                                    log.trace("Workflow instance [ {} ] has non-matching payload path [ {} ]",
                                            instance.getPath(), payload);
                                    remaining++;
                                    continue;
                                }
                            }
                        }

                        // Only remove matching

                        try {
                            instance.adaptTo(Node.class).remove();
                            log.debug("Removed workflow instance at [ {} ]", instance.getPath());

                            workflowRemovedCount++;
                            count++;
                        } catch (RepositoryException e) {
                            log.error("Could not remove workflow instance at [ {} ]. Continuing...",
                                    instance.getPath(), e);
                        }

                        if (count % batchSize == 0) {
                            this.batchComplete(resourceResolver, checkedCount, workflowRemovedCount);

                            log.info("Removed a running total of [ {} ] workflow instances", count);
                        }
                    }
                }

                if (remaining == 0 && isWorkflowDatedFolder(folder) && !StringUtils.startsWith(folder.getName(),
                        new SimpleDateFormat(WORKFLOW_FOLDER_FORMAT).format(new Date()))) {
                    // Dont remove folders w items and dont remove any of "today's" folders
                    // MUST match the YYYY-MM-DD(.*) pattern; do not try to remove root folders
                    try {
                        folder.adaptTo(Node.class).remove();
                        log.debug("Removed empty workflow folder node [ {} ]", folder.getPath());
                        // Incrementing only count to trigger batch save and not total since is not a WF
                        count++;
                    } catch (RepositoryException e) {
                        log.error("Could not remove workflow folder at [ {} ]", folder.getPath(), e);
                    }
                }
            }

            // Save final batch if needed, and update tracking nodes
            this.complete(resourceResolver, checkedCount, workflowRemovedCount);
        }

    } catch (PersistenceException e) {
        this.forceQuit.set(false);
        log.error("Error persisting changes with Workflow Removal", e);
        this.error();
        throw e;
    } catch (WorkflowRemovalException e) {
        this.forceQuit.set(false);
        log.error("Error with Workflow Removal", e);
        this.error();
        throw e;
    } catch (InterruptedException e) {
        this.forceQuit.set(false);
        log.error("Errors in persistence retries during Workflow Removal", e);
        this.error();
        throw e;
    } catch (WorkflowRemovalForceQuitException e) {
        this.forceQuit.set(false);
        // Uncommon instance of using Exception to control flow; Force quitting is an extreme condition.
        log.warn("Workflow removal was force quit. The removal state is unknown.");
        this.internalForceQuit();
        throw e;
    } catch (WorkflowRemovalMaxDurationExceededException e) {
        // Uncommon instance of using Exception to control flow; Exceeding max duration extreme condition.
        log.warn("Workflow removal exceeded max duration of [ {} ] minutes. Final removal commit initiating...",
                maxDurationInMins);
        this.complete(resourceResolver, checkedCount, count);
    }

    if (log.isInfoEnabled()) {
        log.info(
                "Workflow Removal Process Finished! "
                        + "Removed a total of [ {} ] workflow instances in [ {} ] ms",
                count, System.currentTimeMillis() - start);
    }

    return count;
}

From source file:com.steeleforge.aem.ironsites.wcm.WCMUtil.java

/**
 * For protocol specific fully qualified URLs, ensure protocol relativity
 * /*w ww.j av a2 s. c  o m*/
 * @param fullyQualifiedURL
 * @return
 */
public static String getProtocolRelativeURL(String fullyQualifiedURL) {
    if (!StringUtils.startsWith(fullyQualifiedURL, WCMConstants.PROTOCOL_RELATIVE)) {
        return WCMConstants.PROTOCOL_RELATIVE
                + StringUtils.substringAfter(fullyQualifiedURL, WCMConstants.PROTOCOL_RELATIVE);
    }
    return fullyQualifiedURL;
}

From source file:com.taobao.tdhs.jdbc.TDHSStatement.java

private void doUpdate(com.taobao.tdhs.client.statement.Statement s, ParseSQL parseSQL, String tableName,
        String dbName) throws SQLException {
    Query query = preprocessGet(s, parseSQL, tableName, dbName);
    List<Entry<String, String>> updateEntries = parseSQL.getUpdateEntries();
    if (updateEntries == null || updateEntries.isEmpty()) {
        throw new TDHSSQLException("no value to update!", parseSQL.getSql());
    }//from  w ww .j  a v  a  2s .  co m

    for (Entry<String, String> e : updateEntries) {
        if (StringUtils.isBlank(e.getKey()) || StringUtils.isBlank(e.getValue())) {
            throw new TDHSSQLException("insert column and values can't be empty!", parseSQL.getSql());
        }
        String field = StringUtil.escapeField(StringUtils.trim(e.getKey()));
        if (field == null) {
            throw new TDHSSQLException("insert column is error!", parseSQL.getSql());
        }
        String value = StringUtils.trim(e.getValue());
        if (StringUtils.equalsIgnoreCase("null", value)) {
            query.set().field(field).setNull();
        } else if (StringUtils.equalsIgnoreCase("now()", value)) {
            query.set().field(field).setNow();
        } else {
            if (StringUtils.startsWith(value, field)) {
                value = value.substring(field.length());
                value = StringUtils.trim(value);
                if (StringUtils.startsWith(value, "+")) {
                    value = value.substring(1);
                    value = StringUtils.trim(value);
                    if (StringUtil.isLong(value)) {
                        query.set().field(field).add(Long.valueOf(value));
                    } else {
                        throw new TDHSSQLException("update value is error ,is not long", parseSQL.getSql());
                    }
                } else if (StringUtils.startsWith(value, "-")) {
                    value = value.substring(1);
                    value = StringUtils.trim(value);
                    if (StringUtil.isLong(value)) {
                        query.set().field(field).sub(Long.valueOf(value));
                    } else {
                        throw new TDHSSQLException("update value is error ,is not long", parseSQL.getSql());
                    }

                } else {
                    throw new TDHSSQLException("update value is error maybe can't support!", parseSQL.getSql());
                }
            } else {
                value = StringUtil.escapeValue(value);
                if (value == null) {
                    throw new TDHSSQLException("update value is error!", parseSQL.getSql());
                }

                if (StringUtils.startsWith(value, BYTE_PARAMETER_PREFIX)) {
                    int pidx = ConvertUtil
                            .safeConvertInt(StringUtils.substring(value, BYTE_PARAMETER_PREFIX.length()), -1);
                    if (byteParameters.containsKey(pidx)) {
                        query.set().field(field).set(byteParameters.get(pidx));
                    } else {
                        query.set().field(field).set(value);
                    }
                } else {
                    query.set().field(field).set(value);
                }
            }
        }
    }
    TDHSResponse response = null;
    try {
        response = query.update();
    } catch (TDHSException e) {
        throw new SQLException(e);
    }
    processResponse(response, true);
}