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

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

Introduction

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

Prototype

public static boolean endsWith(String str, String suffix) 

Source Link

Document

Check if a String ends with a specified suffix.

Usage

From source file:org.mifosplatform.portfolio.client.api.ClientImagesApiResource.java

@GET
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
public Response downloadClientImage(@PathParam("clientId") final Long clientId) {

    context.authenticatedUser().validateHasReadPermission("CLIENTIMAGE");
    final ClientData clientData = this.clientReadPlatformService.retrieveOne(clientId);

    if (clientData.imageKeyDoesNotExist()) {
        throw new ImageNotFoundException("clients", clientId);
    }/*from  w  ww .ja v  a2 s  . co m*/

    File image = new File(clientData.imageKey());
    String imageName = image.getName();
    ResponseBuilder response = Response.ok(image);
    response.header("Content-Disposition", "attachment; filename=\"" + imageName + "\"");

    // TODO: Need a better way of determining image type

    // determine image type
    String contentType = IMAGE_MIME_TYPE.JPEG.getValue();
    if (StringUtils.endsWith(imageName, IMAGE_FILE_EXTENSION.GIF.getValue())) {
        contentType = IMAGE_MIME_TYPE.GIF.getValue();
    } else if (StringUtils.endsWith(imageName, IMAGE_FILE_EXTENSION.PNG.getValue())) {
        contentType = IMAGE_MIME_TYPE.PNG.getValue();
    }

    response.header("Content-Type", contentType);
    return response.build();
}

From source file:org.nuxeo.ecm.restapi.test.DocumentBrowsingTest.java

@Test
public void iCanGetThePreviewURLThroughContributor() throws Exception {
    // Given an existing document
    DocumentModel note = RestServerInit.getNote(0, session);
    Map<String, String> headers = new HashMap<>();
    headers.put(MarshallingConstants.EMBED_ENRICHERS + ".document", PreviewJsonEnricher.NAME);

    // When i do a GET Request on the note repository
    ClientResponse response = getResponse(RequestType.GET,
            "repo/" + note.getRepositoryName() + "/path" + note.getPathAsString(), headers);

    // Then i get a preview url
    assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
    JsonNode node = mapper.readTree(response.getEntityInputStream());
    JsonNode preview = node.get(RestConstants.CONTRIBUTOR_CTX_PARAMETERS).get("preview");
    assertNotNull(preview);// www .j  a  va2s.c  o m
    StringUtils.endsWith(preview.get("url").getTextValue(), "/default/");
}

From source file:org.opencommercesearch.remote.assetmanager.editor.service.RankingRuleAssetValidator.java

private void validate(AssetEditorInfo editorInfo, String attributeValue) {
    if (StringUtils.countMatches(attributeValue, RuleManager.RANKING_SEPARATOR) > 1) {
        editorInfo.getAssetService().addError(RankingRuleProperty.ATTRIBUTE, TOO_MANY_PIPE_OPERATOR_ERROR_MSG);
        if (isLoggingWarning()) {
            logWarning(TOO_MANY_PIPE_OPERATOR_ERROR_MSG);
        }//from   w w w. j  a  v a  2 s . co  m
    } else if (StringUtils.endsWith(attributeValue, RuleManager.RANKING_SEPARATOR)) {
        editorInfo.getAssetService().addError(RankingRuleProperty.ATTRIBUTE,
                MISSING_SECOND_EXPRESSION_ERROR_MSG);
        if (isLoggingWarning()) {
            logWarning(MISSING_SECOND_EXPRESSION_ERROR_MSG);
        }
    }
}

From source file:org.openmrs.module.amrsreports.rule.MohEvaluableRuleProvider.java

/**
 * @see org.openmrs.logic.rule.provider.RuleProvider#afterStartup()
 *//* ww  w. j  ava 2  s .  c  o  m*/
@Override
public void afterStartup() {

    if (log.isDebugEnabled())
        log.debug("Registering AMRS reports summary rules ...");

    try {
        ModuleClassLoader moduleClassLoader = ModuleFactory.getModuleClassLoader(AMRS_REPORT_MODULE);
        for (URL url : moduleClassLoader.getURLs()) {
            String filename = url.getFile();
            if (StringUtils.contains(filename, AMRS_REPORT_MODULE_API)) {
                ZipFile zipFile = new ZipFile(filename);
                for (Enumeration list = zipFile.entries(); list.hasMoreElements();) {
                    ZipEntry entry = (ZipEntry) list.nextElement();
                    String zipFileName = FilenameUtils.getBaseName(entry.getName());
                    String zipFileExtension = FilenameUtils.getExtension(entry.getName());
                    if (StringUtils.endsWith(zipFileName, RULE_CLASS_SUFFIX)
                            && StringUtils.equals(zipFileExtension, CLASS_SUFFIX)) {
                        MohEvaluableRuleVisitor visitor = new MohEvaluableRuleVisitor();
                        ClassReader classReader = new ClassReader(zipFile.getInputStream(entry));
                        classReader.accept(visitor, false);
                    }
                }
                zipFile.close();
            }
        }
    } catch (IOException e) {
        log.error("Processing rule classes failed. Rule might not get registered.");
    }
}

