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:org.openmrs.module.atomfeed.web.AtomFeedDownloadServlet.java

/**
 * This method is called by the servlet container to process a HEAD request made by RSS readers
 * against the /atomfeed URI/*from   www.j  a v  a  2 s  . co m*/
 * 
 * @see javax.servlet.http.HttpServlet#doHead(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 * @should send not modified error if atom feed has not changed
 * @should send valid headers if atom feed has changed
 */
public void doHead(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // read atomfeed header specific information from the header file
    String headerFileContent = AtomFeedUtil.readFeedHeaderFile();
    int contentLength = 0;
    String etagToken = "";
    Date lastModified = null;
    if (StringUtils.isNotBlank(headerFileContent)) {
        contentLength = headerFileContent.length() + Integer
                .valueOf(StringUtils.substringBetween(headerFileContent, "<entriesSize>", "</entriesSize>"));
        etagToken = StringUtils.substringBetween(headerFileContent, "<versionId>", "</versionId>");
        try {
            lastModified = new SimpleDateFormat(AtomFeedUtil.RFC_3339_DATE_FORMAT)
                    .parse(StringUtils.substringBetween(headerFileContent, "<updated>", "</updated>"));
        } catch (ParseException e) {
            // ignore it here
        }
    }

    // set the content length and type
    resp.setContentLength(contentLength);
    resp.setContentType("application/atom+xml");
    resp.setCharacterEncoding("UTF-8");

    // compare previous ETag token with current one
    String previousEtagToken = req.getHeader("If-None-Match");
    Calendar ifModifiedSince = Calendar.getInstance();
    long ifModifiedSinceInMillis = req.getDateHeader("If-Modified-Since");
    ifModifiedSince.setTimeInMillis(ifModifiedSinceInMillis);
    if (((etagToken != null) && (previousEtagToken != null && previousEtagToken.equals('"' + etagToken + '"')))
            || (ifModifiedSinceInMillis > 0 && ifModifiedSince.getTime().compareTo(lastModified) >= 0)) {
        // send 304 status code that indicates that resource has not been modified
        resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        // re-use original last modified time-stamp
        resp.setHeader("Last-Modified", req.getHeader("If-Modified-Since"));
        // no further processing required
        return;
    }

    // set header for the next time the client calls
    if (etagToken != null) {
        resp.setHeader("ETag", '"' + etagToken + '"');
        // set the last modified time if it's already specified
        if (lastModified == null) {
            // otherwise set the last modified time to now
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.MILLISECOND, 0);
            lastModified = cal.getTime();
        }
        resp.setDateHeader("Last-Modified", lastModified.getTime());
    }
}

From source file:org.openmrs.module.atomfeed.web.AtomFeedDownloadServletTest.java

/**
 * @see AtomFeedDownloadServlet#doHead(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 * @verifies send not modified error if atom feed has not changed
 */// ww w . j a  v a2  s. c  o m
@Test
public void doHead_shouldSendNotModifiedErrorIfAtomFeedHasNotChanged() throws Exception {
    // create servlet and corresponding request and response object to be sent
    AtomFeedDownloadServlet atomFeedDownloadServlet = new AtomFeedDownloadServlet();
    MockHttpServletRequest request = new MockHttpServletRequest("HEAD", "/atomfeed");
    request.setContextPath("/somecontextpath");
    MockHttpServletResponse response = new MockHttpServletResponse();

    // intentionally change atom feed in order to not depend from other tests
    AtomFeedUtil.objectCreated(new Encounter());

    // read atom feed header specific information from the header file
    String headerFileContent = AtomFeedUtil.readFeedHeaderFile();
    int contentLength = 0;
    String etagToken = "";
    Date lastModified = null;
    if (StringUtils.isNotBlank(headerFileContent)) {
        contentLength = headerFileContent.length() + Integer
                .valueOf(StringUtils.substringBetween(headerFileContent, "<entriesSize>", "</entriesSize>"));
        etagToken = StringUtils.substringBetween(headerFileContent, "<versionId>", "</versionId>");
        try {
            lastModified = new SimpleDateFormat(AtomFeedUtil.RFC_3339_DATE_FORMAT)
                    .parse(StringUtils.substringBetween(headerFileContent, "<updated>", "</updated>"));
        } catch (ParseException e) {
            // ignore it here
        }
    }
    // set request headers 
    request.addHeader("If-None-Match", '"' + etagToken + '"');
    request.addHeader("If-Modified-Since", lastModified);

    atomFeedDownloadServlet.service(request, response);
    // check response headers
    Assert.assertEquals(contentLength, response.getContentLength());
    Assert.assertEquals("application/atom+xml", response.getContentType());
    Assert.assertEquals(HttpServletResponse.SC_NOT_MODIFIED, response.getStatus());
    Assert.assertNotNull(response.getHeader("Last-Modified"));
}

