Example usage for org.apache.commons.lang3 StringUtils startsWithIgnoreCase

List of usage examples for org.apache.commons.lang3 StringUtils startsWithIgnoreCase

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils startsWithIgnoreCase.

Prototype

public static boolean startsWithIgnoreCase(final CharSequence str, final CharSequence prefix) 

Source Link

Document

Case insensitive check if a CharSequence starts with a specified prefix.

null s are handled without exceptions.

Usage

From source file:org.kalypso.ui.rrm.internal.results.view.tree.strategies.NaModelStrategy.java

@Override
public TreeNode buildNodes(final TreeNodeModel model) {
    final TreeNode virtualRootNode = new TreeNode(model, null, null, null);

    try {/* ww  w.j a  va 2  s  .c  o  m*/
        final IFolder folderSimulations = m_scenario.getSimulationsFolder();

        folderSimulations.accept(new IResourceVisitor() {
            @Override
            public boolean visit(final IResource resource) {
                if (!(resource instanceof IFolder))
                    return true;
                else if (isBaseFolder((IFolder) resource))
                    return true;
                else if (isCalculationCaseFolder((IFolder) resource)) {
                    if (StringUtils.startsWithIgnoreCase(resource.getName(), "tmp")) //$NON-NLS-1$
                        return true;

                    virtualRootNode.addChild(
                            buildCalculationCaseNodes(virtualRootNode, new RrmSimulation((IFolder) resource)));
                    return true;
                }

                return true;
            }

            private boolean isBaseFolder(final IFolder folder) {
                return folder.equals(folderSimulations);
            }

            private boolean isCalculationCaseFolder(final IFolder folder) {
                return folder.getParent().equals(folderSimulations);
            }

        }, 1, false);
    } catch (final Exception ex) {
        ex.printStackTrace();
    }

    /* tree is empty? so add empty node */
    if (ArrayUtils.isEmpty(virtualRootNode.getChildren()))
        doAddEmptyNode(virtualRootNode);

    return virtualRootNode;
}

From source file:org.kuali.coeus.common.questionnaire.impl.answer.QuestionnaireAnswerServiceImpl.java

protected boolean isAnswerMatched(String condition, String parentAnswer, String conditionValue) {
    boolean valid = false;
    if (ConditionType.CONTAINS_TEXT.getCondition().equals(condition)) {
        valid = StringUtils.containsIgnoreCase(parentAnswer, conditionValue);
    } else if (ConditionType.BEGINS_WITH_TEXT.getCondition().equals(condition)) {
        valid = (StringUtils.startsWithIgnoreCase(parentAnswer, conditionValue));
    } else if (ConditionType.ENDS_WITH_TEXT.getCondition().equals(condition)) {
        valid = (StringUtils.endsWithIgnoreCase(parentAnswer, conditionValue));
    } else if (ConditionType.MATCH_TEXT.getCondition().equals(condition)) {
        valid = parentAnswer.equalsIgnoreCase(conditionValue);
    } else if (Integer.parseInt(condition) >= 5 && Integer.parseInt(condition) <= 10) {
        valid = (ConditionType.LESS_THAN_NUMBER.getCondition().equals(condition)
                && (Integer.parseInt(parentAnswer) < Integer.parseInt(conditionValue)))
                || (ConditionType.LESS_THAN_OR_EQUALS_NUMBER.getCondition().equals(condition)
                        && (Integer.parseInt(parentAnswer) <= Integer.parseInt(conditionValue)))
                || (ConditionType.EQUALS_NUMBER.getCondition().equals(condition)
                        && (Integer.parseInt(parentAnswer) == Integer.parseInt(conditionValue)))
                || (ConditionType.NOT_EQUAL_TO_NUMBER.getCondition().equals(condition)
                        && (Integer.parseInt(parentAnswer) != Integer.parseInt(conditionValue)))
                || (ConditionType.GREATER_THAN_OR_EQUALS_NUMBER.getCondition().equals(condition)
                        && (Integer.parseInt(parentAnswer) >= Integer.parseInt(conditionValue)))
                || (ConditionType.GREATER_THAN_NUMBER.getCondition().equals(condition)
                        && (Integer.parseInt(parentAnswer) > Integer.parseInt(conditionValue)));
    } else if (Integer.parseInt(condition) == 11 || Integer.parseInt(condition) == 12) {
        final DateFormat dateFormat = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT_PATTERN);
        try {/* www .j  a  va  2  s .  c  om*/
            Date date1 = new Date(dateFormat.parse(parentAnswer).getTime());
            Date date2 = new Date(dateFormat.parse(conditionValue).getTime());
            valid = (ConditionType.BEFORE_DATE.getCondition().equals(condition) && (date1.before(date2)))
                    || (ConditionType.AFTER_DATE.getCondition().equals(condition) && (date1.after(date2)));
        } catch (Exception e) {

        }

    }
    return valid;
}

