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:com.lxht.emos.data.cache.intf.HessianUtil.java

/**
 * ??,?,?????./*from www.ja v  a 2 s  . co  m*/
 *
 * @param objectFileDirectory ?
 * @param fileName            ???????
 * @return boolean ??, true:?,false:.
 */
public static boolean removeSerializeLikeFile(String objectFileDirectory, final String fileName) {
    if (StringUtils.isBlank(objectFileDirectory) || StringUtils.isBlank(fileName)) {
        return false;
    }

    // ?File.
    File objDirFile = getObjectFileDir(objectFileDirectory);

    // ????
    File[] objFiles = objDirFile.listFiles(new FilenameFilter() {

        public boolean accept(File dir, String name) {
            if (StringUtils.isBlank(name)) {
                return false;
            }

            /**
             * ??.
             */
            return StringUtils.startsWith(name, fileName);
        }
    });

    if (ArrayUtils.isEmpty(objFiles)) {
        return false;
    }

    // ?.
    for (File file : objFiles) {
        boolean isDelSuc = file.delete();
        if (!isDelSuc) {
            file.deleteOnExit();
            logger.warn("removeSerializeLikeFile(),Delete the local cache file failed.[File:" + file + "]");
            continue;
        }
    }

    return true;
}

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

/**
 * Only if the path template starts with the datadir, return a path relative to it, otherwise
 * return an absolute path.//from   ww w  .  j  a  v a2s.  c  o m
 */
protected String getFileDirRelativeToDataDirIfPossible() {
    String template = getFilePathTemplate();
    if (StringUtils.startsWith(template, "$datadir$")) {
        template = StringUtils.replace(template, "$datadir$", "");
        template = StringUtils.removeStart(template, "/");
    } else {
        //return absolute path (after substituting data directory)
        template = substituteDatadir(template);
    }
    return substituteScan(template);
}

From source file:com.adobe.acs.commons.dam.impl.ReviewTaskAssetMoverHandler.java

