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:net.canadensys.dataportal.occurrence.controller.OccurrenceController.java

/**
 * Build and fill A OccurrenceViewModel based on a OccurrenceModel.
 * /*from www .  ja  v  a 2  s . c o  m*/
 * @param occModel
 * @return OccurrenceViewModel instance, never null
 */
public OccurrenceViewModel buildOccurrenceViewModel(OccurrenceModel occModel, DwcaResourceModel resourceModel,
        List<OccurrenceExtensionModel> occMultimediaExtModelList, Locale locale) {
    OccurrenceViewModel occViewModel = new OccurrenceViewModel();
    ResourceBundle bundle = appConfig.getResourceBundle(locale);
    // handle multimedia first (priority over associatedmedia)
    if (occMultimediaExtModelList != null) {
        String multimediaFormat, multimediaLicense, multimediaReference, multimediaIdentifier, licenseShortname;
        boolean isImage;
        MultimediaViewModel multimediaViewModel;
        Map<String, String> extData;

        for (OccurrenceExtensionModel currMultimediaExt : occMultimediaExtModelList) {
            extData = currMultimediaExt.getExt_data();

            multimediaFormat = StringUtils.defaultString(extData.get("format"));
            multimediaLicense = StringUtils.defaultString(extData.get("license"));
            multimediaIdentifier = extData.get("identifier");
            // if reference is blank, use the identifier
            multimediaReference = StringUtils.defaultIfBlank(extData.get("references"), multimediaIdentifier);

            // check if it's an image
            isImage = multimediaFormat.startsWith("image");
            licenseShortname = appConfig.getLicenseShortName(multimediaLicense);

            multimediaViewModel = new MultimediaViewModel(multimediaIdentifier, multimediaReference,
                    extData.get("title"), multimediaLicense, extData.get("creator"), isImage, licenseShortname);
            occViewModel.addMultimediaViewModel(multimediaViewModel);
        }
    }

    // handle media (only if occMultimediaExtModelList was not provided)
    if ((occMultimediaExtModelList == null || occMultimediaExtModelList.isEmpty())
            && StringUtils.isNotEmpty(occModel.getAssociatedmedia())) {
        // assumes that data are coming from harvester
        String[] media = occModel.getAssociatedmedia().split("; ");

        MultimediaViewModel multimediaViewModel;
        boolean isImage;
        String title;
        int imageNumber = 1, otherMediaNumber = 1;
        for (String currentMedia : media) {
            isImage = MIME_TYPE_MAP.getContentType(currentMedia).startsWith("image");
            String image = bundle.getString("occ.image");
            if (isImage) {
                title = image + " " + imageNumber;
                imageNumber++;
            } else {
                title = bundle.getString("occ.associatedmedia") + " " + otherMediaNumber;
                otherMediaNumber++;
            }

            multimediaViewModel = new MultimediaViewModel(currentMedia, currentMedia, title, null, null,
                    isImage, null);
            occViewModel.addMultimediaViewModel(multimediaViewModel);
        }
    }

    // handle associated sequences
    handleAssociatedSequence(occModel, occViewModel);

    // handle data source page URL (url to the resource page)
    if (resourceModel != null) {
        if (StringUtils.contains(resourceModel.getArchive_url(), IPT_ARCHIVE_PATTERN)) {
            occViewModel.setDataSourcePageURL(StringUtils.replace(resourceModel.getArchive_url(),
                    IPT_ARCHIVE_PATTERN, IPT_RESOURCE_PATTERN));
        }
    }

    // handle Recommended Citation
    String datasourcePageUrl = occViewModel.getDataSourcePageURL();
    if (datasourcePageUrl != null)
        occViewModel.setRecommendedCitation(
                Formatter.buildRecommendedCitation(occModel, datasourcePageUrl, bundle));
    return occViewModel;
}

From source file:io.wcm.handler.url.suffix.SuffixBuilderTest.java

/**
 * tests escaping/unescaping functionality with keys/values/resources suffixes with slashed.
 * The slashes have to be double-escaped as well to void filtered out/misinterpreded by webserver/dispatcher-
 * @throws UnsupportedEncodingException// w  w w  .  ja va2  s  .c  o  m
 */