From source file:org.kuali.coeus.sys.framework.model.KcTransactionalDocumentFormBase.java

/**
 * This is a duplication of KualiTransactionalDocumentFormBase.populateFalseCheckboxes with the cavet that this function
 * puts a NULL in for fields that contain "answer", which are the field names of radio Y/N buttons for the questionnaire framework.
 * @see org.kuali.rice.kns.web.struts.form.KualiTransactionalDocumentFormBase#populateFalseCheckboxes(javax.servlet.http.HttpServletRequest)
 *//*  w w w . ja  va  2 s.  c  o  m*/
@Override
protected void populateFalseCheckboxes(HttpServletRequest request) {
    Map<String, String[]> parameterMap = request.getParameterMap();
    final String checkBoxToResetFieldParam = "checkboxToReset";
    if (parameterMap.get(checkBoxToResetFieldParam) != null) {
        final String[] checkboxesToResetFields = request.getParameterValues("checkboxToReset");
        if (checkboxesToResetFields != null && checkboxesToResetFields.length > 0) {
            for (int i = 0; i < checkboxesToResetFields.length; i++) {
                String propertyName = (String) checkboxesToResetFields[i];
                if (!StringUtils.isBlank(propertyName) && parameterMap.get(propertyName) == null) {
                    if (this instanceof QuestionableFormInterface
                            && (StringUtils.startsWithIgnoreCase(propertyName,
                                    ((QuestionableFormInterface) this).getQuestionnaireFieldStarter())
                                    && StringUtils.containsIgnoreCase(propertyName,
                                            ((QuestionableFormInterface) this).getQuestionnaireFieldMiddle())
                                    && StringUtils.endsWithIgnoreCase(propertyName,
                                            ((QuestionableFormInterface) this).getQuestionnaireFieldEnd())
                                    || propertyName.matches(
                                            ((QuestionableFormInterface) this).getQuestionnaireExpression()))) {
                        populateForProperty(propertyName, null, parameterMap);
                    } else if (this instanceof MultiQuestionableFormInterface) {
                        processMultiQuestionCheckBox(propertyName, parameterMap,
                                (MultiQuestionableFormInterface) this);

                    } else {
                        populateForProperty(propertyName,
                                KimConstants.KIM_ATTRIBUTE_BOOLEAN_FALSE_STR_VALUE_DISPLAY, parameterMap);
                    }
                } else if (!StringUtils.isBlank(propertyName) && parameterMap.get(propertyName) != null
                        && parameterMap.get(propertyName).length >= 1
                        && parameterMap.get(propertyName)[0].equalsIgnoreCase("on")) {
                    populateForProperty(propertyName, KimConstants.KIM_ATTRIBUTE_BOOLEAN_TRUE_STR_VALUE_DISPLAY,
                            parameterMap);
                }
            }
        }
    }
}

From source file:org.kuali.coeus.sys.framework.model.KcTransactionalDocumentFormBase.java