From source file:org.openmrs.module.hl7query.web.controller.HL7QueryControllerTest.java

/**
 * @see {@link HL7QueryController#getEncounters(String,String,String,Date,Date,HttpServletRequest)}
 *//*from  ww w . j a v  a 2s .c o  m*/
@Test
@Verifies(value = "should return the expected hl7 output as xml if the xml header exists", method = "getEncounters(String,String,String,Date,Date,HttpServletRequest)")
public void getEncounters_shouldReturnTheExpectedHl7OutputAsXmlIfTheXmlHeaderExists() throws Exception {
    //TODO Add the ORU_R01.ORDER_OBSERVATION tags(obs) to the test file 'expectedORUR01Output.xml'
    //When https://tickets.openmrs.org/browse/HLQRY-38 is completed
    String expectedOutput = IOUtils
            .toString(getClass().getClassLoader().getResourceAsStream("expectedORUR01XmlOutput.xml"));
    expectedOutput = StringUtils.deleteWhitespace(expectedOutput);

    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    request.addHeader("Accept", "text/xml");
    String hl7Output = new HL7QueryController()
            .getEncounters(null, null, ENCOUNTER_1_UUID, null, null, request, response).toString();
    hl7Output = StringUtils.deleteWhitespace(hl7Output);
    //Ignore timestamp by removing it
    hl7Output = StringUtils.replace(hl7Output, StringUtils.substringBetween(hl7Output, "<TS.1>", "</TS.1>"),
            "");
    //Ignore the uuid of the message
    hl7Output = StringUtils.replace(hl7Output, StringUtils.substringBetween(hl7Output, "<MSH.10>", "</MSH.10>"),
            "");

    Assert.assertEquals(expectedOutput, hl7Output);
}

From source file:org.openmrs.module.hl7query.web.controller.HL7QueryControllerTest.java

/**
 * @see {@link HL7QueryController#getEncounters(String,String,String,Date,Date,HttpServletRequest)}
 *//*  w w w.  j  a  v a 2 s .c  o  m*/