@Test
public void testEscapingWithSlashes() throws UnsupportedEncodingException {
    // both key and value may contain url-unsafe characters, and / = which are used as delimiters
    String slashKey1 = "my/key1";
    String slashValue1 = "my/value1";
    String slashKey2 = "my/key2";
    String slashValue2 = "my/value2";

    ValueMap keyValueMap = ImmutableValueMap.builder().put(slashKey1, slashValue1).put(slashKey2, slashValue2)
            .build();

    // create resources with valid node name
    Page basePage = context.create().page("/content/a", "template", "title");
    Resource baseResource = basePage.getContentResource();
    String resourceType1 = "resourceType1";
    ResourceTypeFilter filterType1 = new ResourceTypeFilter(resourceType1);
    Resource slashResource1 = createResource("/content/a/jcr:content/b/c1", resourceType1);
    String resourceType2 = "resourceType2";
    ResourceTypeFilter filterType2 = new ResourceTypeFilter(resourceType2);
    Resource slashResource2 = createResource("/content/a/jcr:content/b/c2", resourceType2);

    // construct suffix with all keys, values and paths properly escaped
    String suffix = getBuilder().resources(Arrays.asList(slashResource1, slashResource2), baseResource)
            .putAll(keyValueMap).build();
    assertNotNull("suffix empty", suffix);

    // ensure that no slash, not single nor double-escaped found in suffix
    assertTrue("un-escaped slash found", StringUtils.contains(suffix, SUFFIX_PART_DELIMITER)); // "/" is suffix part delimiter
    assertFalse("single-escaped slash found", StringUtils.contains(suffix, URL_ENCODED_SLASH));
    assertFalse("double-escaped slash found", StringUtils.contains(suffix, DOUBLE_URL_ENCODED_SLASH));

    // create SuffixHelper with that suffix, decode it and simulate request to the base page
    String suffixWithExtension = "/" + suffix + ".html";
    SuffixParser parser = getParserWithIncommingSuffix(suffixWithExtension, basePage);
    // both nasty keys should be found and decoded
    assertEquals(slashValue1, parser.get(slashKey1, String.class));
    assertEquals(slashValue2, parser.get(slashKey2, String.class));
    // both nasty resources should be found and decoded
    assertNotNull("resource 1 invalid", parser.getResource(filterType1));
    assertEquals(slashResource1.getPath(), parser.getResource(filterType1).getPath());
    assertNotNull("resource 2 invalid", parser.getResource(filterType2));
    assertEquals(slashResource2.getPath(), parser.getResource(filterType2).getPath());

    // suffix may be used without extension (leads to problem if . is not escaped in suffix parts)
    String suffixWithoutExtension = "/" + suffix;
    parser = getParserWithIncommingSuffix(suffixWithoutExtension, basePage);
    // both nasty keys should be found and decoded
    assertEquals(slashValue1, parser.get(slashKey1, String.class));
    assertEquals(slashValue2, parser.get(slashKey2, String.class));
    // both nasty resources should be found and decoded
    assertEquals(slashResource1.getPath(), parser.getResource(filterType1).getPath());
    assertEquals(slashResource2.getPath(), parser.getResource(filterType2).getPath());

}

From source file:com.erudika.scoold.utils.ScooldUtils.java

public void updateViewCount(Post showPost, HttpServletRequest req, HttpServletResponse res) {
    //do not count views from author
    if (showPost != null && !isMine(showPost, getAuthUser(req))) {
        String postviews = HttpUtils.getStateParam("postviews", req);
        if (!StringUtils.contains(postviews, showPost.getId())) {
            long views = (showPost.getViewcount() == null) ? 0 : showPost.getViewcount();
            showPost.setViewcount(views + 1); //increment count
            HttpUtils.setStateParam("postviews", postviews + "," + showPost.getId(), req, res);
            pc.update(showPost);/* www  .j a  v a2  s . co  m*/
        }
    }
}

From source file:com.mirth.connect.client.ui.components.MirthTree.java

private static PathNode.NodeType getXmlNodeType(MirthTreeNode node) {
    PathNode.NodeType type = null;/*from w w  w  . j av a  2 s.  com*/
    String nodeValue = node.getValue().replaceAll(" \\(.*\\)", "");

    if (nodeContainImplicitNamespace(node)) {
        type = PathNode.NodeType.XML_XMLNS_NODE;
    } else if (StringUtils.startsWith(nodeValue, "@xmlns")) {
        if (StringUtils.contains(nodeValue, ":")) {
            type = PathNode.NodeType.XML_PREFIX_DEFINITION;
        } else {
            type = PathNode.NodeType.XMLNS_DEFINITION;
        }
    } else if (StringUtils.contains(nodeValue, "@")) {
        if (StringUtils.contains(nodeValue, ":")) {
            type = PathNode.NodeType.XML_PREFIXED_ATTRIBUTE;
        } else {
            type = PathNode.NodeType.XML_ATTRIBUTE;
        }
    } else if (StringUtils.contains(nodeValue, ":")) {
        type = PathNode.NodeType.XML_PREFIXED_NODE;
    }
    return type;
}

