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

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

Introduction

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

Prototype

public static String stripStart(String str, String stripChars) 

Source Link

Document

Strips any of a set of characters from the start of a String.

Usage

From source file:org.jamwiki.parser.jflex.JFlexLexer.java

/**
 *
 *//* ww w.j a  va2 s.  c o m*/
protected void parseParagraphEmpty(String raw) {
    // push back everything up to the last of the opening newlines that were matched
    yypushback(StringUtils.stripStart(raw, " \n\r\t").length() + 1);
    if (this.mode < JFlexParser.MODE_LAYOUT) {
        return;
    }
    int newlineCount = 0;
    for (int i = 0; i < raw.length(); i++) {
        if (raw.charAt(i) != '\n') {
            // only count newlines for paragraph creation
            continue;
        }
        newlineCount++;
        if (newlineCount % 2 != 0) {
            // two newlines are required to create a paragraph
            continue;
        }
        this.pushTag("p", null);
        this.append("<br />\n");
        this.popTag("p");
    }
}

From source file:org.jboss.maven.plugins.qstools.checkers.ReadmeChecker.java

/**
 * Check if the file contains all defined metadata
 *//*from   w  w  w .  j av  a2s . c  o  m*/
private void checkReadmeFile(String groupId, File readme, Map<String, List<Violation>> results)
        throws IOException {
    Map<String, String> metadatas = getConfigurationProvider().getQuickstartsRules(groupId)
            .getReadmeMetadatas();
    BufferedReader br = new BufferedReader(new FileReader(readme));
    try {
        Pattern p = Pattern.compile(regexPattern);
        List<String> usedPatterns = new ArrayList<String>();
        Map<String, String> usedValues = new HashMap<String, String>();
        while (br.ready()) {
            String line = br.readLine();
            Matcher m = p.matcher(line);
            if (m.find()) {
                usedPatterns.add(m.group());
                usedValues.put(m.group(),
                        StringUtils.stripStart(line.substring(m.group().length(), line.length()), " "));
            }
        }
        for (String metadataRaw : metadatas.keySet()) {
            String metadata = metadataRaw.replace("FOLDER-NAME", folderName);
            if (usedPatterns.contains(metadata)) {
                String value = usedValues.get(metadata);
                String expected = metadatas.get(metadataRaw);
                if (!value.matches(expected)) {
                    String msg = "Content for metadata [%s = %s] should follow the [%s] pattern";
                    addViolation(readme, results, 0, String.format(msg, metadata, value, expected));
                }
            } else {
                String msg = "File doesn't contain [%s] metadata";
                addViolation(readme, results, 3, String.format(msg, metadata));

            }
        }
        if (!usedPatterns.contains(folderName)) {
            String msg = "Readme title doesn't match the folder name: " + folderName;
            addViolation(readme, results, 1, msg);
        }
    } finally {
        if (br != null) {
            br.close();
        }
    }

}

From source file:org.kuali.rice.krad.datadictionary.MessageBeanProcessor.java

/**
 * Applies the text for a given message to the associated bean definition property
 *
 * @param message message instance to apply
 * @param beanDefinition bean definition the message should be applied to
 * @param beanClass class for the bean definition
 *//*from  ww  w  .j  ava 2 s.c  om*/
protected void applyMessageToBean(Message message, BeanDefinition beanDefinition, Class<?> beanClass) {
    String key = message.getKey().trim();

    // if message doesn't start with path indicator, it will be an explicit key that is matched when
    // iterating over the property values, so we will just return in that case
    if (!key.startsWith(KRADConstants.MESSAGE_KEY_PATH_INDICATOR)) {
        return;
    }

    // if here dealing with a path key, strip off indicator and then process as a property path
    key = StringUtils.stripStart(key, KRADConstants.MESSAGE_KEY_PATH_INDICATOR);

    // list factory beans just have the one list property (with no name)
    if (ListFactoryBean.class.isAssignableFrom(beanClass)) {
        MutablePropertyValues pvs = beanDefinition.getPropertyValues();

        PropertyValue propertyValue = pvs.getPropertyValueList().get(0);
        List<?> listValue = (List<?>) propertyValue.getValue();

        applyMessageToNestedListBean(message, listValue, key);
    } else if (StringUtils.contains(key, ".")) {
        applyMessageToNestedBean(message, beanDefinition, key);
    } else {
        applyMessageTextToPropertyValue(key, message.getText(), beanDefinition);
    }
}

From source file:org.kuali.rice.krad.datadictionary.MessageBeanProcessor.java

