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

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

Introduction

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

Prototype

public static String substringBetween(final String str, final String open, final String close) 

Source Link

Document

Gets the String that is nested in between two Strings.

Usage

From source file:io.restassured.path.xml.XmlPathObjectDeserializationTest.java

@Test
public void xml_path_supports_custom_deserializer() {
    // Given//from w w  w. ja  v a2 s . c om
    final AtomicBoolean customDeserializerUsed = new AtomicBoolean(false);

    final XmlPath xmlPath = new XmlPath(COOL_GREETING)
            .using(XmlPathConfig.xmlPathConfig().defaultObjectDeserializer(new XmlPathObjectDeserializer() {
                public <T> T deserialize(ObjectDeserializationContext ctx) {
                    customDeserializerUsed.set(true);
                    final String xml = ctx.getDataToDeserialize().asString();
                    final Greeting greeting = new Greeting();
                    greeting.setFirstName(StringUtils.substringBetween(xml, "<firstName>", "</firstName>"));
                    greeting.setLastName(StringUtils.substringBetween(xml, "<lastName>", "</lastName>"));
                    return (T) greeting;
                }
            }));

    // When
    final Greeting greeting = xmlPath.getObject("", Greeting.class);

    // Then
    assertThat(greeting.getFirstName(), equalTo("John"));
    assertThat(greeting.getLastName(), equalTo("Doe"));
    assertThat(customDeserializerUsed.get(), is(true));
}

From source file:com.sishuok.chapter4.web.servlet.UploadServlet.java

private String getFileName(final Part part) {
    if (part == null) {
        return null;
    }//from   w  w  w.  j a va  2 s . c  o m

    if (part.getContentType() == null) {
        return null;
    }

    String contentDisposition = part.getHeader("content-disposition");

    if (StringUtils.isEmpty(contentDisposition)) {
        return null;
    }
    // form-data; name="file1"; filename="TODO.txt"
    return StringUtils.substringBetween(contentDisposition, "filename=\"", "\"");

}

From source file:com.erudika.para.rest.Signer.java

/**
 * Validates the signature of the request.
 * @param incoming the incoming HTTP request containing a signature
 * @param secretKey the app's secret key
 * @return true if the signature is valid
 *//* w  w  w  .jav a  2s. c  o  m*/
public boolean isValidSignature(HttpServletRequest incoming, String secretKey) {
    if (incoming == null || StringUtils.isBlank(secretKey)) {
        return false;
    }
    String auth = incoming.getHeader(HttpHeaders.AUTHORIZATION);
    String givenSig = StringUtils.substringAfter(auth, "Signature=");
    String sigHeaders = StringUtils.substringBetween(auth, "SignedHeaders=", ",");
    String credential = StringUtils.substringBetween(auth, "Credential=", ",");
    String accessKey = StringUtils.substringBefore(credential, "/");

    if (StringUtils.isBlank(auth)) {
        givenSig = incoming.getParameter("X-Amz-Signature");
        sigHeaders = incoming.getParameter("X-Amz-SignedHeaders");
        credential = incoming.getParameter("X-Amz-Credential");
        accessKey = StringUtils.substringBefore(credential, "/");
    }

    Request<?> awsReq = buildAWSRequest(incoming, new HashSet<String>(Arrays.asList(sigHeaders.split(";"))));
    sign(awsReq, accessKey, secretKey);

    String auth2 = awsReq.getHeaders().get(HttpHeaders.AUTHORIZATION);
    String recreatedSig = StringUtils.substringAfter(auth2, "Signature=");

    return StringUtils.equals(givenSig, recreatedSig);
}

From source file:com.denimgroup.threadfix.importer.impl.upload.ClangChannelImporter.java