protected void processMultiQuestionCheckBox(String propertyName, Map<String, String[]> parameterMap,
        MultiQuestionableFormInterface form) {
    boolean checkBoxFound = false;
    int j = 0;/*from   w w  w . j av a2 s.com*/
    for (String starter : form.getQuestionnaireFieldStarters()) {
        if (!checkBoxFound && StringUtils.startsWithIgnoreCase(propertyName, starter)
                && StringUtils.containsIgnoreCase(propertyName, form.getQuestionnaireFieldEnds()[j])
                && StringUtils.endsWithIgnoreCase(propertyName, form.getQuestionnaireFieldEnds()[j])) {
            populateForProperty(propertyName, null, parameterMap);
            ;
            checkBoxFound = true;
            break;
        }
        j++;
    }
    if (!checkBoxFound) {
        populateForProperty(propertyName, KimConstants.KIM_ATTRIBUTE_BOOLEAN_FALSE_STR_VALUE_DISPLAY,
                parameterMap);
    }
}

From source file:org.ligoj.app.plugin.prov.aws.in.ProvAwsPriceImportResource.java

/**
 * EC2 spot installer. Install the instance type (if needed), the instance price type (if needed) and the price.
 *
 * @param context/*w ww .  j a  v a  2 s .c  o m*/
 *            The update context.
 * @param json
 *            The current JSON entry.
 * @param spotPriceType
 *            The related AWS Spot instance price type.
 * @param region
 *            The target region.
 * @return The amount of installed prices. Only for the report.
 */
private int install(final UpdateContext context, final AwsEc2SpotPrice json,
        final ProvInstancePriceTerm spotPriceType, final ProvLocation region) {
    return (int) json.getOsPrices().stream()
            .filter(op -> !StringUtils.startsWithIgnoreCase(op.getPrices().get("USD"), "N/A")).map(op -> {
                final VmOs os = op.getName().equals("mswin") ? VmOs.WINDOWS : VmOs.LINUX;
                final ProvInstanceType type = context.getInstanceTypes().get(json.getName());

                // Build the key for this spot
                final String code = "spot-" + region.getName() + "-" + type.getName() + "-" + os.name();
                final ProvInstancePrice price = Optional.ofNullable(context.getPrevious().get(code))
                        .orElseGet(() -> {
                            final ProvInstancePrice p = new ProvInstancePrice();
                            p.setCode(code);
                            p.setType(type);
                            p.setTerm(spotPriceType);
                            p.setTenancy(ProvTenancy.SHARED);
                            p.setOs(os);
                            p.setLocation(region);
                            return p;
                        });

                // Update the price as needed
                final double cost = Double.parseDouble(op.getPrices().get("USD"));
                return saveAsNeeded(price, round3Decimals(cost * 24 * 30.5), p -> {
                    p.setCostPeriod(cost);
                    ipRepository.save(price);
                });
            }).count();
}

From source file:org.mitre.mpf.mvc.model.FileTreeNode.java

public FileTreeNode(File f) {
    this.text = f.getName();
    this.fullPath = f.getAbsolutePath();
    if (f.isFile()) {
        this.file = true;
        //this will prevent the node from having the ability to expand
        this.nodes = null;

        //TODO: move this checking to a method!
        String name = f.getName();

        String extension = "";
        int i = name.lastIndexOf('.');
        if (i > 0) {
            extension = name.toLowerCase().substring(i + 1);
        }/*from w w  w.  ja  va 2 s .c o m*/

        //TODO: would save processing if not going from Java 6 to Java 7/8
        Path p = Paths.get(this.fullPath, name);
        String contentType = "";
        try {
            contentType = Files.probeContentType(p);
        } catch (Exception ex) {
            //TODO: a logger in here would probably break serialization - should move the content retrieval to another method
            //log.error("An exception occurred when trying to determine the content type of the file '{}': {}", f.getAbsolutePath(), ex);
        }

        //photo ?
        // glyphicon glyphicon-picture
        //audio ?
        // glyphicon glyphicon-music   
        //video ?
        // glyphicon glyphicon-film

        if (StringUtils.startsWithIgnoreCase(contentType, "AUDIO")) {
            this.icon = "glyphicon glyphicon-music";
        } else if (StringUtils.startsWithIgnoreCase(contentType, "IMAGE")) {
            this.icon = "glyphicon glyphicon-picture";
        } else if (StringUtils.startsWithIgnoreCase(contentType, "VIDEO")) {
            this.icon = "glyphicon glyphicon-film";
        } else {
            //TODO: doesn't display an mkv, capital JPG            
            //TODO: should not be included!!
            //TOOD: could use the extension as a backup if the content-type is ignored
            this.icon = "glyphicon glyphicon-file";
        }
    } else {
        //directory
        if (f.list().length <= 0) {
            //icon should be a closed folder by default
            this.nodes = null;
        }

        //set the expansion to false because the node will automatically expand if/when nodes are added
        //the expanded state will stay with the node
        this.state.expanded = false;
    }
}