From source file:io.wcm.handler.richtext.impl.RichTextRewriteContentHandlerImpl.java

/**
 * URL-decode value if required./*from w  w w.  j a  v a 2s .co m*/
 * @param value Probably encoded value.
 * @return Decoded value
 */
private String decodeIfEncoded(String value) {
    if (StringUtils.contains(value, "%")) {
        try {
            return URLDecoder.decode(value, CharEncoding.UTF_8);
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(ex);
        }
    }
    return value;
}

From source file:ee.ria.xroad.asyncdb.AsyncDBIntegrationTest.java

private static void validateSavedMessage(int requestNo, List<String> itemsToBeContained) throws Exception {
    try {// ww w. j  a va 2s.  c  o m
        String filePath = getMessageDetailsFilePath(requestNo, MessageQueue.MESSAGE_FILE_NAME);
        LOG.debug("Inspecting SOAP message on file path: '{}'", filePath);

        String fileContent = FileUtils.readFileToString(new File(filePath), StandardCharsets.UTF_8);
        LOG.debug("File content is: '{}'", fileContent);

        for (String item : itemsToBeContained) {
            if (!StringUtils.contains(fileContent, item)) {
                throw new IntegrationTestFailedException(
                        "Saved message does not contain expected item '" + item + "'.");
            }
        }
    } catch (FileNotFoundException e) {
        throw new IntegrationTestFailedException(e.getMessage());
    }
}

From source file:io.wcm.caravan.io.http.impl.CaravanHttpServiceConfig.java

/**
 * Checks if protocols are defined in the ribbon "listOfServers" properties, which is not supported by ribbon itself.
 * If this is the case, remove them and set our custom "http.protocol" property instead to the protocol, if
 * it is set to "auto".//from www . j av  a  2s  .  c om
 */
private void applyRibbonHostsProcotol(String serviceId) {
    Configuration archaiusConfig = ArchaiusConfig.getConfiguration();

    String[] listOfServers = archaiusConfig.getStringArray(serviceId + RIBBON_PARAM_LISTOFSERVERS);
    String protocolForAllServers = archaiusConfig.getString(serviceId + HTTP_PARAM_PROTOCOL);

    // get protocols defined in servers
    Set<String> protocolsFromListOfServers = Arrays.stream(listOfServers)
            .filter(server -> StringUtils.contains(server, "://"))
            .map(server -> StringUtils.substringBefore(server, "://")).collect(Collectors.toSet());

    // skip further processing of no protocols defined
    if (protocolsFromListOfServers.isEmpty()) {
        return;
    }

    // ensure that only one protocol is defined. if not use the first one and write a warning to the log files.
    String protocol = new TreeSet<String>(protocolsFromListOfServers).iterator().next();
    if (protocolsFromListOfServers.size() > 1) {
        log.warn("Different protocols are defined for property {}: {}. Only protocol '{}' is used.",
                RIBBON_HOSTS_PROPERTY, StringUtils.join(listOfServers, LIST_SEPARATOR), protocol);
    }

    // if http protocol is not set to "auto" write a warning as well, because protocol is defined in server list as well
    if (!(StringUtils.equals(protocolForAllServers, RequestUtil.PROTOCOL_AUTO)
            || StringUtils.equals(protocolForAllServers, protocol))) {
        log.warn(
                "Protocol '{}' is defined for property {}: {}, but an other protocol is defined in the server list: {}. Only protocol '{}' is used.",
                protocolForAllServers, PROTOCOL_PROPERTY, StringUtils.join(listOfServers, LIST_SEPARATOR),
                protocol);
    }

    // remove protocol from list of servers and store default protocol
    List<String> listOfServersWithoutProtocol = Arrays.stream(listOfServers)
            .map(server -> StringUtils.substringAfter(server, "://")).collect(Collectors.toList());
    archaiusConfig.setProperty(serviceId + RIBBON_PARAM_LISTOFSERVERS,
            StringUtils.join(listOfServersWithoutProtocol, LIST_SEPARATOR));
    archaiusConfig.setProperty(serviceId + HTTP_PARAM_PROTOCOL, protocol);
}

From source file:ching.icecreaming.action.ResourceDescriptors.java