private Finding parseInputStream(String reportFileName, InputStream in) {

    List<DataFlowElement> dataFlowElements = list();
    Map<FindingKey, String> findingKeyStringMap = map();

    String bugDesc = null;/*from  ww w.j  ava2s.c o  m*/
    String bugType = null;
    String bugCategory = null;
    String bugPath = null;
    String bugFile = null;
    String bugLine = null;
    String bugColumn = null;

    String line, nonHtmlLine;
    String previousSourceLine = "";
    String previousLineNumber = "";

    boolean foundLastError = false;
    int dataFlowSeq = 0;

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    try {
        line = reader.readLine();
        while (line != null && !foundLastError) {
            if (line.startsWith(BUGDESC) && line.endsWith(BUGTAIL))
                bugDesc = StringUtils.substringBetween(line, BUGDESC, BUGTAIL);
            else if (line.startsWith(BUGTYPE) && line.endsWith(BUGTAIL))
                bugType = StringUtils.substringBetween(line, BUGTYPE, BUGTAIL);
            else if (line.startsWith(BUGCATEGORY) && line.endsWith(BUGTAIL))
                bugCategory = StringUtils.substringBetween(line, BUGCATEGORY, BUGTAIL);
            else if (line.startsWith(BUGPATH) && line.endsWith(BUGTAIL))
                bugPath = StringUtils.substringBetween(line, BUGPATH, BUGTAIL);
            else if (line.startsWith(BUGLINE) && line.endsWith(BUGTAIL))
                bugLine = StringUtils.substringBetween(line, BUGLINE, BUGTAIL);
            else if (line.startsWith(BUGCOLUMN) && line.endsWith(BUGTAIL))
                bugColumn = StringUtils.substringBetween(line, BUGCOLUMN, BUGTAIL);
            else if (line.startsWith(BUGFILE_START) && line.endsWith(BUGFILE_END))
                bugFile = StringUtils.substringBetween(line, BUGFILE_START, BUGFILE_END);

            if (line.matches(REGEX_LINE_SOURCE)) {
                nonHtmlLine = line.replaceAll("<span class='expansion'>([^<]*)</span>", "");
                nonHtmlLine = nonHtmlLine.replaceAll("<[^>]*>", ""); // strip html
                previousLineNumber = StringUtils.substringBetween(line, "id=\"LN", "\">");
                previousSourceLine = nonHtmlLine.replaceFirst(previousLineNumber, "");
            } else if (line.matches(REGEX_LINE_COMMENT)) {
                DataFlowElement element = new DataFlowElement();
                element.setLineText(previousSourceLine);
                element.setSourceFileName(bugFile);
                if (line.contains("id=\"EndPath\"")) {
                    element.setLineNumber(Integer.parseInt(bugLine));
                    element.setColumnNumber(Integer.parseInt(bugColumn));
                    foundLastError = true;
                } else {
                    element.setLineNumber(Integer.parseInt(previousLineNumber));
                }
                String prevElemLineText = null;
                if (dataFlowSeq > 0) {
                    prevElemLineText = dataFlowElements.get(dataFlowSeq - 1).getLineText();
                }
                if (prevElemLineText != null && element.getLineText().equals(prevElemLineText)) {
                    // concurrent line comments, overwrite last element
                    element.setSequence(dataFlowSeq);
                    dataFlowElements.set(dataFlowSeq - 1, element);
                } else {
                    element.setSequence(++dataFlowSeq);
                    dataFlowElements.add(element);
                }
            }
            line = reader.readLine();
        }
        reader.close();
    } catch (IOException e) {
        log.error("IOException thrown when reading file " + reportFileName, e);
    }

    String vulnCode = bugCategory.concat(":").concat(bugType);
    findingKeyStringMap.put(FindingKey.VULN_CODE, vulnCode);
    findingKeyStringMap.put(FindingKey.DETAIL, bugDesc);
    findingKeyStringMap.put(FindingKey.PATH, bugFile);
    findingKeyStringMap.put(FindingKey.SEVERITY_CODE, "Medium");

    Finding finding = super.constructFinding(findingKeyStringMap);
    if (finding == null) {
        throw new IllegalStateException("XML was invalid or we didn't parse out enough information");
    }
    finding.setIsStatic(true);
    finding.setDataFlowElements(dataFlowElements);
    finding.setSourceFileLocation(bugPath);
    finding.setNativeId(getNativeIdFromReport(reportFileName));

    return finding;
}

From source file:com.jayway.restassured.path.xml.XmlPathObjectDeserializationTest.java

@Test
public void xml_path_supports_custom_deserializer() {
    // Given/*from w w w . j a v a2 s  . c o  m*/
    final AtomicBoolean customDeserializerUsed = new AtomicBoolean(false);

    final XmlPath xmlPath = new XmlPath(COOL_GREETING)
            .using(xmlPathConfig().defaultObjectDeserializer(new XmlPathObjectDeserializer() {
                public <T> T deserialize(ObjectDeserializationContext ctx) {
                    customDeserializerUsed.set(true);
                    final String xml = ctx.getDataToDeserialize().asString();
                    final Greeting greeting = new Greeting();
                    greeting.setFirstName(StringUtils.substringBetween(xml, "<firstName>", "</firstName>"));
                    greeting.setLastName(StringUtils.substringBetween(xml, "<lastName>", "</lastName>"));
                    return (T) greeting;
                }
            }));

    // When
    final Greeting greeting = xmlPath.getObject("", Greeting.class);

    // Then
    assertThat(greeting.getFirstName(), equalTo("John"));
    assertThat(greeting.getLastName(), equalTo("Doe"));
    assertThat(customDeserializerUsed.get(), is(true));
}

From source file:de.tor.tribes.util.parser.TroopsParser.java