From source file:org.mitre.mpf.mvc.util.ModelUtils.java

public static MarkupResultModel converMarkupResult(MarkupResult markupResult) {
    boolean isImage = false;
    boolean fileExists = true;
    if (markupResult.getMarkupUri() != null) {
        String nonUrlPath = markupResult.getMarkupUri().replace("file:", "");
        String markupContentType = NIOUtils.getPathContentType(Paths.get(nonUrlPath));
        isImage = (markupContentType != null && StringUtils.startsWithIgnoreCase(markupContentType, "IMAGE"));
        fileExists = new File(nonUrlPath).exists();
    }/*w ww.j av  a2  s  .c om*/

    //if the markup uri does not end with 'avi', the file is considered an image
    return new MarkupResultModel(markupResult.getId(), markupResult.getJobId(), markupResult.getPipeline(),
            markupResult.getMarkupUri(), markupResult.getSourceUri(), isImage, fileExists);
}

From source file:org.mitre.mpf.mvc.util.NIOUtils.java

public static String getFileTreeNodeIconString(final Path path, final List<String> customExtensions) {
    //photo ?//w  ww  . j  a  va  2 s  .  c om
    // glyphicon glyphicon-picture
    //audio ?
    // glyphicon glyphicon-music   
    //video ?
    // glyphicon glyphicon-film
    //other extensions
    // glyphicon glyphicon-file

    String iconStr = null;
    if (path != null && Files.isRegularFile(path)) {
        String contentType = getPathContentType(path);

        if (contentType != null) {
            if (StringUtils.startsWithIgnoreCase(contentType, "AUDIO")) {
                iconStr = "glyphicon glyphicon-music";
            } else if (StringUtils.startsWithIgnoreCase(contentType, "IMAGE")) {
                iconStr = "glyphicon glyphicon-picture";
            } else if (StringUtils.startsWithIgnoreCase(contentType, "VIDEO")) {
                iconStr = "glyphicon glyphicon-film";
            } else if (customExtensions != null && !customExtensions.isEmpty()) {
                //java NIO does not have an implemented solution for getting the extension - makes sense
                String ext = FilenameUtils.getExtension(path.getFileName().toString());
                if (customExtensions.contains(ext)) {
                    iconStr = "glyphicon glyphicon-file";
                }
            }
        }
    }

    return iconStr;
}

From source file:org.mitre.mpf.wfm.camelOps.TestMediaInspectionProcessor.java

License:asdf