/**
 * Checks a string property value for a message placeholder and if found the message is retrieved and updated
 * in the property value//  w ww . ja  va2 s  .  c o  m
 *
 * @param propertyValue string value to process for message placeholders
 * @param nestedBeanStack stack of bean definitions that contain the property, used to determine the namespace
 * and component for the message retrieval
 * @return String new value for the property (possibly modified from an external message)
 */
protected String processMessagePlaceholders(String propertyValue, Stack<BeanDefinitionHolder> nestedBeanStack) {
    String trimmedPropertyValue = StringUtils.stripStart(propertyValue, " ");
    if (StringUtils.isBlank(trimmedPropertyValue)) {
        return propertyValue;
    }

    String newPropertyValue = propertyValue;

    // first check for a replacement message key
    if (trimmedPropertyValue.startsWith(KRADConstants.MESSAGE_KEY_PLACEHOLDER_PREFIX)
            && StringUtils.contains(trimmedPropertyValue, KRADConstants.MESSAGE_KEY_PLACEHOLDER_SUFFIX)) {
        String messageKeyStr = StringUtils.substringBetween(trimmedPropertyValue,
                KRADConstants.MESSAGE_KEY_PLACEHOLDER_PREFIX, KRADConstants.MESSAGE_KEY_PLACEHOLDER_SUFFIX);

        // get any default specified value (given after the message key)
        String messageKeyWithPlaceholder = KRADConstants.MESSAGE_KEY_PLACEHOLDER_PREFIX + messageKeyStr
                + KRADConstants.MESSAGE_KEY_PLACEHOLDER_SUFFIX;

        String defaultPropertyValue = StringUtils.substringAfter(trimmedPropertyValue,
                messageKeyWithPlaceholder);

        // set the new property value to the message text (if found), or the default value if a message was not found
        // note the message text could be an empty string, in which case it will override the default
        String messageText = getMessageTextForKey(messageKeyStr, nestedBeanStack);
        if (messageText != null) {
            // if default value set then we need to merge any expressions
            if (StringUtils.isNotBlank(defaultPropertyValue)) {
                newPropertyValue = getMergedMessageText(messageText, defaultPropertyValue);
            } else {
                newPropertyValue = messageText;
            }
        } else {
            newPropertyValue = defaultPropertyValue;
        }
    }
    // now check for message keys within an expression
    else if (StringUtils.contains(trimmedPropertyValue, KRADConstants.EXPRESSION_MESSAGE_PLACEHOLDER_PREFIX)) {
        String[] expressionMessageKeys = StringUtils.substringsBetween(newPropertyValue,
                KRADConstants.EXPRESSION_MESSAGE_PLACEHOLDER_PREFIX,
                KRADConstants.EXPRESSION_MESSAGE_PLACEHOLDER_SUFFIX);

        for (String expressionMessageKey : expressionMessageKeys) {
            String expressionMessageText = getMessageTextForKey(expressionMessageKey, nestedBeanStack);
            newPropertyValue = StringUtils
                    .replace(newPropertyValue,
                            KRADConstants.EXPRESSION_MESSAGE_PLACEHOLDER_PREFIX + expressionMessageKey
                                    + KRADConstants.EXPRESSION_MESSAGE_PLACEHOLDER_SUFFIX,
                            expressionMessageText);
        }
    }

    return newPropertyValue;
}

From source file:org.obiba.mica.file.notification.FilePublicationFlowMailNotification.java

public void send(String path, RevisionStatus current, RevisionStatus status) {
    if (micaConfigService.getConfig().isFsNotificationsEnabled() && current != status) {
        String[] documentParts = StringUtils.stripStart(path, "/").split("/");
        if (documentParts.length < 2)
            return;
        String documentInstance = String.format("/%s/%s", documentParts[0], documentParts[1]);

        Map<String, String> ctx = createContext();
        ctx.put("document", documentInstance);
        ctx.put("documentType", documentParts[0]);
        ctx.put("documentId", documentParts[1]);
        ctx.put("path", path);

        List<SubjectAcl> acls = subjectAclService.findByResourceInstance("/draft/file", documentInstance);
        String subject = mailService.getSubject(micaConfigService.getConfig().getFsNotificationsSubject(), ctx,
                DEFAULT_FILE_NOTIFICATION_SUBJECT);

        sendNotification(status, ctx, subject, FILE_NOTIFICATION_TEMPLATE, acls);
    }//w  ww. ja  v a 2s. c  om
}

From source file:org.openhab.binding.homematic.internal.config.binding.DatapointConfig.java

/**
 * Sets the address, strips a leading CCU team marker.
 *//* www  .j av a 2 s  .co m*/
private void setAddress(String address) {
    this.address = StringUtils.stripStart(address, "*");
}

From source file:org.opennms.netmgt.provision.service.dns.DnsRequisitionUrlConnection.java

