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

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

Introduction

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

Prototype

public static boolean contains(final CharSequence seq, final CharSequence searchSeq) 

Source Link

Document

Checks if CharSequence contains a search CharSequence, handling null .

Usage

From source file:org.diorite.cfg.system.elements.StringTemplateElement.java

@Override
public void appendValue(final Appendable writer, final CfgEntryData field, final Object source,
        final Object elementRaw, final int level, final ElementPlace elementPlace) throws IOException {
    StringStyle style = field.getOption(FieldOptions.STRING_STYLE, StringStyle.DEFAULT);
    if ((style == StringStyle.ALWAYS_MULTI_LINE) && (elementPlace == ElementPlace.SIMPLE_LIST_OR_MAP)) // multi line strings don't works in simple lists/maps.
    {// ww  w. j  a v a  2  s  . c o m
        style = StringStyle.DEFAULT;
    }
    final String element = Enum.class.isAssignableFrom(elementRaw.getClass()) ? ((Enum<?>) elementRaw).name()
            : elementRaw.toString();
    switch (style) {
    case ALWAYS_QUOTED: {
        writeQuoted(writer, element);
        break;
    }
    case ALWAYS_SINGLE_QUOTED: {
        writeSingleQuoted(writer, StringUtils.replaceEach(element, REP_PREV_1, REP_PREV_2));
        break;
    }
    case ALWAYS_MULTI_LINE: {
        writeMultiLine(writer, element, level, elementPlace);
        break;
    }
    default: {
        final boolean haveNewLines = StringUtils.contains(element, '\n');
        if ((elementPlace != ElementPlace.SIMPLE_LIST_OR_MAP) && haveNewLines) {
            writeMultiLine(writer, element, level, elementPlace);
            return;
        }
        boolean needQuote = false;
        if (element.isEmpty()) {
            writeSingleQuoted(writer, element);
            return;
        }
        final char f = element.charAt(0);
        if (StringUtils.containsAny(element, ':', '#')) {
            needQuote = true;
        } else {
            for (final char c : CANT_BE_FIRST) {
                if (c == f) {
                    needQuote = true;
                    break;
                }
            }
        }
        if (needQuote) {
            writeQuoted(writer, element);
            return;
        }
        if (StringUtils.isNumeric(element)) {
            writeQuoted(writer, element);
        } else {
            writer.append(StringUtils.replace(element, "\n", "\\n"));
        }
        break;
    }
    }
}

From source file:org.displaytag.jsptests.PaginationTest.java

/**
 * Verifies that the generated page contains the pagination links with the inupt parameter. Tests #917200 ("{}" in
 * parameters).//from  www. j  a  v a  2  s.  com
 *
 * @throws Exception any axception thrown during test.
 */
@Override
@Test
public void doTest() throws Exception {

    WebRequest request = new GetMethodWebRequest(getJspUrl(getJspName()));
    request.setParameter("{foo}", "/.,;:/||\\bar");

    WebResponse response = this.runner.getResponse(request);

    if (this.log.isDebugEnabled()) {
        this.log.debug("RESPONSE: " + response.getText());
    }

    WebLink[] links = response.getLinks();

    Assert.assertEquals("Wrong number of links in result.", 4, links.length);

    for (int j = 0; j < links.length; j++) {
        if (this.log.isDebugEnabled()) {
            this.log.debug(j + " " + links[j].getURLString());
        }

        Assert.assertTrue(
                StringUtils.contains(links[j].getURLString(), "%7Bfoo%7D=%2F.%2C%3B%3A%2F%7C%7C%5Cbar"));
    }

}

From source file:org.dspace.app.rest.BitstreamContentRestControllerIT.java

