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:no.freecode.translator.business.MessageImporter.java

public void importData(InputStream input, String filename) throws IOException {
    MessageLocale locale = getLocale(filename);
    locale.persist();//from w  w  w.j av  a2s .  com

    BufferedReader csvReader = new BufferedReader(new InputStreamReader(input));

    //        HashMap<String, MessageSection> sections = new HashMap<String, MessageSection>();

    //        MessageSection curSection = new MessageSection();
    String curSectionId;
    String curComment = null;

    String line;
    while ((line = StringEscapeUtils.unescapeJava(StringUtils.strip(csvReader.readLine()))) != null) {

        if (StringUtils.startsWith(line, "#")) {
            String comment = StringUtils.stripStart(line, "# ");
            if (StringUtils.isNotEmpty(comment)) {
                curComment = comment;
            }

        } else {
            // Proper line
            String[] entry = StringUtils.split(line, "=", 2);

            if (entry.length == 2) {
                String key = StringUtils.strip(entry[0]);
                String value = StringUtils.strip(entry[1]);

                String[] keyFragments = StringUtils.split(key, ".", 2);

                if (keyFragments.length < 2) {
                    // Root section
                    curSectionId = "root";

                } else {
                    // Split into sections based on what's before the first '.' in the key.
                    curSectionId = keyFragments[0];
                }

                MessageSection curSection = MessageSection.findMessageSection(curSectionId);
                //                    curSection = sections.get(curSectionId);

                if (curSection == null) {
                    curSection = new MessageSection();
                    curSection.setId(curSectionId);
                    //                        sections.put(curSectionId, curSection);
                }

                if (StringUtils.isNotBlank(curComment)) {
                    curSection.setDescription(curComment);
                    curComment = null;
                }

                Set<Message> messages = curSection.getMessages();
                if (messages == null) {
                    messages = new HashSet<Message>();
                    curSection.setMessages(messages);
                }

                // Does this message already have one or more translation? If not, create a new message.
                List<Message> res = Message.findMessagesByPropertyEquals(key).getResultList();
                Message message;
                if (res.size() > 0) {
                    message = res.get(0);
                    logger.trace("Yes, found an already persisted one: " + message);

                } else {
                    message = new Message();
                }

                message.setProperty(key);
                message.getTranslations().put(locale, value);

                messages.add(message);

                logger.trace("persisting curSection: " + curSection);
                curSection.persist();

            } else {
                // Could be an empty line, or an invalid line. Ignore it.
            }
        }
    }

    //        logger.info("sections: " + sections.size());
    //        for (MessageSection section : sections.values()) {
    //            System.out.println(": (id:" + section.getId() + ") " + section);
    //            
    //            for (Message message : section.getMessages()) {
    //                System.out.println("--: (id:" + message.getId() + ") " + message);
    //                
    //                for (Entry<MessageLocale, String> entry : message.getTranslations().entrySet()) {
    //                    System.out.println("-----: " + entry.getKey() + ": " + entry.getValue());
    //                }
    //            }
    //            
    //            section.persist();
    //        }
}

From source file:org.adl.util.EnvironmentVariable.java

/**
 * Retrieves the value of the specified environment variable.
 *
 * @param iKey   Name of the environment variable.
 *
 * @return Value of the specified environment variable.
 *//*from w  w w  .ja  v  a2  s . c om*/
public static String getValue(String iKey) {
    String value = "";

    try {
        Process p;
        String osName = System.getProperty("os.name");

        if ((osName.equalsIgnoreCase("Windows 95")) || (osName.equalsIgnoreCase("Windows 98"))
                || (osName.equalsIgnoreCase("Windows Me"))) {
            p = Runtime.getRuntime().exec("command.com /c echo %" + iKey + "%");
        } else {
            p = Runtime.getRuntime().exec("cmd.exe /c echo %" + iKey + "%");
        }

        p.waitFor();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        value = br.readLine();

        if (StringUtils.startsWith(value, "%")) {
            value = "";
        }

        br.close();
        p.destroy();
    } catch (IOException ioe) {
        System.out.println("Could not read environment variable key " + iKey);
    } catch (InterruptedException ie) {
        System.out.println("The process has been interrupted");
    }

    return value;
}

From source file:org.adl.validator.contentpackage.CPValidator.java