private boolean searchFilter(String searchField, String searchOper, String searchString, Object object1) {
    boolean result1 = true;
    String string1 = null;/*  w  w  w.  j a  v a2s  .c om*/
    Integer integer1 = null;
    java.sql.Timestamp timestamp1 = null;
    org.joda.time.DateTime dateTime1 = null, dateTime2 = null;
    DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
    java.util.Date date1 = null;

    if (object1 instanceof String) {
        string1 = (String) object1;
        switch (searchOper) {
        case "eq":
            result1 = StringUtils.equals(string1, searchString);
            break;
        case "ne":
            result1 = !StringUtils.equals(string1, searchString);
            break;
        case "bw":
            result1 = StringUtils.startsWith(string1, searchString);
            break;
        case "bn":
            result1 = !StringUtils.startsWith(string1, searchString);
            break;
        case "ew":
            result1 = StringUtils.endsWith(string1, searchString);
            break;
        case "en":
            result1 = !StringUtils.endsWith(string1, searchString);
            break;
        case "cn":
            result1 = StringUtils.contains(string1, searchString);
            break;
        case "nc":
            result1 = !StringUtils.contains(string1, searchString);
            break;
        case "nu":
            result1 = StringUtils.isBlank(string1);
            break;
        case "nn":
            result1 = StringUtils.isNotBlank(string1);
            break;
        case "in":
        case "ni":
        case "lt":
        case "le":
        case "gt":
        case "ge":
        default:
            break;
        }
    } else if (object1 instanceof Integer) {
        if (NumberUtils.isNumber(searchString)) {
            integer1 = (Integer) object1;
            switch (searchOper) {
            case "eq":
                result1 = (NumberUtils.toInt(searchString, 0) == integer1.intValue());
                break;
            case "ne":
                result1 = (NumberUtils.toInt(searchString, 0) != integer1.intValue());
                break;
            case "lt":
                result1 = (NumberUtils.toInt(searchString, 0) > integer1.intValue());
                break;
            case "le":
                result1 = (NumberUtils.toInt(searchString, 0) >= integer1.intValue());
                break;
            case "gt":
                result1 = (NumberUtils.toInt(searchString, 0) < integer1.intValue());
                break;
            case "ge":
                result1 = (NumberUtils.toInt(searchString, 0) <= integer1.intValue());
                break;
            case "bw":
            case "bn":
            case "ew":
            case "en":
            case "cn":
            case "nc":
            case "in":
            case "ni":
            case "nu":
            case "nn":
            default:
                break;
            }
        }
    } else if (object1 instanceof java.sql.Timestamp || object1 instanceof java.util.Date) {
        if (object1 instanceof java.sql.Timestamp) {
            timestamp1 = (java.sql.Timestamp) object1;
            dateTime1 = new org.joda.time.DateTime(timestamp1.getTime());
        } else if (object1 instanceof java.util.Date) {
            date1 = (java.util.Date) object1;
            if (date1 != null)
                dateTime1 = new org.joda.time.DateTime(date1);
        }
        try {
            dateTime2 = dateTimeFormatter.parseDateTime(searchString);
        } catch (java.lang.IllegalArgumentException exception1) {
            dateTime2 = null;
        }
        if (dateTime2 != null && dateTime1 != null) {
            switch (searchOper) {
            case "eq":
                result1 = dateTime1.equals(dateTime2);
                break;
            case "ne":
                result1 = !dateTime1.equals(dateTime2);
                break;
            case "lt":
                result1 = dateTime1.isBefore(dateTime2);
                break;
            case "le":
                result1 = (dateTime1.isBefore(dateTime2) || dateTime1.equals(dateTime2));
                break;
            case "gt":
                result1 = dateTime1.isAfter(dateTime2);
                break;
            case "ge":
                result1 = (dateTime1.isAfter(dateTime2) || dateTime1.equals(dateTime2));
                break;
            case "bw":
            case "bn":
            case "ew":
            case "en":
            case "cn":
            case "nc":
            case "in":
            case "ni":
                break;
            case "nu":
                result1 = (timestamp1 == null);
                break;
            case "nn":
                result1 = (timestamp1 != null);
                break;
            default:
                break;
            }
        }
    }
    return !result1;
}

From source file:de.micromata.genome.db.jpa.logging.BaseJpaLoggingImpl.java

/**
 * {@inheritDoc}/*from   www.  j a  v  a  2 s  . c  om*/
 *
 */