@Override
public void handleEvent(Event event) {
    ResourceResolver resourceResolver = null;

    try {//  ww  w.j  a  va2s  .  com
        resourceResolver = resourceResolverFactory.getServiceResourceResolver(AUTH_INFO);
        final String path = (String) event.getProperty("TaskId");
        final Resource taskResource = resourceResolver.getResource(path);

        if (taskResource != null) {
            final ValueMap taskProperties = taskResource.getValueMap();

            // Perform a fast check to see if this project has the required properties to perform the asset moving
            if (StringUtils.startsWith(taskProperties.get(PN_ON_APPROVE, String.class), PATH_CONTENT_DAM)
                    || StringUtils.startsWith(taskProperties.get(PN_ON_REJECT, String.class),
                            PATH_CONTENT_DAM)) {

                log.debug("Handling event (creating a Job) for Assets Review Task @ [ {} ]", path);

                ScheduleOptions options = scheduler.NOW();
                String jobName = this.getClass().getSimpleName().toString().replace(".", "/") + "/" + path;
                options.name(jobName);

                options.canRunConcurrently(false);

                scheduler.schedule(new ImmediateJob(path), options);
            }
        }
    } catch (LoginException e) {
        log.error("Could not get resource resolver", e);
    } finally {
        // Always close resource resolvers you open
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
}

From source file:com.haulmont.cuba.gui.xml.layout.loaders.WindowLoader.java

protected void loadTimer(ComponentsFactory factory, final Window component, Element element) {
    Timer timer = factory.createTimer();
    timer.setXmlDescriptor(element);/*w  w  w  . j  a v  a 2  s.  c o m*/
    timer.setId(element.attributeValue("id"));
    String delay = element.attributeValue("delay");
    if (StringUtils.isEmpty(delay)) {
        throw new GuiDevelopmentException("Timer 'delay' can't be empty", context.getCurrentFrameId(),
                "Timer ID", timer.getId());
    }

    int value;
    try {
        value = Integer.parseInt(delay);
    } catch (NumberFormatException e) {
        throw new GuiDevelopmentException("Timer 'delay' must be numeric", context.getFullFrameId(),
                ParamsMap.of("Timer delay", delay, "Timer ID", timer.getId()));
    }

    if (value <= 0) {
        throw new GuiDevelopmentException("Timer 'delay' must be greater than 0", context.getFullFrameId(),
                "Timer ID", timer.getId());
    }

    timer.setDelay(value);
    timer.setRepeating(Boolean.parseBoolean(element.attributeValue("repeating")));

    String onTimer = element.attributeValue("onTimer");
    if (StringUtils.isNotEmpty(onTimer)) {
        String timerMethodName = onTimer;
        if (StringUtils.startsWith(onTimer, "invoke:")) {
            timerMethodName = StringUtils.substring(onTimer, "invoke:".length());
        }
        timerMethodName = StringUtils.trim(timerMethodName);

        addInitTimerMethodTask(timer, timerMethodName);
    }

    String autostart = element.attributeValue("autostart");
    if (StringUtils.isNotEmpty(autostart) && Boolean.parseBoolean(autostart)) {
        addAutoStartTimerTask(timer);
    }

    timer.setFrame(context.getFrame());

    component.addTimer(timer);
}

From source file:com.googlesource.gerrit.plugins.github.notification.WebhookServlet.java

/**
 * validates callback signature sent from github
 *
 * @param signatureHeader signature HTTP request header of a github webhook
 * @param payload HTTP request body/*  w w  w  . j  a va 2s .  c  o  m*/
 * @return true if webhook secret is not configured or signatureHeader is
 *         valid against payload and the secret, false if otherwise.
 * @throws UnsupportedEncodingException
 */
private boolean validateSignature(String signatureHeader, String body, String encoding)
        throws UnsupportedEncodingException {
    byte[] payload = body.getBytes(encoding == null ? "UTF-8" : encoding);
    if (config.webhookSecret == null || config.webhookSecret.equals("")) {
        logger.debug("{}.webhookSecret not configured. Skip signature validation", GitHubConfig.CONF_SECTION);
        return true;
    }

    if (!StringUtils.startsWith(signatureHeader, SIGNATURE_PREFIX)) {
        logger.error("Unsupported webhook signature type: {}", signatureHeader);
        return false;
    }
    byte[] signature;
    try {
        signature = Hex.decodeHex(signatureHeader.substring(SIGNATURE_PREFIX.length()).toCharArray());
    } catch (DecoderException e) {
        logger.error("Invalid signature: {}", signatureHeader);
        return false;
    }
    return MessageDigest.isEqual(signature, getExpectedSignature(payload));
}

From source file:com.fengduo.bee.commons.velocity.CustomVelocityLayoutView.java

private String buildViewName() {
    String url = getUrl();// w  w  w  .  j a va 2  s  .c  o  m
    if (StringUtils.startsWith(url, "/")) {
        url = url.substring(1, url.length());
    }
    return DEFAULT_VIEW_DIRECTORY + "/" + url;
}

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

/**
 * Avoids repeat delimiters/*from w  w  w .  j av  a 2 s.  c  o m*/
 * 
 * @param token
 * @param delimiter
 * @return
 */
private static String getDelimitered(String token, String delimiter) {
    if (StringUtils.isNotBlank(token) && !StringUtils.startsWith(token, delimiter)) {
        return delimiter + token;
    }
    return token;
}

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

/**
 * @return the file path relative to the data directory if it starts with the datadir,
 * otherwise returns absolute path./*from   w  ww .j ava 2s  .  c  o m*/
 * @throws Exception
 */
protected String getRelativeFilePath() throws Exception {
    String fullFileName = getFullFileName();
    String datadir = PathConstructor.createFromDefaultProperty();
    if (StringUtils.startsWith(fullFileName, datadir)) {
        String relativeFilename = StringUtils.removeStart(fullFileName, datadir);
        relativeFilename = StringUtils.removeStart(relativeFilename, "/");
        return relativeFilename;
    }
    return fullFileName;
}

From source file:hudson.plugins.clearcase.ucm.UcmMakeBaselineComposite.java

/**
 * Retrieve all Clearcase UCM component (with pvob suffix) for a stream
 *
 * @param stream the stream name like 'P_EngDesk_Product_3.2_int@\P_ORC'
 * @param clearTool the clearcase launcher
 * @return component list attached to the stream like ['DocGen_PapeeteDoc@\P_ORC','DocMgt_Modulo@\P_ORC']
 * @throws IOException/*from   w w w . jav  a  2s.  c  o m*/
 * @throws InterruptedException
 */
private List<String> getComponentList(ClearTool clearTool, String stream)
        throws IOException, InterruptedException {
    String output = clearTool.lsstream(stream, null, "\"%[components]XCp\"");
    String comp[] = output.split(",\\s");
    List<String> result = new ArrayList<String>();
    final String prefix = "component:";
    for (String c : comp) {
        if (StringUtils.startsWith(c, prefix)) {
            result.add(StringUtils.difference(prefix, c));
        } else {
            throw new IOException(
                    "Invalid format for component in output. Must starts with 'component:' : " + c);
        }
    }

    return result;
}

From source file:eionet.meta.imp.VocabularyCSVImportHandler.java

/**
 * In this method, beans are generated (either created or updated) according to values in CSV file.
 *
 * @throws eionet.meta.service.ServiceException
 *             if there is the input is invalid
 *///  w ww.ja  v  a 2 s.  co  m
public void generateUpdatedBeans() throws ServiceException {
    // content.
    CSVReader reader = new CSVReader(this.content);
    DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");

    try {
        String[] header = reader.readNext();

        // first check if headers contains fix columns
        String[] fixedHeaders = new String[VocabularyCSVOutputHelper.CONCEPT_ENTRIES_COUNT];
        VocabularyCSVOutputHelper.addFixedEntryHeaders(fixedHeaders);

        // compare if it has URI
        boolean isEqual = StringUtils.equalsIgnoreCase(header[VocabularyCSVOutputHelper.URI_INDEX],
                fixedHeaders[VocabularyCSVOutputHelper.URI_INDEX]);

        if (!isEqual) {
            reader.close();
            throw new ServiceException("Missing header! CSV file should start with header: '"
                    + fixedHeaders[VocabularyCSVOutputHelper.URI_INDEX] + "'");
        }

        List<String> fixedHeadersList = new ArrayList<String>(
                Arrays.asList(Arrays.copyOf(fixedHeaders, VocabularyCSVOutputHelper.CONCEPT_ENTRIES_COUNT)));
        // remove uri from header
        fixedHeadersList.remove(VocabularyCSVOutputHelper.URI_INDEX);
        Map<String, Integer> fixedHeaderIndices = new HashMap<String, Integer>();
        for (int i = VocabularyCSVOutputHelper.URI_INDEX + 1; i < header.length; i++) {
            String elementHeader = StringUtils.trimToNull(header[i]);
            if (StringUtils.isBlank(elementHeader)) {
                throw new ServiceException("Header for column (" + (i + 1) + ") is empty!");
            }

            int headerIndex = -1;
            boolean headerFound = false;
            for (headerIndex = 0; headerIndex < fixedHeadersList.size(); headerIndex++) {
                if (StringUtils.equalsIgnoreCase(elementHeader, fixedHeadersList.get(headerIndex))) {
                    headerFound = true;
                    break;
                }
            }

            // if it is a fixed header value (concept property), add to map and continue
            if (headerFound) {
                String headerValue = fixedHeadersList.remove(headerIndex);
                fixedHeaderIndices.put(headerValue, i);
                continue;
            }

            // it is not a concept attribute and but a data element identifier
            // if there is language appended, split it
            String[] tempStrArray = elementHeader.split("[@]");
            if (tempStrArray.length == 2) {
                elementHeader = tempStrArray[0];
            }

            // if bound elements do not contain header already, add it (if possible)
            if (!this.boundElementsIds.containsKey(elementHeader)) {
                // search for data element
                this.elementsFilter.setIdentifier(elementHeader);
                DataElementsResult elementsResult = this.dataService.searchDataElements(this.elementsFilter);
                // if there is one and only one element check if header and identifer exactly matches!
                if (elementsResult.getTotalResults() < 1) {
                    throw new ServiceException("Cannot find any data element for column: " + elementHeader
                            + ". Please bind element manually then upload CSV.");
                } else if (elementsResult.getTotalResults() > 1) {
                    throw new ServiceException("Cannot find single data element for column: " + elementHeader
                            + ". Search returns: " + elementsResult.getTotalResults()
                            + " elements. Please bind element manually then upload CSV.");
                } else {
                    DataElement elem = elementsResult.getDataElements().get(0);
                    if (StringUtils.equals(elementHeader, elem.getIdentifier())) {
                        // found it, add to list and map
                        this.boundElementsIds.put(elementHeader,
                                elementsResult.getDataElements().get(0).getId());
                        this.newBoundElement.add(elem);
                    } else {
                        throw new ServiceException("Found data element did not EXACTLY match with column: "
                                + elementHeader + ", found: " + elem.getIdentifier());
                    }
                }
            }
        } // end of for loop iterating on headers

        String[] lineParams;
        // first row is header so start from 2
        for (int rowNumber = 2; (lineParams = reader.readNext()) != null; rowNumber++) {
            if (lineParams.length != header.length) {
                StringBuilder message = new StringBuilder();
                message.append("Row (").append(rowNumber).append(") ");
                message.append("did not have same number of columns with header, it was skipped.");
                message.append(" It should have have same number of columns (empty or filled).");
                this.logMessages.add(message.toString());
                continue;
            }

            // do line processing
            String uri = lineParams[VocabularyCSVOutputHelper.URI_INDEX];
            if (StringUtils.isEmpty(uri)) {
                this.logMessages.add("Row (" + rowNumber + ") was skipped (Base URI was empty).");
                continue;
            } else if (StringUtils.startsWith(uri, "//")) {
                this.logMessages.add("Row (" + rowNumber
                        + ") was skipped (Concept was excluded by user from update operation).");
                continue;
            } else if (!StringUtils.startsWith(uri, this.folderContextRoot)) {
                this.logMessages
                        .add("Row (" + rowNumber + ") was skipped (Base URI did not match with Vocabulary).");
                continue;
            }

            String conceptIdentifier = uri.replace(this.folderContextRoot, "");
            if (StringUtils.contains(conceptIdentifier, "/") || !Util.isValidIdentifier(conceptIdentifier)) {
                this.logMessages.add("Row (" + rowNumber + ") did not contain a valid concept identifier.");
                continue;
            }

            // now we have a valid row
            Pair<VocabularyConcept, Boolean> foundConceptWithFlag = findOrCreateConcept(conceptIdentifier);

            // if vocabulary concept duplicated with another row, importer will ignore it not to repeat
            if (foundConceptWithFlag == null || foundConceptWithFlag.getRight()) {
                this.logMessages
                        .add("Row (" + rowNumber + ") duplicated with a previous concept, it was skipped.");
                continue;
            }

            VocabularyConcept lastFoundConcept = foundConceptWithFlag.getLeft();
            // vocabulary concept found or created
            this.toBeUpdatedConcepts.add(lastFoundConcept);

            Integer conceptPropertyIndex = null;
            // check label
            conceptPropertyIndex = fixedHeaderIndices.get(fixedHeaders[VocabularyCSVOutputHelper.LABEL_INDEX]);
            if (conceptPropertyIndex != null) {
                lastFoundConcept.setLabel(StringUtils.trimToNull(lineParams[conceptPropertyIndex]));
            }

            // check definition
            conceptPropertyIndex = fixedHeaderIndices
                    .get(fixedHeaders[VocabularyCSVOutputHelper.DEFINITION_INDEX]);
            if (conceptPropertyIndex != null) {
                lastFoundConcept.setDefinition(StringUtils.trimToNull(lineParams[conceptPropertyIndex]));
            }

            // check notation
            conceptPropertyIndex = fixedHeaderIndices
                    .get(fixedHeaders[VocabularyCSVOutputHelper.NOTATION_INDEX]);
            if (conceptPropertyIndex != null) {
                lastFoundConcept.setNotation(StringUtils.trimToNull(lineParams[conceptPropertyIndex]));
            }

            // TODO: update - with merging flexible csv import
            // check start date
            // ignore status and accepteddate changes

            // now it is time iterate on rest of the columns, here is the tricky part
            List<DataElement> elementsOfConcept = null;
            List<DataElement> elementsOfConceptByLang = null;
            String prevHeader = null;
            String prevLang = null;
            for (int k = VocabularyCSVOutputHelper.URI_INDEX + 1; k < lineParams.length; k++) {
                if (StringUtils.isEmpty(lineParams[k])) {
                    // value is empty, no need to proceed
                    continue;
                }

                if (fixedHeaderIndices.containsValue(k)) {
                    // concept property, already handled
                    continue;
                }

                String elementHeader = header[k];
                String lang = null;
                String[] tempStrArray = elementHeader.split("[@]");
                if (tempStrArray.length == 2) {
                    elementHeader = tempStrArray[0];
                    lang = tempStrArray[1];
                }

                if (!StringUtils.equals(elementHeader, prevHeader)) {
                    elementsOfConcept = getDataElementValuesByName(elementHeader,
                            lastFoundConcept.getElementAttributes());
                    if (elementsOfConcept == null) {
                        elementsOfConcept = new ArrayList<DataElement>();
                        lastFoundConcept.getElementAttributes().add(elementsOfConcept);
                    }
                }

                if (!StringUtils.equals(elementHeader, prevHeader) || !StringUtils.equals(lang, prevLang)) {
                    elementsOfConceptByLang = getDataElementValuesByNameAndLang(elementHeader, lang,
                            lastFoundConcept.getElementAttributes());
                }

                prevLang = lang;
                prevHeader = elementHeader;

                VocabularyConcept foundRelatedConcept = null;
                if (Util.isValidUri(lineParams[k])) {
                    foundRelatedConcept = findRelatedConcept(lineParams[k]);
                }

                // check for pre-existence of the VCE by attribute value or related concept id
                Integer relatedId = null;
                if (foundRelatedConcept != null) {
                    relatedId = foundRelatedConcept.getId();
                }
                boolean returnFromThisPoint = false;
                for (DataElement elemByLang : elementsOfConceptByLang) {
                    String elementValueByLang = elemByLang.getAttributeValue();
                    if (StringUtils.equals(lineParams[k], elementValueByLang)) {
                        // vocabulary concept element already in database, no need to continue, return
                        returnFromThisPoint = true;
                        break;
                    }

                    if (relatedId != null) {
                        Integer relatedConceptId = elemByLang.getRelatedConceptId();
                        if (relatedConceptId != null && relatedConceptId.intValue() == relatedId.intValue()) {
                            // vocabulary concept element already in database, no need to continue, return
                            returnFromThisPoint = true;
                            break;
                        }
                    }
                }
                // check if an existing VCE found or not
                if (returnFromThisPoint) {
                    continue;
                }

                // create VCE
                DataElement elem = new DataElement();
                elementsOfConcept.add(elem);
                elem.setAttributeLanguage(lang);
                elem.setIdentifier(elementHeader);
                elem.setId(this.boundElementsIds.get(elementHeader));
                // check if there is a found related concept
                if (foundRelatedConcept != null) {
                    elem.setRelatedConceptIdentifier(foundRelatedConcept.getIdentifier());
                    int id = foundRelatedConcept.getId();
                    elem.setRelatedConceptId(id);
                    elem.setAttributeValue(null);
                    if (id < 0) {
                        addToElementsReferringNotCreatedConcepts(id, elem);
                    }
                } else {
                    elem.setAttributeValue(lineParams[k]);
                    elem.setRelatedConceptId(null);
                }
            } // end of for loop iterating on rest of the columns (for data elements)
        } // end of row iterator (while loop on rows)
        processUnseenConceptsForRelatedElements();
    } catch (IOException e) {
        e.printStackTrace();
        throw new ServiceException(e.getMessage());
    } catch (RuntimeException e) {
        e.printStackTrace();
        throw new ServiceException(e.getMessage());
    } finally {
        try {
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}