/**
 * This method checks that if the &lt;resource&gt; is local to the content
 * package, then a &lt;file&gt; element is required that represents the
 * &lt;resource&gt; itself. The href attribute of the &lt;file&gt; element
 * shall be identical to the href attribute of the &lt;resource&gt;
 * //from  w  w  w .ja v a 2 s  . co  m
 * @param iResourceNode
 *            - The &lt;resource&gt; element
 * @return boolean - Result of the overall check. True if the checks passed,
 *         false otherwise.
 */
private boolean checkResourceFileHref(Node iResourceNode) {
    boolean result = true;
    String msgText = "";

    // retrive the href and apply xml:base
    String resourceHref = DOMTreeUtility.getAttributeValue(iResourceNode, "href");

    // only continue check if the resourceHref exists
    if (!resourceHref.equals("")) {
        // remove all parameters from the end of the href, if they exist

        // first deal with ?
        int questionMarkIndex = StringUtils.indexOf(resourceHref, '?');
        if (questionMarkIndex > 0) {
            resourceHref = StringUtils.substring(resourceHref, 0, questionMarkIndex);
        }

        // also deal with #
        int poundIndex = StringUtils.indexOf(resourceHref, '#');
        if (poundIndex > 0) {
            resourceHref = StringUtils.substring(resourceHref, 0, poundIndex);
        }

        // we must manually retrieve the resource xml:base attribute value
        // the applyXMLBase is not aware of it at this time of processing
        String resourceXMLBase = DOMTreeUtility.getAttributeValue(iResourceNode, "base");

        // resourceID used for logging error messages
        String resourceID = DOMTreeUtility.getAttributeValue(iResourceNode, "identifier");
        mLogger.debug("Checking for this resource now " + resourceID);

        // apply XML Base to the href if it exists
        resourceHref = mXMLBase[0][1] + mXMLBase[1][1] + resourceXMLBase + resourceHref;

        // only need to perform this check on local resource
        if (!StringUtils.startsWith(resourceHref, "http:") && !StringUtils.startsWith(resourceHref, "https:")
                && !StringUtils.startsWith(resourceHref, "ftp:")
                && !StringUtils.startsWith(resourceHref, "ftps:")) {
            // we have a resource that is local to the package, must have a
            // file
            // href that is identifical to it

            List<String> files = mResourceTable.get(resourceID);

            if (files != null) {
                if (!files.contains(resourceHref)) {
                    // the resourceHref does not contain a matching file
                    // href when
                    // it should
                    result = false;

                    msgText = Messages.getString("CPValidator.628", resourceID);
                    mLogger.debug("FAILED: " + msgText);
                    DetailedLogMessageCollection.getInstance()
                            .addMessage(new LogMessage(MessageType.FAILED, msgText));
                }
            } else {
                // there are no files that exist for the local resource
                result = false;

                msgText = Messages.getString("CPValidator.628", resourceID);
                mLogger.debug("FAILED: " + msgText);
                DetailedLogMessageCollection.getInstance()
                        .addMessage(new LogMessage(MessageType.FAILED, msgText));
            }
        }
    }
    return result;
}

From source file:org.alfresco.rest.framework.tests.core.SerializeTests.java

@Test
public void testInvokeEntity() throws IOException {
    ResourceWithMetadata entityResource = locator.locateEntityResource(api, "sheep", HttpMethod.GET);
    assertNotNull(entityResource);//  w  ww  .  j  av  a 2 s . c o m
    EntityResourceAction.ReadById<?> getter = (ReadById<?>) entityResource.getResource();

    String out = writeResponse(helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api, null,
            NOT_USED, getter.readById("1234A3", NOT_USED)));
    assertTrue("There must be json output", StringUtils.startsWith(out, "{\"entry\":"));

    EntityResourceAction.Read<?> getAll = (Read<?>) entityResource.getResource();
    CollectionWithPagingInfo<?> resources = getAll.readAll(null);
    out = writeResponse(helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api, null,
            Params.valueOf("notUsed", null, null), resources));
    assertTrue("There must be json output as List", StringUtils.startsWith(out, "{\"list\":"));
}

From source file:org.alfresco.rest.framework.tests.core.SerializeTests.java

