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

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

Introduction

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

Prototype

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

Source Link

Document

Gets the String that is nested in between two Strings.

Usage

From source file:com.backelite.sonarqube.swift.coverage.CoberturaReportParser.java

private static void collectFileData(SMInputCursor clazz, CoverageMeasuresBuilder builder)
        throws XMLStreamException {
    SMInputCursor line = clazz.childElementCursor("lines").advance().childElementCursor("line");
    while (line.getNext() != null) {
        int lineId = Integer.parseInt(line.getAttrValue("number"));
        try {//www . j a  v a  2  s .com
            builder.setHits(lineId, (int) ParsingUtils.parseNumber(line.getAttrValue("hits"), Locale.ENGLISH));
        } catch (ParseException e) {
            throw new XmlParserException(e);
        }

        String isBranch = line.getAttrValue("branch");
        String text = line.getAttrValue("condition-coverage");
        if (StringUtils.equals(isBranch, "true") && StringUtils.isNotBlank(text)) {
            String[] conditions = StringUtils.split(StringUtils.substringBetween(text, "(", ")"), "/");
            builder.setConditions(lineId, Integer.parseInt(conditions[1]), Integer.parseInt(conditions[0]));
        }
    }
}

From source file:com.zb.app.biz.service.WeixinTest.java