/**
 * Creates an instance of the JaxB annotated RequisionNode class.
 * /*from   w w  w . ja  v a  2 s  .co  m*/
 * @param rec
 * @return a populated RequisitionNode based on defaults and data from the
 *   A record returned from a DNS zone transfer query.
 */
private RequisitionNode createRequisitionNode(Record rec) {
    String addr = null;
    if ("A".equals(Type.string(rec.getType()))) {
        ARecord arec = (ARecord) rec;
        addr = StringUtils.stripStart(arec.getAddress().toString(), "/");
    } else if ("AAAA".equals(Type.string(rec.getType()))) {
        AAAARecord aaaarec = (AAAARecord) rec;
        addr = aaaarec.rdataToString();
    } else {
        throw new IllegalArgumentException(
                "Invalid record type " + Type.string(rec.getType()) + ". A or AAAA expected.");
    }

    RequisitionNode n = new RequisitionNode();

    String host = rec.getName().toString();
    String nodeLabel = StringUtils.stripEnd(StringUtils.stripStart(host, "."), ".");

    n.setBuilding(getForeignSource());

    switch (m_foreignIdHashSource) {
    case 1:
        n.setForeignId(computeHashCode(nodeLabel));
        LOG.debug("Generating foreignId from hash of nodelabel {}", nodeLabel);
        break;
    case 2:
        n.setForeignId(computeHashCode(addr));
        LOG.debug("Generating foreignId from hash of ipAddress {}", addr);
        break;
    case 3:
        n.setForeignId(computeHashCode(nodeLabel + addr));
        LOG.debug("Generating foreignId from hash of nodelabel+ipAddress {}{}", nodeLabel, addr);
        break;
    default:
        n.setForeignId(computeHashCode(nodeLabel));
        LOG.debug("Default case: Generating foreignId from hash of nodelabel {}", nodeLabel);
        break;
    }
    n.setNodeLabel(nodeLabel);

    RequisitionInterface i = new RequisitionInterface();
    i.setDescr("DNS-" + Type.string(rec.getType()));
    i.setIpAddr(addr);
    i.setSnmpPrimary(PrimaryType.PRIMARY);
    i.setManaged(Boolean.TRUE);
    i.setStatus(Integer.valueOf(1));

    for (String service : m_services) {
        service = service.trim();
        i.insertMonitoredService(new RequisitionMonitoredService(service));
        LOG.debug("Adding provisioned service {}", service);
    }

    n.putInterface(i);

    return n;
}

From source file:org.opentestsystem.delivery.testreg.upload.validator.fileformat.DuplicateRecordProcessor.java

private String getNcesId(final String ncesIdValue) {
    return StringUtils.stripStart(ncesIdValue, "0");
}

From source file:org.owasp.jbrofuzz.core.Verifier.java

/**
 * <p>Method responsible for parsing the printable
 * String contents of the file fuzzers.jbrf to
 * the prototype HashMap.</p>// www.j a  va  2s  .  c  o  m
 * 
 * @param input the .jbrf file in String input
 */