From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java

/**
 * This method writes the atom feed data to the given stream. <br/>
 * The given stream is not closed/*  w  w w. j a  va2  s.co  m*/
 * 
 * @param stream an open outputstream that will be written to
 * @param asOfDate if not null, limits the entries to only ones updated after this date
 * @should download full stream with null date
 * @should download partial stream by given date
 * @should stream multiline entry
 */
public static void getAtomFeedStream(OutputStream stream, Date asOfDate) {
    OutputStream out = new BufferedOutputStream(stream);

    File atomheaderfile = getFeedHeaderFile();
    if (atomheaderfile.exists()) {
        try {
            // stream the atom header to output
            String atomHeader = FileUtils.readFileToString(atomheaderfile);
            // truncate "</feed>" from the atom header string
            if (StringUtils.isNotBlank(atomHeader)) {
                atomHeader = StringUtils.substringBeforeLast(atomHeader, "</feed>");
            }
            // write part of the header to the stream 
            out.write(atomHeader.getBytes());

            // then stream the entries to the output
            File atomfile = getFeedEntriesFile();

            // if the date filtering parameter is passed in
            // we need to limit the entries to only ones, which were 
            // updated after this date
            if (asOfDate != null) {
                String entry;
                BufferedReader br = new BufferedReader(new FileReader(atomfile));
                while ((entry = br.readLine()) != null) {
                    // if current entry has a new line then handle it gracefully
                    while (!StringUtils.endsWith(entry, "</entry>")) {
                        String newLine = br.readLine();
                        // if end of file is reached and new line does not contain new entry
                        if (newLine != null && !StringUtils.contains(newLine, "<entry>")) {
                            entry = entry.concat("\n").concat(newLine);
                        } else {
                            // otherwise an invalid entry is found, terminate processing
                            throw new Exception("Invalid atom feed entry. No end tag </entry> found.");
                        }
                    }
                    Date updated = new SimpleDateFormat(RFC_3339_DATE_FORMAT)
                            .parse(StringUtils.substringBetween(entry, "<updated>", "</updated>"));
                    if (updated.compareTo(asOfDate) > -1) {
                        // write entry to the stream 
                        entry = entry.concat("\n");
                        out.write(entry.getBytes());
                    } else {
                        // if entry with updatedDate lower that given one is reached
                        // we need to stop filtering
                        break;
                    }
                }
            } else {
                // bulk write all entries to the stream 
                out.write(FileUtils.readFileToByteArray(atomfile));
            }

            // write the "</feed>" element that isn't in the entries file (and was
            // in the header file)
            out.write("</feed>".getBytes());
            out.flush();
        } catch (Exception e) {
            log.error("Unable to stream atom header file and/or entries file, because of error: ", e);
        }
    }
}

From source file:org.openmrs.module.atomfeed.AtomFeedUtilTest.java

/**
 * @see AtomFeedUtil#getAtomFeedStream(java.io.OutputStream, java.util.Date)
 * @verifies download full stream with null date
 *///from w w w  .j  av a2s. c o m
@Test
public void getAtomFeedStream_shouldDownloadFullStreamWithNullDate() throws Exception {
    MockHttpServletResponse response = new MockHttpServletResponse();
    // if atom feed file exists, just get rid of it 
    File feedFile = AtomFeedUtil.getFeedEntriesFile();
    if (feedFile.exists()) {
        feedFile.delete();
    }
    // write couple of entries to atom feed 
    AtomFeedUtil.writeToFeed("test1", new Encounter());
    AtomFeedUtil.writeToFeed("test2", new Patient());

    AtomFeedUtil.getAtomFeedStream(response.getOutputStream(), null);

    // get response content to use it when asserting
    String responseContent = response.getContentAsString();

    // test if response contains header file content
    String atomHeader = FileUtils.readFileToString(AtomFeedUtil.getFeedHeaderFile());
    // truncate "</feed>" from the atom header string
    if (StringUtils.isNotBlank(atomHeader)) {
        atomHeader = StringUtils.substringBeforeLast(atomHeader, "</feed>");
    }
    Assert.assertTrue(StringUtils.contains(responseContent, atomHeader));

    // test that response content also contains both entries
    Assert.assertTrue(StringUtils.contains(responseContent, "<action>test1</action>"));
    Assert.assertTrue(StringUtils.contains(responseContent, "<action>test2</action>"));

    // test that response content also contains closing tag </feed>
    Assert.assertTrue(StringUtils.endsWith(responseContent, "</feed>"));
}