@Test(timeout = 5 * MINUTES)
public void testImageInspection() throws Exception {
    log.info("Starting image inspection test.");

    TransientMedia transientMedia = new TransientMedia(next(),
            ioUtils.findFile("/samples/meds1.jpg").toString());
    Exchange exchange = new DefaultExchange(camelContext);
    exchange.getIn().getHeaders().put(MpfHeaders.JOB_ID, next());
    exchange.getIn().setBody(jsonUtils.serialize(transientMedia));
    mediaInspectionProcessor.process(exchange);

    Object responseBody = exchange.getOut().getBody();
    Assert.assertTrue("A response body must be set.", responseBody != null);
    Assert.assertTrue(String.format("Response body must be a byte[]. Actual: %s.", responseBody.getClass()),
            responseBody instanceof byte[]);

    // Implied assertion: Deserialization works.
    TransientMedia responseTransientMedia = jsonUtils.deserialize((byte[]) responseBody, TransientMedia.class);

    Assert.assertTrue(//from   ww  w  . ja  v  a2  s .c om
            String.format("The response entity must not fail. Actual: %s. Message: %s.",
                    Boolean.toString(responseTransientMedia.isFailed()), responseTransientMedia.getMessage()),
            !responseTransientMedia.isFailed());

    String targetType = "image";
    Assert.assertTrue(
            String.format("The medium's type should begin with '%s'. Actual: %s.", targetType,
                    responseTransientMedia.getType()),
            StringUtils.startsWithIgnoreCase(responseTransientMedia.getType(), targetType));

    int targetLength = 1;
    Assert.assertTrue(String.format("The medium's length should be %d. Actual: %d.", targetLength,
            responseTransientMedia.getLength()), responseTransientMedia.getLength() == targetLength);

    String targetHash = "c067e7eed23a0fe022140c30dbfa993ae720309d6567a803d111ecec739a6713";//`sha256sum meds1.jpg`
    Assert.assertTrue(
            String.format("The medium's hash should have matched '%s'. Actual: %s.", targetHash,
                    responseTransientMedia.getSha256()),
            targetHash.equalsIgnoreCase(responseTransientMedia.getSha256()));

    log.info("Image inspection passed.");
}

From source file:org.mitre.mpf.wfm.camelOps.TestMediaInspectionProcessor.java

License:asdf

/** Tests that the results from a video file are sane. */
@Test(timeout = 5 * MINUTES)/*from  w  w  w  .j  ava2  s  .c  o  m*/
public void testVideoInspection() throws Exception {
    log.info("Starting video inspection test.");

    TransientMedia transientMedia = new TransientMedia(next(),
            ioUtils.findFile("/samples/video_01.mp4").toString());

    Exchange exchange = new DefaultExchange(camelContext);
    exchange.getIn().getHeaders().put(MpfHeaders.JOB_ID, next());
    exchange.getIn().setBody(jsonUtils.serialize(transientMedia));
    mediaInspectionProcessor.process(exchange);

    Object responseBody = exchange.getOut().getBody();
    Assert.assertTrue("A response body must be set.", responseBody != null);
    Assert.assertTrue(String.format("Response body must be a byte[]. Actual: %s.", responseBody.getClass()),
            responseBody instanceof byte[]);

    // Implied assertion: Deserialization works.
    TransientMedia responseTransientMedia = jsonUtils.deserialize((byte[]) responseBody, TransientMedia.class);

    Assert.assertTrue(
            String.format("The response entity must not fail. Actual: %s. Message: %s.",
                    Boolean.toString(responseTransientMedia.isFailed()), responseTransientMedia.getMessage()),
            !responseTransientMedia.isFailed());

    String targetType = "video";
    Assert.assertTrue(
            String.format("The medium's type should begin with '%s'. Actual: %s.", targetType,
                    responseTransientMedia.getType()),
            StringUtils.startsWithIgnoreCase(responseTransientMedia.getType(), targetType));

    int targetLength = 90; //`ffprobe -show_packets video_01.mp4 | grep video | wc -l`
    Assert.assertTrue(String.format("The medium's length should be %d. Actual: %d.", targetLength,
            responseTransientMedia.getLength()), responseTransientMedia.getLength() == targetLength);

    String targetHash = "5eacf0a11d51413300ee0f4719b7ac7b52b47310a49320703c1d2639ebbc9fea"; //`sha256sum video_01.mp4`
    Assert.assertTrue(
            String.format("The medium's hash should have matched '%s'. Actual: %s.", targetHash,
                    responseTransientMedia.getSha256()),
            targetHash.equalsIgnoreCase(responseTransientMedia.getSha256()));

    log.info("Video inspection passed.");
}