@Test
@Verifies(value = "should return the patient encounters given the patient identifier and id type", method = "getEncounters(String,String,String,Date,Date,HttpServletRequest)")
public void getEncounters_shouldReturnThePatientEncountersGivenThePatientIdentifierAndIdType()
        throws Exception {
    //TODO Add the ORU_R01.ORDER_OBSERVATION tags(obs) to the test file 'expectedOutput_encountersByPatient.xml'
    //When https://tickets.openmrs.org/browse/HLQRY-38 is completed
    String expectedOutput = IOUtils.toString(
            getClass().getClassLoader().getResourceAsStream("expectedOutput_encountersByPatient.xml"));
    expectedOutput = StringUtils.deleteWhitespace(expectedOutput);

    final String identifier = "6TS-4";
    final String identifierTypeUuid = "1a339fe9-38bc-4ab3-b180-320988c0b968";
    final int expectedEncounterCount = 3;
    Patient patient = Context.getPatientService().getPatient(7);
    //sanity checks
    Assert.assertEquals(identifier, patient.getPatientIdentifier().getIdentifier());
    Assert.assertEquals(identifierTypeUuid, patient.getPatientIdentifier().getIdentifierType().getUuid());
    Assert.assertEquals(expectedEncounterCount,
            Context.getEncounterService().getEncountersByPatient(patient).size());

    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    request.addHeader("Accept", "text/xml");
    String hl7Output = new HL7QueryController()
            .getEncounters(identifier, identifierTypeUuid, null, null, null, request, response).toString();

    hl7Output = StringUtils.deleteWhitespace(hl7Output);
    //Ignore timestamp by removing it
    hl7Output = StringUtils.replace(hl7Output, StringUtils.substringBetween(hl7Output, "<TS.1>", "</TS.1>"),
            "");
    //Ignore the uuid of the message
    hl7Output = StringUtils.replace(hl7Output, StringUtils.substringBetween(hl7Output, "<MSH.10>", "</MSH.10>"),
            "");

    Assert.assertEquals(expectedOutput, hl7Output);
}

From source file:org.openmrs.module.hl7query.web.controller.HL7QueryControllerTest.java

/**
 * @see {@link HL7QueryController#getEncounters(String,String,String,Date,Date,HttpServletRequest)}
 *///from   www.  ja  v  a  2  s.c  om
@Test
@Verifies(value = "should return the patient encounters matching specified start and end encounter dates", method = "getEncounters(String,String,String,Date,Date,HttpServletRequest)")
public void getEncounters_shouldReturnThePatientEncountersMatchingSpecifiedStartAndEndEncounterDates()
        throws Exception {
    //TODO Add the ORU_R01.ORDER_OBSERVATION tags(obs) to the test file 'expectedOutput_encountersByStartAndEndDate.xml'
    //When https://tickets.openmrs.org/browse/HLQRY-38 is completed
    String expectedOutput = IOUtils.toString(
            getClass().getClassLoader().getResourceAsStream("expectedOutput_encountersByStartAndEndDate.xml"));
    expectedOutput = StringUtils.deleteWhitespace(expectedOutput);

    final String identifier = "6TS-4";
    final String identifierTypeUuid = "1a339fe9-38bc-4ab3-b180-320988c0b968";
    Patient patient = Context.getPatientService().getPatient(7);
    //sanity checks
    Assert.assertEquals(identifier, patient.getPatientIdentifier().getIdentifier());
    Assert.assertEquals(identifierTypeUuid, patient.getPatientIdentifier().getIdentifierType().getUuid());

    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    request.addHeader("Accept", "text/xml");
    Encounter expectedEncounter = Context.getEncounterService().getEncounter(4);
    String hl7Output = new HL7QueryController()
            .getEncounters(identifier, identifierTypeUuid, null, expectedEncounter.getEncounterDatetime(),
                    expectedEncounter.getEncounterDatetime(), request, response)
            .toString();

    hl7Output = StringUtils.deleteWhitespace(hl7Output);
    //Ignore timestamp by removing it
    hl7Output = StringUtils.replace(hl7Output, StringUtils.substringBetween(hl7Output, "<TS.1>", "</TS.1>"),
            "");
    //Ignore the uuid of the message
    hl7Output = StringUtils.replace(hl7Output, StringUtils.substringBetween(hl7Output, "<MSH.10>", "</MSH.10>"),
            "");

    Assert.assertEquals(expectedOutput, hl7Output);
}

From source file:org.openurp.thesis.service.impl.CnkiThesisCheckServiceImpl.java