From source file:org.openmrs.module.atomfeed.AtomFeedUtilTest.java

/**
 * @see AtomFeedUtil#getAtomFeedStream(java.io.OutputStream, java.util.Date)
 * @verifies download partial stream by given date
 *///from ww  w  .  j  a va  2 s  .  c om
@Test
public void getAtomFeedStream_shouldDownloadPartialStreamByGivenDate() throws Exception {
    MockHttpServletResponse response = new MockHttpServletResponse();
    // if atom feed file exists, just get rid of it 
    File feedFile = AtomFeedUtil.getFeedEntriesFile();
    if (feedFile.exists()) {
        feedFile.delete();
    }
    // write couple of entries to atom feed 
    AtomFeedUtil.writeToFeed("test1", new Encounter());
    AtomFeedUtil.writeToFeed("test2", new Patient());
    // do some sleep to have asOfDate parameter for filtering entries
    Calendar asOfDate = Calendar.getInstance();
    Thread.sleep(1500);
    // add another entries (ones which will be filtered to stream)
    AtomFeedUtil.writeToFeed("test3", new Encounter());
    AtomFeedUtil.writeToFeed("test4", new Patient());

    AtomFeedUtil.getAtomFeedStream(response.getOutputStream(), asOfDate.getTime());

    // get response content to use it when asserting
    String responseContent = response.getContentAsString();

    // test if response contains header file content
    String atomHeader = FileUtils.readFileToString(AtomFeedUtil.getFeedHeaderFile());
    // truncate "</feed>" from the atom header string
    if (StringUtils.isNotBlank(atomHeader)) {
        atomHeader = StringUtils.substringBeforeLast(atomHeader, "</feed>");
    }
    Assert.assertTrue(StringUtils.contains(responseContent, atomHeader));

    // test that response content also contains both entries, added after sleep
    Assert.assertTrue(StringUtils.contains(responseContent, "<action>test3</action>"));
    Assert.assertTrue(StringUtils.contains(responseContent, "<action>test4</action>"));

    // test that response content also contains both entries, added after sleep
    Assert.assertFalse(StringUtils.contains(responseContent, "<action>test1</action>"));
    Assert.assertFalse(StringUtils.contains(responseContent, "<action>test2</action>"));

    // test that response content also contains closing tag </feed>
    Assert.assertTrue(StringUtils.endsWith(responseContent, "</feed>"));

}

From source file:org.openmrs.module.atomfeed.AtomFeedUtilTest.java

/**
 * @see AtomFeedUtil#getAtomFeedStream(java.io.OutputStream, java.util.Date)
 * @verifies stream multiline entry/*from  ww w  .  j  a  v a  2  s.  c  o m*/
 */
@Test
public void getAtomFeedStream_shouldStreamMultiLineEntry() throws Exception {
    MockHttpServletResponse response = new MockHttpServletResponse();
    // if atom feed file exists, just get rid of it 
    File feedFile = AtomFeedUtil.getFeedEntriesFile();
    if (feedFile.exists()) {
        feedFile.delete();
    }
    // do some sleep to have asOfDate parameter for filtering entries
    Calendar asOfDate = Calendar.getInstance();
    Thread.sleep(1500);
    // write couple of entries to atom feed 
    AtomFeedUtil.writeToFeed("test1\ntest2", new Encounter());
    AtomFeedUtil.writeToFeed("test3", new Encounter());
    AtomFeedUtil.writeToFeed("test4", new Patient());

    AtomFeedUtil.getAtomFeedStream(response.getOutputStream(), asOfDate.getTime());

    // get response content to use it when asserting
    String responseContent = response.getContentAsString();

    // test if response contains header file content
    String atomHeader = FileUtils.readFileToString(AtomFeedUtil.getFeedHeaderFile());
    // truncate "</feed>" from the atom header string
    if (StringUtils.isNotBlank(atomHeader)) {
        atomHeader = StringUtils.substringBeforeLast(atomHeader, "</feed>");
    }
    Assert.assertTrue(StringUtils.contains(responseContent, atomHeader));

    // test that response content also contains entries
    Assert.assertTrue(StringUtils.contains(responseContent, "test1\ntest2"));
    Assert.assertTrue(StringUtils.contains(responseContent, "<action>test3</action>"));
    Assert.assertTrue(StringUtils.contains(responseContent, "<action>test4</action>"));

    // test that response content also contains closing tag </feed>
    Assert.assertTrue(StringUtils.endsWith(responseContent, "</feed>"));

}