public boolean parse(String pTroopsString) {
    StringTokenizer lineTok = new StringTokenizer(pTroopsString, "\n\r");
    int villageLines = -1;
    boolean retValue = false;
    int foundTroops = 0;
    //boolean haveVillage = false;
    Village v = null;//from   w  ww  .  j a  va  2  s  . co  m
    TroopAmountFixed ownTroops = null;
    TroopAmountFixed troopsInVillage = null;
    TroopAmountFixed troopsOutside = null;
    TroopAmountFixed troopsOnTheWay = null;
    TroopsManager.getSingleton().invalidate();
    // used to update group on the fly, if not "all" selected
    String groupName = null;
    // groups could be multiple lines, detection is easiest for first line (starts with "Gruppen:")
    boolean groupLines = false;
    // store visited villages, so we can add em to selected group
    List<Village> villages = new LinkedList<>();
    while (lineTok.hasMoreElements()) {
        //parse single line for village
        String line = lineTok.nextToken();
        //tokenize line by tab and space
        //  StringTokenizer elemTok = new StringTokenizer(line, " \t");
        //parse single line for village
        if (v != null) {
            //parse 4 village lines!
            line = line.trim();
            if (line.trim().startsWith(getVariable("troops.own"))) {
                ownTroops = parseUnits(line.replaceAll(getVariable("troops.own"), "").trim());
            } else if (line.trim().startsWith(getVariable("troops.in.village"))) {
                troopsInVillage = parseUnits(line.replaceAll(getVariable("troops.in.village"), "").trim());
            } else if (line.trim().startsWith(getVariable("troops.outside"))) {
                troopsOutside = parseUnits(line.replaceAll(getVariable("troops.outside"), "").trim());
            } else if (line.trim().startsWith(getVariable("troops.on.the.way"))) {
                troopsOnTheWay = parseUnits(line.replaceAll(getVariable("troops.on.the.way"), "").trim());
            }
            villageLines--;
        } else {
            try {
                Village current = VillageParser.parseSingleLine(line);
                if (current != null) {
                    v = current;
                    villageLines = 4;
                    // we are not searching for further group names
                    groupLines = false;
                    // add village to list of villages in selected group
                    if (groupName != null)
                        villages.add(v);
                } else {
                    // Check if current line is first group line. In case it is, store selected group
                    if (line.trim().startsWith(getVariable("overview.groups")))
                        groupLines = true;
                    // Check if current line contains active group. In case it does, store group name and stop searching
                    if (groupLines && line.matches(".*>.*?<.*")) {
                        groupLines = false;
                        groupName = StringUtils.substringBetween(line, ">", "<"); // = line.replaceAll(".*>|<.*",""); if we stop using Apache Commons            
                    }
                }
            } catch (Exception e) {
                v = null;
                villageLines = 0;
                // Check if current line is first group line. In case it is, store selected group
                if (line.trim().startsWith(getVariable("overview.groups")))
                    groupLines = true;
                // Check if current line contains active group. In case it does, store group name and stop searching
                if (groupLines && line.matches(".*>.*?<.*")) {
                    groupLines = false;
                    groupName = StringUtils.substringBetween(line, ">", "<"); // = line.replaceAll(".*>|<.*",""); if we stop using Apache Commons            
                }
            }
        }
        //add troops information
        if (villageLines == 0) {
            if (v != null && ownTroops != null && troopsInVillage != null && troopsOutside != null
                    && troopsOnTheWay != null) {
                //add troops to manager
                VillageTroopsHolder own = TroopsManager.getSingleton().getTroopsForVillage(v,
                        TroopsManager.TROOP_TYPE.OWN, true);
                VillageTroopsHolder inVillage = TroopsManager.getSingleton().getTroopsForVillage(v,
                        TroopsManager.TROOP_TYPE.IN_VILLAGE, true);
                VillageTroopsHolder outside = TroopsManager.getSingleton().getTroopsForVillage(v,
                        TroopsManager.TROOP_TYPE.OUTWARDS, true);
                VillageTroopsHolder onTheWay = TroopsManager.getSingleton().getTroopsForVillage(v,
                        TroopsManager.TROOP_TYPE.ON_THE_WAY, true);

                own.setTroops(ownTroops);
                inVillage.setTroops(troopsInVillage);
                outside.setTroops(troopsOutside);
                onTheWay.setTroops(troopsOnTheWay);
                ownTroops = null;
                troopsInVillage = null;
                troopsOutside = null;
                troopsOnTheWay = null;
                v = null;
                foundTroops++;
                //found at least one village, so retValue is true    
                retValue = true;
            } else {
                v = null;
                ownTroops = null;
                troopsInVillage = null;
                troopsOutside = null;
                troopsOnTheWay = null;
            }
        }
    }
    if (retValue) {
        try {
            DSWorkbenchMainFrame.getSingleton()
                    .showSuccess("DS Workbench hat Truppeninformationen zu " + foundTroops
                            + ((foundTroops == 1) ? " Dorf " : " Drfern ")
                            + " in die Truppenbersicht eingetragen.");
        } catch (Exception e) {
            NotifierFrame.doNotification("DS Workbench hat Truppeninformationen zu " + foundTroops
                    + ((foundTroops == 1) ? " Dorf " : " Drfern ") + " in die Truppenbersicht eingetragen.",
                    NotifierFrame.NOTIFY_INFO);
        }
    }

    //update selected group, if any
    if (groupName != null && !groupName.equals(getVariable("groups.all"))) {
        HashMap<String, List<Village>> groupTable = new HashMap<>();
        groupTable.put(groupName, villages);
        DSWorkbenchMainFrame.getSingleton().fireGroupParserEvent(groupTable);
    }

    TroopsManager.getSingleton().revalidate(retValue);
    return retValue;
}