public List<CheckResult> search(String author, String article) {
    Map<String, String> params = new HashMap<String, String>();
    params.put("DDL1", "");
    params.put("TB1", author);
    params.put("DDLJCZT", "0");
    params.put("ImageButton5.x", "-762");
    params.put("ImageButton5.y", "-178");
    params.putAll(infoParams);// w  ww  .  j a  va2  s. co m
    HttpPost httpost = new HttpPost(searchUrl);
    // params.put("__ASYNCPOST","true");
    // httpost.addHeader("X-MicrosoftAjax", "Delta=true");
    String text = null;
    try {
        httpost.setEntity(new UrlEncodedFormEntity(convertToValuePairs(params), "UTF-8"));
        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();
        text = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
    } catch (Exception e) {
        return Collections.emptyList();
    }
    text = StringUtils.substringBetween(text, "GridView2", "</table>");
    if (StringUtils.isEmpty(text))
        return Collections.emptyList();
    List<CheckResult> results = extract(text);
    if (null == article)
        return results;

    List<CheckResult> rs = new ArrayList<CheckResult>();
    for (CheckResult cr : results) {
        if (null != cr.getArticle() && cr.getArticle().contains(article))
            rs.add(cr);
    }
    return rs;
}

From source file:org.openurp.thesis.service.impl.CnkiThesisCheckServiceImpl.java

/**
 * ?/* w  w w  . j a v  a 2 s.  c om*/
 * 
 * @param text
 * @return
 */
protected List<CheckResult> extract(String text) {
    Matcher m = checkPattern.matcher(text);
    List<CheckResult> results = new ArrayList<CheckResult>();
    // [2]id:value="id"
    // [5]article:<a>article</a>
    // [8]author:<a>author</a>
    // [11]content:<div title="?">0%</div><div title="??">0</div>
    // [14]date
    // [17]downloadurl:<a target="_blank"
    // href=" http://checkdownload.cnki.net/thesisdownload/?downType=0&user=yourname&userServerID=1&fileID=fileId&check=5f6cad62f7fa352955321bc1b4989912"
    // >
    while (m.find()) {
        String content = m.group(11);
        long id = Long.valueOf(StringUtils.substringBetween(m.group(2), "value=\"", "\""));
        String thesis = StringUtils.substringBetween(m.group(5), ">", "</a>");
        String author = StringUtils.substringBetween(m.group(8), ">", "</a>");
        if (content.contains("?")) {
            String ratioStr = StringUtils.substringBetween(content, "?\">", "%</div>");
            float ratio = Float.valueOf(ratioStr) / 100;
            int count = Integer.valueOf(StringUtils.substringBetween(content, "??\">", "</div>"));
            Date checkOn = Date.valueOf(m.group(14).trim());
            String checksum = StringUtils.substringBetween(m.group(17), "check=", "\"");
            results.add(new CheckResult(id, thesis, author, checksum, checkOn, ratio, count));
        } else {
            Date checkOn = Date.valueOf(m.group(14).trim());
            String checksum = StringUtils.substringBetween(m.group(17), "check=", "\"");
            results.add(new CheckResult(id, thesis, author, checksum, checkOn));
        }

    }
    return results;
}

From source file:org.pentaho.big.data.kettle.plugins.formats.impl.orc.input.OrcInputDialog.java

/**
 * When all else fails, extract he orc type from the field description.
 *
 * @see #concatenateOrcNameAndType(IOrcInputField)
 *//*from ww  w .  j  a  v a 2s .c o m*/
private OrcSpec.DataType extractOrcType(String orcNameTypeFromUI) {
    if (orcNameTypeFromUI != null) {
        String uiType = StringUtils.substringBetween(orcNameTypeFromUI, "(", ")");
        if (uiType != null) {
            String uiTypeTrimmed = uiType.trim();
            for (OrcSpec.DataType temp : OrcSpec.DataType.values()) {
                if (temp.getName().equalsIgnoreCase(uiTypeTrimmed)) {
                    return temp;
                }
            }
        }
    }
    return null;
}

From source file:org.pentaho.big.data.kettle.plugins.formats.impl.parquet.input.ParquetInputDialog.java

/**
 * When all else fails, extract he parquet type from the field description.
 *
 * @see #concatenateParquetNameAndType(IParquetInputField)
 *///from  w w  w.java  2  s  .  com