@Test
public void retrieveCitationCoverpageOfBitstream() throws Exception {
    configurationService.setProperty("citation-page.enable_globally", true);
    citationDocumentService.afterPropertiesSet();
    context.turnOffAuthorisationSystem();

    //** GIVEN **
    //1. A community-collection structure with one parent community and one collections.
    parentCommunity = CommunityBuilder.createCommunity(context).withName("Parent Community").build();

    Collection col1 = CollectionBuilder.createCollection(context, parentCommunity).withName("Collection 1")
            .build();// w w w. j a v  a 2  s  . c  o m

    //2. A public item with a bitstream
    File originalPdf = new File(testProps.getProperty("test.bitstream"));

    try (InputStream is = new FileInputStream(originalPdf)) {

        Item publicItem1 = ItemBuilder.createItem(context, col1)
                .withTitle("Public item citation cover page test 1").withIssueDate("2017-10-17")
                .withAuthor("Smith, Donald").withAuthor("Doe, John").build();

        Bitstream bitstream = BitstreamBuilder.createBitstream(context, publicItem1, is)
                .withName("Test bitstream")
                .withDescription("This is a bitstream to test the citation cover page.")
                .withMimeType("application/pdf").build();

        //** WHEN **
        //We download the bitstream
        byte[] content = getClient().perform(get("/api/core/bitstreams/" + bitstream.getID() + "/content"))

                //** THEN **
                .andExpect(status().isOk())

                //The Content Length must match the full length
                .andExpect(header().string("Content-Length", not(nullValue())))
                //The server should indicate we support Range requests
                .andExpect(header().string("Accept-Ranges", "bytes"))
                //The ETag has to be based on the checksum
                .andExpect(header().string("ETag", bitstream.getChecksum()))
                //We expect the content type to match the bitstream mime type
                .andExpect(content().contentType("application/pdf"))
                //THe bytes of the content must match the original content
                .andReturn().getResponse().getContentAsByteArray();

        // The citation cover page contains the item title.
        // We will now verify that the pdf text contains this title.
        String pdfText = extractPDFText(content);
        System.out.println(pdfText);
        assertTrue(StringUtils.contains(pdfText, "Public item citation cover page test 1"));

        // The dspace-api/src/test/data/dspaceFolder/assetstore/ConstitutionofIreland.pdf file contains 64 pages,
        // manually counted + 1 citation cover page
        assertEquals(65, getNumberOfPdfPages(content));

        //A If-None-Match HEAD request on the ETag must tell is the bitstream is not modified
        getClient().perform(head("/api/core/bitstreams/" + bitstream.getID() + "/content")
                .header("If-None-Match", bitstream.getChecksum())).andExpect(status().isNotModified());

        //The download and head request should also be logged as a statistics record
        checkNumberOfStatsRecords(bitstream, 2);
    }
}

From source file:org.dspace.servicemanager.config.DSpaceEnvironmentConfiguration.java

public static Map<String, Object> getModifiedEnvMap() {
    HashMap<String, Object> env = new HashMap<>(System.getenv().size());
    for (String key : System.getenv().keySet()) {
        // ignore all properties that do not contain __ as those will be loaded
        // by apache commons config environment lookup.
        if (!StringUtils.contains(key, "__")) {
            continue;
        }/* www .  j  a  v a  2  s  . c o m*/

        // replace "__P__" with a single dot.
        // replace "__D__" with a single dash.
        String lookup = StringUtils.replace(key, "__P__", ".");
        lookup = StringUtils.replace(lookup, "__D__", "-");
        if (System.getenv(key) != null) {
            // store the new key with the old value in our new properties map.
            env.put(lookup, System.getenv(key));
            log.debug("Found env " + lookup + " = " + System.getenv(key) + ".");
        } else {
            log.debug("Didn't found env " + lookup + ".");
        }
    }
    return env;
}

From source file:org.echoice.core.module.jpa.Hibernates.java