@Test
public void testInvokeMultiPartEntity() throws IOException {
    ResourceWithMetadata entityResource = locator.locateEntityResource(api, "multiparttest", HttpMethod.POST);
    assertNotNull(entityResource);/*from ww w.ja  v  a  2  s  .  c  om*/
    MultiPartResourceAction.Create<?> resource = (MultiPartResourceAction.Create<?>) entityResource
            .getResource();

    File file = TempFileProvider.createTempFile("ParamsExtractorTests-", ".txt");
    PrintWriter writer = new PrintWriter(file);
    writer.println("Multipart Mock test2.");
    writer.close();

    MultiPartRequest reqBody = MultiPartBuilder.create()
            .setFileData(new FileData(file.getName(), file, MimetypeMap.MIMETYPE_TEXT_PLAIN)).build();

    MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST", "");
    mockRequest.setContent(reqBody.getBody());
    mockRequest.setContentType(reqBody.getContentType());

    String out = writeResponse(helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api, null,
            NOT_USED, resource.create(new FormData(mockRequest), NOT_USED, callBack)));
    assertTrue("There must be json output", StringUtils.startsWith(out, "{\"entry\":"));
}

From source file:org.alfresco.rest.framework.tests.core.SerializeTests.java

@Test
public void testSerializeResponse() throws IOException {
    ResourceWithMetadata relationResource = locator.locateRelationResource(api, "sheep", "baaahh",
            HttpMethod.GET);//from ww  w  .  java2 s .  c om
    assertNotNull(relationResource);
    RelationshipResourceAction.Read<?> getter = (RelationshipResourceAction.Read<?>) relationResource
            .getResource();
    CollectionWithPagingInfo<?> resources = getter.readAll("123", Params.valueOf("", null, null));
    String out = writeResponse(helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api, null,
            Params.valueOf("notUsed", null, null), resources));
    assertTrue("There must be json output as List", StringUtils.startsWith(out, "{\"list\":"));
}

From source file:org.alfresco.rest.framework.tests.core.SerializeTests.java

@Test
public void testPagedCollection() throws IOException {
    ResourceWithMetadata relationResource = locator.locateRelationResource(api, "sheep", "baaahh",
            HttpMethod.GET);//from ww w  .  jav  a  2 s .c  o  m
    assertNotNull(relationResource);
    RelationshipResourceAction.Read<?> getter = (RelationshipResourceAction.Read<?>) relationResource
            .getResource();
    CollectionWithPagingInfo<?> resources = getter.readAll("123", Params.valueOf("", null, null));
    assertNotNull(resources);
    assertTrue(resources.getTotalItems().intValue() == 3);
    assertFalse(resources.hasMoreItems());
    String out = writeResponse(helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api, null,
            Params.valueOf("notUsed", null, null), resources));
    assertTrue("There must be json output as List with pagination",
            StringUtils.startsWith(out, "{\"list\":{\"pagination\":{\"count\":3,"));

    resources = getter.readAll("123", ParamsExtender.valueOf(Paging.valueOf(0, 1), "123"));
    assertTrue(resources.getCollection().size() == 1);
    assertTrue(resources.hasMoreItems());
    out = writeResponse(helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api, null,
            Params.valueOf("notUsed", null, null), resources));
    assertTrue("There must be json output as List with pagination",
            StringUtils.startsWith(out, "{\"list\":{\"pagination\":{\"count\":1,"));

}

From source file:org.alfresco.rest.framework.tests.core.SerializeTests.java

@SuppressWarnings({ "rawtypes" })
@Test//from  w w  w. jav  a  2 s  .com
public void testSerializePagedCollection() throws IOException {
    assertNotNull(helper);
    CollectionWithPagingInfo paged = CollectionWithPagingInfo.asPaged(null, null);
    String out = writeResponse(helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api, null,
            Params.valueOf("notUsed", null, null), paged));
    assertTrue("There must be json output as List with pagination",
            StringUtils.startsWith(out, "{\"list\":{\"pagination\":{\"count\":0,"));
    Paging pageRequest = Paging.valueOf(1, 2);

    paged = CollectionWithPagingInfo.asPaged(pageRequest,
            Arrays.asList(new Goat(), new Sheep("ABCD"), new Sheep("XYZ")));
    out = writeResponse(helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api, null,
            Params.valueOf("notUsed", null, null), paged));
    assertTrue("There must be json output as List with pagination",
            StringUtils.startsWith(out, "{\"list\":{\"pagination\":{\"count\":3,"));

    paged = CollectionWithPagingInfo.asPaged(pageRequest,
            Arrays.asList(new Goat(), new Sheep("ABCD"), new Sheep("XYZ")), true, 5000);
    out = writeResponse(helper.processAdditionsToTheResponse(mock(WebScriptResponse.class), api, null,
            Params.valueOf("notUsed", null, null), paged));
    assertTrue("There must be json output as List with pagination", StringUtils.startsWith(out,
            "{\"list\":{\"pagination\":{\"count\":3,\"hasMoreItems\":true,\"totalItems\":5000"));

}