From source file:org.openmrs.module.clinicalsummary.evaluator.reminder.ReminderUtils.java

/**
 * This evaluation method are meant to be used inside velocity template. The method will return empty result when any exception happens during the
 * execution of the rule.// w  w w  .j  av a2  s  . c  om
 *
 * @see org.openmrs.module.clinicalsummary.service.EvaluatorService#evaluate(Patient, String, java.util.Map)
 */
public void evaluate(final Patient patient, final String token, final Map<String, Object> parameters) {
    try {
        if (StringUtils.endsWith(token, REMINDER_TOKEN_MARKER)) {
            EvaluatorService evaluatorService = Context.getService(EvaluatorService.class);
            Result result = evaluatorService.evaluate(patient, token, parameters);
            if (StringUtils.isNotEmpty(result.toString())) {
                Reminder reminder = new Reminder(new Date(), result.toString(), token);

                List<Mapping> mappings = Context.getService(SummaryService.class).getMappings(summary, null,
                        null);
                Collection<String> encounterTypes = new ArrayList<String>();
                for (Mapping mapping : mappings) {
                    EncounterType encounterType = mapping.getEncounterType();
                    encounterTypes.add(encounterType.getName());
                }

                Map<String, Object> encounterParameters = new HashMap<String, Object>();
                parameters.put(EvaluableConstants.ENCOUNTER_TYPE, encounterTypes);
                parameters.put(EvaluableConstants.ENCOUNTER_FETCH_SIZE, 1);

                Result encounterResults = evaluatorService.evaluate(patient,
                        EncounterWithStringRestrictionRule.TOKEN, encounterParameters);
                if (CollectionUtils.isNotEmpty(encounterResults)) {
                    Result encounterResult = encounterResults.latest();
                    Encounter encounter = (Encounter) encounterResult.getResultObject();
                    reminder.setEncounter(encounter);
                    reminder.setPatient(encounter.getPatient());
                    reminder.setProvider(encounter.getProvider());
                    reminder.setLocation(encounter.getLocation());
                    reminder.setReminderDatetime(encounter.getEncounterDatetime());
                }
                Context.getService(ReminderService.class).saveReminder(reminder);
            }
        }
    } catch (Exception e) {
        log.error("Evaluating token " + token + " on patient " + patient.getPatientId() + " failed ...", e);
    }
}

From source file:org.openmrs.module.clinicalsummary.rule.EvaluableSummaryRuleProvider.java

/**
 * @see org.openmrs.logic.rule.provider.RuleProvider#afterStartup()
 *//*  ww w.  ja  v a2  s  . c om*/
@Override
public void afterStartup() {

    if (log.isDebugEnabled())
        log.debug("Registering clinical summary rules ...");

    try {
        ModuleClassLoader moduleClassLoader = ModuleFactory.getModuleClassLoader(CLINICAL_SUMMARY_MODULE);
        for (URL url : moduleClassLoader.getURLs()) {
            String filename = url.getFile();
            if (StringUtils.contains(filename, CLINICAL_SUMMARY_MODULE_API)) {
                ZipFile zipFile = new ZipFile(filename);
                for (Enumeration list = zipFile.entries(); list.hasMoreElements();) {
                    ZipEntry entry = (ZipEntry) list.nextElement();
                    String zipFileName = FilenameUtils.getBaseName(entry.getName());
                    String zipFileExtension = FilenameUtils.getExtension(entry.getName());
                    if (StringUtils.endsWith(zipFileName, RULE_CLASS_SUFFIX)
                            && StringUtils.equals(zipFileExtension, CLASS_SUFFIX)) {
                        EvaluableRuleVisitor visitor = new EvaluableRuleVisitor();
                        ClassReader classReader = new ClassReader(zipFile.getInputStream(entry));
                        classReader.accept(visitor, false);
                    }
                }
                zipFile.close();
            }
        }
    } catch (IOException e) {
        log.error("Processing rule classes failed. Rule might not get registered.");
    }
}