public static String getDialect(DataSource dataSource) {
    String jdbcUrl = getJdbcUrlFromDataSource(dataSource);

    if (StringUtils.contains(jdbcUrl, ":h2:")) {
        return H2Dialect.class.getName();
    } else if (StringUtils.contains(jdbcUrl, ":mysql:")) {
        return MySQL5InnoDBDialect.class.getName();
    } else if (StringUtils.contains(jdbcUrl, ":oracle:")) {
        return Oracle10gDialect.class.getName();
    } else if (StringUtils.contains(jdbcUrl, ":postgresql:")) {
        return PostgreSQL82Dialect.class.getName();
    } else if (StringUtils.contains(jdbcUrl, ":sqlserver:")) {
        return SQLServer2008Dialect.class.getName();
    } else {//from ww  w .  j  a v  a2 s.co  m
        throw new IllegalArgumentException("Unknown Database of " + jdbcUrl);
    }
}

From source file:org.eclipse.epp.internal.logging.aeri.ui.utils.Proxies.java

/**
 * Returns the domain of the current machine- if any.
 *
 * @param userName/*from ww w.  ja  v  a 2s.co m*/
 *            the user name which may be null. On windows it may contain the domain name as prefix "domain\\username".
 */
public static Optional<String> getUserDomain(String userName) {

    // check the app's system properties
    String domain = System.getProperty(PROP_HTTP_AUTH_NTLM_DOMAIN);
    if (domain != null) {
        return of(domain);
    }

    // check the OS environment
    domain = System.getenv(ENV_USERDOMAIN);
    if (domain != null) {
        return of(domain);
    }

    // test the user's name whether it may contain an information about the domain name
    if (StringUtils.contains(userName, DOUBLEBACKSLASH)) {
        return of(substringBefore(userName, DOUBLEBACKSLASH));
    }

    // no domain name found
    return absent();
}

From source file:org.emau.icmvc.ganimed.epix.core.internal.PersonPreprocessedCache.java

private List<PersonPreprocessed> getPersonsPreprocessedByPdqWithAnd(List<PersonPreprocessed> persons,
        SearchMask mask, int maxResults) {
    for (PersonPreprocessed person : ppCache.values()) {
        Calendar.getInstance().setTime(person.getBirthDate());
        boolean result = true;
        boolean checkIf = false;

        if (persons.size() < maxResults) {
            if (StringUtils.isNotEmpty(mask.getFirstName())) {
                result = result && StringUtils.contains(person.getFirstName().toLowerCase(),
                        mask.getFirstName().toLowerCase());
                checkIf = true;/*from w ww . ja  v a 2 s . c  o m*/
            }

            if (StringUtils.isNotEmpty(mask.getLastName())) {
                result = result && StringUtils.contains(person.getLastName().toLowerCase(),
                        mask.getLastName().toLowerCase());
                checkIf = true;
            }

            if (StringUtils.isNotEmpty(mask.getBirthDay())) {
                result = result && Calendar.getInstance().get(Calendar.DAY_OF_MONTH) == Integer
                        .parseInt(mask.getBirthDay());
                checkIf = true;
            }

            if (StringUtils.isNotEmpty(mask.getBirthMonth())) {
                result = result
                        && Calendar.getInstance().get(Calendar.MONTH) == Integer.parseInt(mask.getBirthMonth());
                checkIf = true;
            }

            if (StringUtils.isNotEmpty(mask.getBirthYear())) {
                result = result
                        && Calendar.getInstance().get(Calendar.YEAR) == Integer.parseInt(mask.getBirthYear());

                checkIf = true;
            }

            if (result & checkIf) {
                persons.add(person);
            }
        }
    }
    return persons;
}

From source file:org.esigate.extension.parallelesi.Esi.java

@Override
public boolean event(EventDefinition id, Event event) {
    RenderEvent renderEvent = (RenderEvent) event;

    boolean doEsi = true;

    // ensure we should process esi
    if (renderEvent.getHttpResponse() != null
            && renderEvent.getHttpResponse().containsHeader(Surrogate.H_X_ENABLED_CAPABILITIES)) {
        String enabledCapabilities = renderEvent.getHttpResponse()
                .getFirstHeader(Surrogate.H_X_ENABLED_CAPABILITIES).getValue();

        doEsi = false;//from ww w  . ja  v a2  s.  c om
        for (String capability : CAPABILITIES) {
            if (StringUtils.contains(enabledCapabilities, capability)) {
                doEsi = true;
                break;
            }
        }

    }

    if (doEsi) {
        renderEvent.getRenderers().add(new EsiRenderer(this.executor));
    }

    // Continue processing
    return true;
}