From source file:com.ibm.watson.apis.conversation_enhanced.rest.ProxyResource.java

private String filter(String contents) {
    String contentNoBrackets = StringUtils.substringBetween(contents, "[", "]");
    String weatherContent = new WeatherLookupFilter().filter(contentNoBrackets);
    return (weatherContent != null) ? weatherContent : new StockQuoteFilter().filter(contentNoBrackets);
}

From source file:com.thruzero.common.core.infonode.InfoNodeTest.java

@Test
public void testNestedNodeNoParentValue() {
    InfoNodeElement complexNode = SampleInfoNodeBuilderUtils
            .createComplexNestedInfoNodeWithoutParentValue(RootNodeOption.GENERATE_ROOT_NODE, 10);

    // verify that parent to child transition is smooth (i.e., no null printed in result)
    String partialResultStr = StringUtils.substringBetween(complexNode.toString(), "<TestParentElement",
            "<Test0Element");
    assertTrue(partialResultStr.trim().equals(">"));
}

From source file:com.thruzero.common.core.fs.SubstitutionVisitorTest.java

private void validateTest(final File tempTestFile, final String originalContents) {
    String substitutedContents = null;
    try {/*from   w ww  .  j av  a  2  s .  co  m*/
        substitutedContents = FileUtilsExt.readFromFile(tempTestFile);
    } catch (FileUtilsException e1) {
        // ignore
    }
    assertNotNull("Could not read substitution file after walk.", substitutedContents);
    assertFalse("Substitution failed - files are same before and after substitution.",
            StringUtils.equals(originalContents, substitutedContents));
    assertNull("Substitution failed - files contain substitution variables.",
            StringUtils.substringBetween(substitutedContents, "${", "}"));
    assertFalse("Substitution failed - files contain remnants of substitution variables.",
            StringUtils.contains(substitutedContents, "${"));
    assertFalse("Substitution failed - files contain remnants of substitution variables.",
            StringUtils.contains(substitutedContents, "$"));
    assertFalse("Substitution failed - files contain remnants of substitution variables.",
            StringUtils.contains(substitutedContents, "}"));
}

From source file:com.thinkbiganalytics.ingest.TableRegisterSupportTest.java

@Test
public void testTableCreateS3() {
    ColumnSpec[] specs = ColumnSpec.createFromString(
            "id|bigint|my comment\nname|string\ncompany|string|some description\nzip|string\nphone|string\nemail|string\ncountry|string\nhired|date");
    ColumnSpec[] parts = ColumnSpec.createFromString("year|int\ncountry|string");
    TableRegisterConfiguration conf = new TableRegisterConfiguration("s3a://testBucket/model.db/",
            "s3a://testBucket/model.db/", "s3a://testBucket/app/warehouse/");
    TableRegisterSupport support = new TableRegisterSupport(connection, conf);
    TableType[] tableTypes = new TableType[] { TableType.FEED, TableType.INVALID, TableType.VALID,
            TableType.MASTER };/* ww  w  .j  a v a  2 s .c  o m*/
    for (TableType tableType : tableTypes) {
        String ddl = support.createDDL("bar", "employee", specs, parts,
                "ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.OpenCSVSerde'", "stored as orc",
                "tblproperties (\"orc.compress\"=\"SNAPPY\")", tableType);
        String location = StringUtils.substringBetween(ddl, "LOCATION '", "'");
        if (tableType == TableType.MASTER) {
            assertEquals("Master location does not match", "s3a://testBucket/app/warehouse/bar/employee",
                    location);
        } else {
            assertEquals("Locations do not match",
                    "s3a://testBucket/model.db/bar/employee/" + tableType.toString().toLowerCase(), location);
        }
    }
}