@Override
protected void selectLogsImpl(Timestamp start, Timestamp end, Integer loglevel, String category, String msg,
        List<Pair<String, String>> logAttributes, final int startRow, final int maxRow, List<OrderBy> orderBy,
        final boolean masterOnly, final LogEntryCallback callback) throws EndOfSearch {

    final StopWatch sw = new StopWatch();
    sw.start();

    final StringBuilder queryStringBuilder = new StringBuilder(
            "select lm from " + getMasterClass().getName() + "  as lm");
    if (masterOnly == false) {
        queryStringBuilder.append(" left outer join fetch lm.attributes");
    }

    boolean firstWhere = true;
    // final List<Object> args = new ArrayList<Object>();
    Map<String, Object> argmap = new HashMap<>();
    if (start != null) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.createdAt >= :createdAtMin");
        argmap.put("createdAtMin", start);
    }
    if (end != null) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.createdAt <= :createdAtMax");
        argmap.put("createdAtMax", end);
    }
    if (loglevel != null) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.loglevel >= :logLevelMin");
        argmap.put("logLevelMin", new Short(loglevel.shortValue()));
    }
    if (StringUtils.isNotBlank(category) == true) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.category = :category");
        argmap.put("category", category);
    }
    if (StringUtils.isNotBlank(msg) == true) {
        firstWhere = addWhere(queryStringBuilder, firstWhere, "lm.shortmessage like :message");
        argmap.put("message", msg + "%");
    }
    if (logAttributes != null) {
        int attrNum = 0;
        for (Pair<String, String> pat : logAttributes) {
            ++attrNum;
            LogAttributeType at = getAttributeTypeByString(pat.getFirst());
            if (at == null) {
                GLog.warn(GenomeLogCategory.Configuration,
                        "SelLogs; Cannot find LogAttribute: " + pat.getFirst());
                continue;
            }
            if (at.isSearchKey() == false) {
                GLog.warn(GenomeLogCategory.Configuration,
                        "SelLogs; LogAttribute not searchable: " + pat.getFirst());
                continue;
            }
            if (StringUtils.contains(pat.getSecond(), "%") == false) {
                firstWhere = addWhere(queryStringBuilder, firstWhere, at.columnName(), " = :attr" + attrNum);
            } else {
                firstWhere = addWhere(queryStringBuilder, firstWhere, at.columnName(), " like :attr" + attrNum);
            }

            argmap.put("attr" + attrNum, pat.getSecond());
        }
    }

    if (CollectionUtils.isEmpty(orderBy) == false) {
        queryStringBuilder.append(" order by ");
        boolean first = true;
        for (OrderBy order : orderBy) {
            if (first == true) {
                first = false;
            } else {
                queryStringBuilder.append(", ");
            }
            String propertyName = convertColumnNameToPropertyName(order.getColumn());
            queryStringBuilder.append("lm.").append((propertyName != null) ? propertyName : order.getColumn()); // eventually
            // requires
            // translation
            // to
            // propertynames
            queryStringBuilder.append(order.isDescending() ? " desc" : " asc");
        }
    }

    EmgrFactory<DefaultEmgr> mgrfac = getEmgrFactory();
    mgrfac.runInTrans(new EmgrCallable<Void, DefaultEmgr>() {
        @Override
        public Void call(DefaultEmgr mgr) {

            Query query = mgr.createQuery(queryStringBuilder.toString());
            for (Map.Entry<String, Object> arg : argmap.entrySet()) {
                query.setParameter(arg.getKey(), arg.getValue());
            }
            query.setFirstResult(startRow);
            if (masterOnly == true) {
                query.setMaxResults(maxRow);
            } else {
                query.setMaxResults(maxRow * 10); // pessimistic assumption:
                // 10 attributes per
                // master entry
            }

            List<M> res = query.getResultList();

            for (M lmDo : res) {
                LogEntry le = new LogEntry();
                copyMasterFields(le, lmDo, masterOnly);
                try {
                    callback.onRow(le);
                } catch (EndOfSearch eos) {
                    break;
                }
            }
            return null;
        }
    });
}

From source file:com.norconex.committer.idol.IdolCommitter.java

/**
 * Add/Remove/Commit documents based on the parameters passed to the method.
 * @param url URL to post/*  w w w  . jav a2 s.  co m*/
 * @param the content to post
 */
private void postToIDOL(String url, String content) {
    HttpURLConnection con = null;
    DataOutputStream wr = null;
    try {
        con = createURLConnection(url);
        wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(content);
        wr.flush();

        //Get the response
        int responseCode = con.getResponseCode();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Sending 'POST' request to URL : " + url);
            LOG.debug("Post parameters : " + content);
            LOG.debug("Server Response Code : " + responseCode);
        }
        String response = IOUtils.toString(con.getInputStream());
        if ((isCFS() && !StringUtils.contains(response, "SUCCESS"))
                || (!isCFS() && !StringUtils.contains(response, "INDEXID"))) {
            throw new CommitterException("Unexpected HTTP response: " + response);
        }
        wr.close();
    } catch (IOException e) {
        throw new CommitterException("Cannot post content to " + createURL(), e);
    } finally {
        if (con != null) {
            con.disconnect();
        }
        IOUtils.closeQuietly(wr);
    }
}