private ParquetSpec.DataType extractParquetType(String parquetNameTypeFromUI) {
    if (parquetNameTypeFromUI != null) {
        String uiType = StringUtils.substringBetween(parquetNameTypeFromUI, "(", ")");
        if (uiType != null) {
            String uiTypeTrimmed = uiType.trim();
            for (ParquetSpec.DataType temp : ParquetSpec.DataType.values()) {
                if (temp.getName().equalsIgnoreCase(uiTypeTrimmed)) {
                    return temp;
                }
            }
        }
    }
    return null;
}

From source file:org.royaldev.royalcommands.rcommands.pluginmanager.SCmdDownload.java

@Override
public boolean runCommand(final CommandSender cs, Command cmd, String label, String[] eargs,
        CommandArguments ca) {//from  w  w  w. j av a2  s.  c o  m
    if (eargs.length < 1) {
        cs.sendMessage(MessageColor.NEGATIVE + "Please provide plugin tag!");
        cs.sendMessage(MessageColor.NEGATIVE + "http://dev.bukkit.org/server-mods/" + MessageColor.NEUTRAL
                + "royalcommands" + MessageColor.NEGATIVE + "/");
        return true;
    }
    final boolean recursive = eargs.length > 1 && eargs[1].equalsIgnoreCase("true");
    final String customTag = this.getParent().getCustomTag(eargs[0]);
    final String tag = (customTag == null) ? eargs[0].toLowerCase() : customTag;
    final String commandUsed = label;
    final Runnable r = new Runnable() {
        @Override
        public void run() {
            cs.sendMessage(MessageColor.POSITIVE + "Getting download link...");
            String pluginUrlString = "http://dev.bukkit.org/server-mods/" + tag + "/files.rss";
            String file;
            try {
                final URL url = new URL(pluginUrlString);
                final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .parse(url.openConnection().getInputStream());
                doc.getDocumentElement().normalize();
                final NodeList nodes = doc.getElementsByTagName("item");
                final Node firstNode = nodes.item(0);
                if (firstNode.getNodeType() == 1) {
                    final Element firstElement = (Element) firstNode;
                    final NodeList firstElementTagName = firstElement.getElementsByTagName("link");
                    final Element firstNameElement = (Element) firstElementTagName.item(0);
                    final NodeList firstNodes = firstNameElement.getChildNodes();
                    final String link = firstNodes.item(0).getNodeValue();
                    final URL dpage = new URL(link);
                    final BufferedReader br = new BufferedReader(new InputStreamReader(dpage.openStream()));
                    final StringBuilder content = new StringBuilder();
                    String inputLine;
                    while ((inputLine = br.readLine()) != null)
                        content.append(inputLine);
                    br.close();
                    file = StringUtils.substringBetween(content.toString(),
                            "<li class=\"user-action user-action-download\"><span><a href=\"",
                            "\">Download</a></span></li>");
                } else
                    throw new Exception();
            } catch (Exception e) {
                cs.sendMessage(MessageColor.NEGATIVE
                        + "Could not fetch download link! Either this plugin has no downloads, or you specified an invalid tag.");
                cs.sendMessage(MessageColor.NEGATIVE + "Tag: http://dev.bukkit.org/server-mods/"
                        + MessageColor.NEUTRAL + "plugin-name" + MessageColor.NEGATIVE + "/");
                return;
            }
            if (SCmdDownload.this.getParent().downloadAndMovePlugin(file, null, recursive, cs)) {
                cs.sendMessage(MessageColor.POSITIVE + "Downloaded plugin. Use " + MessageColor.NEUTRAL + "/"
                        + commandUsed + " load" + MessageColor.POSITIVE + " to enable it.");
            } else
                cs.sendMessage(MessageColor.NEGATIVE + "Could not download that plugin. Please try again.");
        }
    };
    this.plugin.getServer().getScheduler().runTaskAsynchronously(this.plugin, r);
    return true;
}