private static void parsePrototypes(Map<String, Prototype> map, String input) {

    // Break down the file contents into lines
    final String[] fileInput = input.split("\n");

    if (fileInput.length > MAX_LINES) {
        throw new RuntimeException(ERROR_MSG + "fuzzers.jbrf has more than " + MAX_LINES + " lines.");
    }

    if (fileInput.length < 3) {
        throw new RuntimeException(ERROR_MSG + "fuzzers.jbrf does not have enough lines.");
    }

    for (int i = 0; i < fileInput.length; i++) {

        // Ignore comment lines starting with '#'
        if (fileInput[i].startsWith("#")) {
            continue;
        }

        // Ignore lines of length greater than MAX_LINE_LENGTH
        if (fileInput[i].length() > MAX_LINE_LENGTH) {
            continue;
        }

        // Check 1 indicating a likely prototype candidate
        try {
            if (fileInput[i].charAt(1) != ':') {
                continue;
            }
            if (fileInput[i].charAt(13) != ':') {
                continue;
            }

        } catch (final IndexOutOfBoundsException e1) {
            continue;
        }

        // [0] -> P || R || X
        // [1] -> "001-HTT-MTH"
        // [2] -> Uppercase HTTP Methods
        // [3] -> 8
        final String[] _fla = fileInput[i].split(":");

        // Check that there are four fields separated by :
        if (_fla.length != 4) {
            continue;
        }

        final char inputTypeChar = _fla[0].charAt(0);

        // Check [0] -> Fuzzer Type 'Z' or 'P', etc..
        if (!Prototype.isValidFuzzerType(inputTypeChar)) {
            continue;
        }

        // The Id: 009-SQL-INJ cannot be empty
        if (_fla[1].isEmpty()) {
            continue;
        }

        // The name: "SQL Injection" cannot be empty
        if (_fla[2].isEmpty()) {
            continue;
        }

        // Check the prototype name length
        if (_fla[2].length() > MAX_PROTO_NAME_LENGTH) {
            continue;
        }

        int noPayloads = 0;
        try {
            noPayloads = Integer.parseInt(_fla[3]);

        } catch (final NumberFormatException e) {
            continue;
        }

        // Check how many payloads this prototype has
        if (noPayloads > MAX_NO_OF_PAYLOADS) {
            continue;
        }

        // Allow only zero fuzzers to have no payloads
        if (noPayloads == 0) {
            continue;
        }

        // Check we have that many payloads left in file
        if (i + noPayloads > fileInput.length) {
            continue;
        }

        try {
            if (!fileInput[i + 1].startsWith(">")) {
                continue;
            }
            if (!fileInput[i + 2].startsWith(">>")) {
                continue;
            }
        } catch (final IndexOutOfBoundsException e) {
            continue;
        }

        String line2 = "";
        try {
            line2 = fileInput[i + 1].substring(1);
        } catch (final IndexOutOfBoundsException e) {
            continue;
        }

        String comment = "";
        try {
            comment = fileInput[i + 2].substring(2);
        } catch (final IndexOutOfBoundsException e) {
            continue;
        }

        // [0] -> HTTP Methods
        // [1] -> Replacive Fuzzers
        // [2] -> Uppercase Fuzzers
        final String[] _sla = line2.split("\\|");
        if (_sla.length > MAX_NO_OF_CATEGORIES) {
            continue;
        }

        // Alas! Finally create a prototype
        final Prototype proto = new Prototype(inputTypeChar, _fla[1], _fla[2]);

        // If categories do exist in the second line
        if (_sla.length > 0) {

            for (String categ_ry : _sla) {
                // add the category to the prototype
                categ_ry = StringUtils.stripEnd(categ_ry, " ");
                categ_ry = StringUtils.stripStart(categ_ry, " ");

                if (!categ_ry.isEmpty()) {
                    proto.addCategory(categ_ry);
                }

            }
        }
        // If no categories have been identified,
        // add a default category
        else {

            proto.addCategory("JBroFuzz");

        }

        // Add the comment
        proto.addComment(comment);

        // Add the values of each payload
        for (int j = 1; j <= noPayloads; j++) {
            try {

                proto.addPayload(fileInput[i + 2 + j]);

            } catch (final IndexOutOfBoundsException e) {
                continue;
            }
        }

        // Finally add the prototype to the database
        map.put(_fla[1], proto);

    }

}

From source file:org.owasp.jbrofuzz.headers.HeaderLoader.java

/**
 * <p>//  w ww .  j  av  a 2 s. c om
 * Private, recursive method used at construction to populate the master
 * <code>HeaderTreeNode</code> that can be accessed via the
 * <code>getMasterTreeNode</code> method.
 * </p>
 * <p>
 * In accessing this method, do not forget to reset the
 * <code>globalCounter</code> as if it reaches a value of
 * <code>MAX_RECURSION
 * </code> this method will simply return.
 * </p>
 * 
 * @param categoriesArray
 *            The array of nodes to be added.
 * @param headerTreeNode
 *            The tree node on which to be added.
 * 
 * @see #getMasterHeader()
 * @author subere@uncon.org
 * @version 1.3
 * @since 1.2
 */
private void addNodes(final String[] categoriesArray, final HeaderTreeNode headerTreeNode) {

    if (categoriesArray.length == 0) {
        return;
    }
    if (globalCounter > MAX_RECURSION) {
        return;
    }
    globalCounter++;
    // Find the first element
    final String firstElement = StringUtils.stripStart(StringUtils.stripEnd(categoriesArray[0], " "), " ");
    // Use the index to know its position
    int index = 0;
    boolean exists = false;
    for (final Enumeration<HeaderTreeNode> e = extracted(headerTreeNode); e.hasMoreElements() && !exists;) {

        final String currentElement = e.nextElement().toString();

        if (currentElement.equalsIgnoreCase(firstElement)) {

            exists = true;

        } else {
            // If firstElement not current, increment
            index++;

        }
    }

    // Does the first element exist?
    if (!exists) {

        headerTreeNode.add(new HeaderTreeNode(firstElement));
    }

    // Remove the first element, start again
    final String[] temp = (String[]) ArrayUtils.subarray(categoriesArray, 1, categoriesArray.length);
    final HeaderTreeNode nemp = (HeaderTreeNode) headerTreeNode.getChildAt(index);

    addNodes(temp, nemp);

}