public void login() {
    httpClient = new HttpClient();
    PostMethod post = new PostMethod(loginUrl);
    post.addParameter(new NameValuePair("username", account));
    post.addParameter(new NameValuePair("pwd", DigestUtils.md5Hex(password)));
    post.addParameter(new NameValuePair("imgcode", ""));
    post.addParameter(new NameValuePair("f", "json"));
    post.setRequestHeader("Host", "mp.weixin.qq.com");
    post.setRequestHeader("Referer", "https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm2-login&lang=zh_CN");

    try {/*from  w w w.  j a v a  2 s .c  o  m*/
        int code = httpClient.executeMethod(post);
        if (HttpStatus.SC_OK == code) {
            String res = post.getResponseBodyAsString();
            JSONParser parser = new JSONParser();
            JSONObject obj = (JSONObject) parser.parse(res);
            JSONObject _obj = (JSONObject) obj.get("base_resp");
            @SuppressWarnings("unused")
            String msg = (String) _obj.get("err_msg");
            String redirect_url = (String) obj.get("redirect_url");
            Long errCode = (Long) _obj.get("ret");
            if (0 == errCode) {
                isLogin = true;
                token = StringUtils.substringAfter(redirect_url, "token=");
                if (null == token) {
                    token = StringUtils.substringBetween(redirect_url, "token=", "&");
                }
                StringBuffer cookie = new StringBuffer();
                for (Cookie c : httpClient.getState().getCookies()) {
                    cookie.append(c.getName()).append("=").append(c.getValue()).append(";");
                }
                this.cookiestr = cookie.toString();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.gs.tools.doc.extractor.core.html.HTMLDocumentExtractor.java

public long extract(String sourceUrl, String targetFolderName) throws Exception {
    logger.info("Init extraction from: " + sourceUrl);
    logger.info("Disk location: " + targetFolderName);
    File rootDir = new File(targetFolderName);
    String rootLocation = sourceUrl.substring(0, sourceUrl.lastIndexOf("/"));
    String fileName = sourceUrl.substring(sourceUrl.lastIndexOf("/") + 1);
    long fileCount = 0;

    // download content
    byte[] contentByte = downloadManager.readContentFromGET(sourceUrl);
    sourceUrlCache.add(sourceUrl);//from  www  .j  a v  a2s.com
    if (null != contentByte && contentByte.length > 0) {
        // save the content
        File targetFile = new File(rootDir, fileName);
        logger.info("Save to: " + targetFile.getAbsolutePath());
        writeTo(contentByte, new BufferedOutputStream(new FileOutputStream(targetFile)));
        fileCount++;
        logger.info("File count: " + fileCount);
        // get as text content
        String homePageContent = new String(contentByte, ENCODING_UTF_8);
        String headSection = StringUtils.substringBetween(homePageContent, "<head", "</head>");
        // download css from root page
        fileCount += downloadCss(rootDir, rootLocation, headSection);

        String bodySection = StringUtils.substringBetween(homePageContent, "<body", "</body>");
        // download other links

        fileCount += processBody(rootDir, rootLocation, bodySection);
    }
    return fileCount;
}

From source file:mitm.application.djigzo.james.mailets.PDFReplyURLBuilderTest.java

@Test
public void testUnicode() throws URLBuilderException {
    final String key = "abc";
    final String subject = "Gre";

    PDFReplyURLBuilder builder = new PDFReplyURLBuilder(new StandardHttpURLBuilder());

    builder.setBaseURL("http://www.example.com");
    builder.setUser("user@example.com");
    builder.setFrom("test@example.com");
    builder.setRecipient("test@recipient.example.com");
    builder.setSubject(subject);/*w ww  .ja v a 2 s. c  o m*/
    builder.setKey(key);
    builder.setTime(8765L);
    builder.setMessageID("123");

    String url = builder.buildURL();

    assertNotNull(url);

    PDFReplyURLBuilder.KeyProvider keyProvider = new PDFReplyURLBuilder.KeyProvider() {
        @Override
        public String getKey(PDFReplyURLBuilder builder) throws URLBuilderException {
            return key;
        }
    };

    String envelope = StringUtils.substringBetween(url, "env=", "&hmac=");
    String hmac = StringUtils.substringAfter(url, "hmac=");

    System.out.println(url);
    System.out.println(envelope);
    System.out.println(hmac);

    builder = new PDFReplyURLBuilder(new StandardHttpURLBuilder());
    builder.loadFromEnvelope(envelope, hmac, keyProvider);

    assertEquals("user@example.com", builder.getUser());
    assertEquals("test@example.com", builder.getFrom());
    assertEquals("test@recipient.example.com", builder.getRecipient());
    assertEquals(subject, builder.getSubject());
}

From source file:gov.nih.nci.cacis.ip.mirthconnect.CanonicalModelProcessor.java

/**
 * Method accepts canonical data for processing
 * // ww w. ja v a 2s . c  om
 * @param request CaCISRequest
 * @return response CaCISResponse
 * @throws AcceptCanonicalFault Fault
 * @throws
 */
@WebResult(name = "caCISResponse", targetNamespace = CACIS_NS, partName = "parameter")
@WebMethod
public gov.nih.nci.cacis.CaCISResponse acceptCanonical(
        @WebParam(partName = "parameter", name = "caCISRequest", targetNamespace = CACIS_NS) CaCISRequest request)
        throws AcceptCanonicalFault {

    final CaCISResponse response = new CaCISResponse();

    final StringWriter sw = new StringWriter();
    try {
        final JAXBContext jc = JAXBContext.newInstance(CaCISRequest.class);
        final Marshaller m = jc.createMarshaller();

        final PrintWriter pw = new PrintWriter(sw);
        m.marshal(request, pw);
        response.setStatus(ResponseStatusType.SUCCESS);
    } catch (JAXBException jaxE) {
        throw new AcceptCanonicalFault("Error Marshalling object", jaxE);
    }

    try {
        String mcResponse = webServiceMessageReceiver.processData(sw.toString());

        if (mcResponse != null && (mcResponse.indexOf("Error") > -1 || mcResponse.indexOf("Exception") > -1
                || mcResponse.indexOf("ERROR") > -1 || mcResponse.indexOf("error") > -1)) {
            mcResponse = StringUtils.remove(mcResponse, "SUCCESS:");
            String channelUid = StringUtils.substringBetween(mcResponse, "(", ")");
            if (channelUid != null) {
                mcResponse = StringUtils.remove(mcResponse, "(" + channelUid + ")");
            }
            throw new AcceptCanonicalFault(
                    StringUtils.substring(mcResponse, StringUtils.lastIndexOf(mcResponse, ':')));
        }
        response.setStatus(ResponseStatusType.SUCCESS);
        return response;
        // CHECKSTYLE:OFF
    } catch (Exception e) {
        // CHECKSTYLE:ON
        //throw new AcceptCanonicalFault("Error processing message!" + e.getMessage(), e);
        throw new AcceptCanonicalFault(e.getMessage(), e);
    }
}

From source file:com.google.gdt.eclipse.designer.model.widgets.panels.SplitPanelInfo.java

/**
 * @return the name of region used to associate given {@link WidgetInfo}.
 */// w ww . j  a  va 2 s. c  om
private static String getRegion(WidgetInfo widget) {
    String region = getWidgetAssociationMethod(widget);
    region = StringUtils.substringBetween(region, "set", "Widget");
    region = StringUtils.uncapitalize(region);
    return region;
}

From source file:com.voa.weixin.task.Task.java

/**
 * ?access_token/*from  ww w  .  j a va2s .  co  m*/
 */
public void changeToken() {
    if (StringUtils.contains(url, "ACCESS_TOKEN")) {
        url = StringUtils.replace(url, "ACCESS_TOKEN", Carp.token);
    } else {
        String oldToken = StringUtils.substringAfter(url, "access_token=");
        if (StringUtils.contains(oldToken, "&")) {
            oldToken = StringUtils.substringBetween(url, "access_token=", "&");
        }

        url = StringUtils.replace(url, oldToken, Carp.token);

    }
}

From source file:com.glluch.profilesparser.ProfileHtmlReader.java

/**
 * Read an parse a hmtl file which contains a ICT profile. Some parts are extracted 
 * with Jsop and some others from a plain text.
 * @param filename The html file where the profile is stored.
 * @return An ICTProfile read from the html file.
 */// ww w  . j  a  v  a 2  s.c  om
@Override
public ICTProfile reader(String filename) {
    ICTProfile res = new ICTProfile();

    try {
        init(filename);

        Element ts = doc.select("h2").first();
        res.setTitle(ts.ownText().trim());

        //Get summary, the text  Mission and KPI
        int i = 0;
        Elements txts = doc.select("h3 + p");
        for (Element text : txts) {
            if (i == 0) {
                res.setSummary(text.ownText());
            }
            if (i == 1) {
                res.setMission(new Mission(text.ownText()));
            }
            if (i == 2) {
                res.setKpi(text.ownText());
            }
            i++;
        }

        //Get Mission Deliverables and tasks
        String acc = StringUtils.substringBetween(allTxt, "Accountable", "Responsible").trim();
        String respon = StringUtils.substringBetween(allTxt, "Responsible", "Contributor").trim();
        String contrib = StringUtils.substringBetween(allTxt, "Contributor", "Main task/s").trim();
        String tks = StringUtils.substringBetween(allTxt, "Main task/s", "KPI area ").trim();

        HashMap<Integer, String> uls = new HashMap<>();
        i = 0;
        if (StringUtils.isNotEmpty(acc)) {
            uls.put(i++, "Accountable");
        }
        if (StringUtils.isNotEmpty(respon)) {
            uls.put(i++, "Responsible");
        }
        if (StringUtils.isNotEmpty(contrib)) {
            uls.put(i++, "Contributor");
        }
        if (StringUtils.isNotEmpty(tks)) {
            uls.put(i++, "Main task/s");
        } //TODO delete else

        //System.out.println(uls.toString());
        Elements html_uls = doc.select("ul");
        if (html_uls.size() != uls.size()) {

            System.out.println("\nERROR in " + res.getTitle() + ", num ul=" + html_uls.size() + ", num_parts="
                    + uls.size());
        }
        i = 0;
        for (Element ul : html_uls) {
            String target = uls.get(i);
            res = place(res, target, ul);
            i++;
        }

        //res.setTasks(tasks);
        //Get Competences
        i = 0;
        Elements cs = doc.select("h4");//the first h4 is not a competence

        ArrayList<String> comps = new ArrayList<>();//all comptences are here but not the levels
        for (Element c : cs) {
            if (i != 0) {
                comps.add(c.ownText());
            }
            i++;
        } //for

        res.setEcfs(foundLevels(comps, allTxt));

        //first p after first h3  h3:eq(0) + p
    } catch (IOException ex) {
        Logger.getLogger(ProfileHtmlReader.class.getName()).log(Level.SEVERE, null, ex);
    }
    return res;
}

From source file:com.intel.cosbench.driver.generator.RangeIntGenerator.java

private static RangeIntGenerator tryParse(String pattern) {
    pattern = StringUtils.substringBetween(pattern, "(", ")");
    String[] args = StringUtils.split(pattern, ",");
    int lower = Integer.parseInt(args[0]);
    int upper = Integer.parseInt(args[1]);
    return new RangeIntGenerator(lower, upper);
}

From source file:edu.sampleu.travel.web.action.TravelDocumentAction2.java

public ActionForward deleteAccount(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // Remove the travel account at the index specified in the "methodToCall" parameter.
    TravelDocumentForm2 travelForm = (TravelDocumentForm2) form;
    String strIndex = StringUtils.substringBetween(
            (String) request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE),
            KRADConstants.METHOD_TO_CALL_PARM1_LEFT_DEL, KRADConstants.METHOD_TO_CALL_PARM1_RIGHT_DEL);
    if (StringUtils.isNotBlank(strIndex)) {
        ((TravelDocument2) travelForm.getDocument()).getTravelAccounts().remove(Integer.parseInt(strIndex));
    }/*  w w w . ja v a2  s.  c o  m*/
    return mapping.findForward(RiceConstants.MAPPING_BASIC);
}