From source file:org.exist.mongodb.xquery.gridfs.Get.java

/**
 *  Get document from GridFS//from w  ww .  j  a v a 2s . com
 */
Sequence get(GridFSDBFile gfsFile, boolean forceBinary) throws IOException, XPathException {

    // Obtain meta-data
    DBObject metadata = gfsFile.getMetaData();

    // Decompress when needed
    String compression = (metadata == null) ? null : (String) metadata.get(EXIST_COMPRESSION);
    boolean isGzipped = StringUtils.equals(compression, Constants.GZIP);
    InputStream is = isGzipped ? new GZIPInputStream(gfsFile.getInputStream()) : gfsFile.getInputStream();

    // Find what kind of data is stored
    int datatype = (metadata == null) ? Type.UNTYPED : (int) metadata.get(EXIST_DATATYPE);
    boolean hasXMLContentType = StringUtils.contains(gfsFile.getContentType(), "xml");
    boolean isXMLtype = (Type.DOCUMENT == datatype || Type.ELEMENT == datatype || hasXMLContentType);

    // Convert input stream to eXist-db object
    Sequence retVal;
    if (forceBinary || !isXMLtype) {
        retVal = Base64BinaryDocument.getInstance(context, is);

    } else {
        retVal = processXML(context, is);
    }
    return retVal;
}

From source file:org.exist.mongodb.xquery.gridfs.Stream.java

/**
 * Stream document to HTTP agent//from  w  w  w.java2 s. c o  m
 */
void stream(GridFSDBFile gfsFile, String documentId, Boolean setDisposition)
        throws IOException, XPathException {
    if (gfsFile == null) {
        throw new XPathException(this, GridfsModule.GRFS0004,
                String.format("Document '%s' could not be found.", documentId));
    }

    DBObject metadata = gfsFile.getMetaData();

    // Determine actual size
    String compression = (metadata == null) ? null : (String) metadata.get(EXIST_COMPRESSION);
    Long originalSize = (metadata == null) ? null : (Long) metadata.get(EXIST_ORIGINAL_SIZE);

    long length = gfsFile.getLength();
    if (originalSize != null) {
        length = originalSize;
    }

    // Stream response stream
    ResponseWrapper rw = getResponseWrapper(context);

    // Set HTTP Headers
    rw.addHeader(Constants.CONTENT_LENGTH, String.format("%s", length));

    // Set filename when required
    String filename = determineFilename(documentId, gfsFile);
    if (setDisposition && StringUtils.isNotBlank(filename)) {
        rw.addHeader(Constants.CONTENT_DISPOSITION, String.format("attachment;filename=%s", filename));
    }

    String contentType = getMimeType(gfsFile.getContentType(), filename);
    if (contentType != null) {
        rw.setContentType(contentType);
    }

    boolean isGzipSupported = isGzipEncodingSupported(context);

    // Stream data
    if ((StringUtils.isBlank(compression))) {
        // Write data as-is, no marker available that data is stored compressed
        try (OutputStream os = rw.getOutputStream()) {
            gfsFile.writeTo(os);
            os.flush();
        }

    } else {

        if (isGzipSupported && StringUtils.contains(compression, GZIP)) {
            // Write compressend data as-is, since data is stored as gzipped data and
            // the agent suports it.
            rw.addHeader(Constants.CONTENT_ENCODING, GZIP);
            try (OutputStream os = rw.getOutputStream()) {
                gfsFile.writeTo(os);
                os.flush();
            }

        } else {
            // Write data uncompressed
            try (OutputStream os = rw.getOutputStream()) {
                InputStream is = gfsFile.getInputStream();
                try (GZIPInputStream gzis = new GZIPInputStream(is)) {
                    IOUtils.copyLarge(gzis, os);
                    os.flush();
                }
            }
        }
    }
}