From source file:org.andromda.cartridges.gui.GuiUtils.java

/**
 * Reads the validator arguments from the the given tagged value.
 * //from   ww w.  jav  a2s  .  c  om
 * @param validatorTaggedValue
 * @return returns a list of String instances or an empty list
 * @throws IllegalArgumentException when the input string does not match the required pattern
 */
public static List<String> parseValidatorArgs(String validatorTaggedValue) {

    if (validatorTaggedValue == null) {

        throw new IllegalArgumentException("Validator tagged value cannot be null");

    }

    final List<String> validatorArgs = new ArrayList<String>();

    // isn't it an annotation ?
    if (!StringUtils.startsWith(validatorTaggedValue, GuiUtils.ANNOTATION_VALIDATOR_PREFIX)) {

        // check if the input tagged value matches the required pattern
        if (!GuiUtils.VALIDATOR_TAGGEDVALUE_PATTERN.matcher(validatorTaggedValue).matches()) {

            throw new IllegalArgumentException(
                    "Illegal validator tagged value (this tag is used to specify custom validators "
                            + "and might look like myValidator(myVar=myArg,myVar2=myArg2), perhaps you wanted to use "
                            + "andromda_presentation_view_field_format?): " + validatorTaggedValue);

        }

        // only keep what is between parentheses (if any)
        final int left = validatorTaggedValue.indexOf('(');

        if (left > -1) {

            final int right = validatorTaggedValue.indexOf(')');

            validatorTaggedValue = validatorTaggedValue.substring(left + 1, right);

            final String[] pairs = validatorTaggedValue.split(",");

            for (final String pair : pairs) {

                final int equalsIndex = pair.indexOf('=');

                // it's possible the argument is the empty string
                if (equalsIndex < (pair.length() - 1)) {

                    validatorArgs.add(pair.substring(equalsIndex + 1));

                } else {

                    validatorArgs.add("");

                }

            }

        }

    }

    return validatorArgs;

}

From source file:org.andromda.cartridges.gui.GuiUtils.java

/**
 * Reads the validator variable names from the the given tagged value.
 * //from   w w  w . j a va2s. co  m
 * @param validatorTaggedValue
 * @return never null, returns a list of String instances
 * @throws IllegalArgumentException when the input string does not match the required pattern
 */
public static List<String> parseValidatorVars(String validatorTaggedValue) {

    if (validatorTaggedValue == null) {

        throw new IllegalArgumentException("Validator tagged value cannot be null");

    }

    final List<String> validatorVars = new ArrayList<String>();

    // isn't it an annotation ?
    if (!StringUtils.startsWith(validatorTaggedValue, GuiUtils.ANNOTATION_VALIDATOR_PREFIX)) {

        // check if the input tagged value matches the required pattern
        if (!GuiUtils.VALIDATOR_TAGGEDVALUE_PATTERN.matcher(validatorTaggedValue).matches()) {

            throw new IllegalArgumentException("Illegal validator tagged value: " + validatorTaggedValue);

        }

        // only keep what is between parentheses (if any)
        final int left = validatorTaggedValue.indexOf('(');

        if (left > -1) {

            final int right = validatorTaggedValue.indexOf(')');

            validatorTaggedValue = validatorTaggedValue.substring(left + 1, right);

            final String[] pairs = validatorTaggedValue.split(",");

            for (final String pair : pairs) {

                final int equalsIndex = pair.indexOf('=');

                validatorVars.add(pair.substring(0, equalsIndex));

            }

        }

    }

    return validatorVars;

}