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

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

Introduction

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

Prototype

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

Source Link

Document

Gets the String that is nested in between two Strings.

Usage

From source file:edu.si.services.beans.edansidora.EdanAPITest.java

@Test
public void solrIDSTest() throws Exception {

    MockEndpoint mockResult = getMockEndpoint("mock:result");

    //Test IDS solr
    SOLR_PORT = 8089;//from  ww  w  .ja  v a2s . c  o  m
    String uri = SOLR_SERVER + ":" + SOLR_PORT + "/solr/ids/select";
    String solrQuery = "archive:EMAMMAL AND uan:emammal_image_d33997s6i1";
    String httpQuery = "?q=" + URLEncoder.encode(solrQuery, "UTF-8") + "&wt=json&indent=true";

    Exchange exchange = new DefaultExchange(context);
    exchange.getIn().setHeader("CamelHttpMethod", "GET");
    exchange.getIn().setHeader("CamelHttpQuery", httpQuery);
    exchange.getIn().setHeader("uri", uri);

    assumeTrue("The Solr Server could not be found! Make sure you are connected to SI VPN!",
            hostAvailabilityCheck(SOLR_SERVER, SOLR_PORT));

    template.send("direct:solrTest", exchange);

    assertMockEndpointsSatisfied();

    JSONObject json = new JSONObject(mockResult.getExchanges().get(0).getIn().getBody(String.class));

    String expected_archive = StringUtils.substringBetween(solrQuery, "archive:", " ");
    String result_archive = json.getJSONObject("response").getJSONArray("docs").getJSONObject(0)
            .getString("archive");
    LOG.info("Expected archive = {}, Returned archive = {}", expected_archive, result_archive);
    assertEquals("The returned archive does not match", expected_archive, result_archive);

    String expected_uan = StringUtils.substringAfter(solrQuery, "uan:");
    String result_uan = json.getJSONObject("response").getJSONArray("docs").getJSONObject(0).getString("uan");
    LOG.info("Expected uan = {}, Returned uan = {}", expected_uan, result_uan);
    assertEquals("The returned uan does not match", expected_uan, result_uan);

}

From source file:com.gargoylesoftware.htmlunit.javascript.host.css.CSSStyleSheet.java

/**
 * @param documentMode see {@link HTMLDocument#getDocumentMode()}
 *//*from w ww  . j  av a  2  s .c om*/
private static boolean isValidCondition(final Condition condition, final int documentMode,
        final DomNode domNode) {
    switch (condition.getConditionType()) {
    case Condition.SAC_AND_CONDITION:
        final CombinatorCondition cc1 = (CombinatorCondition) condition;
        return isValidCondition(cc1.getFirstCondition(), documentMode, domNode)
                && isValidCondition(cc1.getSecondCondition(), documentMode, domNode);
    case Condition.SAC_ATTRIBUTE_CONDITION:
    case Condition.SAC_ID_CONDITION:
    case Condition.SAC_LANG_CONDITION:
    case Condition.SAC_ONE_OF_ATTRIBUTE_CONDITION:
    case Condition.SAC_BEGIN_HYPHEN_ATTRIBUTE_CONDITION:
    case Condition.SAC_ONLY_CHILD_CONDITION:
    case Condition.SAC_ONLY_TYPE_CONDITION:
    case Condition.SAC_CONTENT_CONDITION:
    case Condition.SAC_CLASS_CONDITION:
        return true;
    case Condition.SAC_PSEUDO_CLASS_CONDITION:
        final PseudoClassConditionImpl pcc = (PseudoClassConditionImpl) condition;
        String value = pcc.getValue();
        if (value.endsWith(")")) {
            if (value.endsWith("()")) {
                return false;
            }
            value = value.substring(0, value.indexOf('(') + 1) + ')';
        }
        if (documentMode < 9) {
            return CSS2_PSEUDO_CLASSES.contains(value);
        }

        if (!CSS2_PSEUDO_CLASSES.contains(value)
                && domNode.hasFeature(QUERYSELECTOR_CSS3_PSEUDO_REQUIRE_ATTACHED_NODE)
                && !domNode.isDirectlyAttachedToPage() && !domNode.hasChildNodes()) {
            throw new CSSException("Syntax Error");
        }

        if ("nth-child()".equals(value)) {
            final String arg = StringUtils.substringBetween(pcc.getValue(), "(", ")").trim();
            return "even".equalsIgnoreCase(arg) || "odd".equalsIgnoreCase(arg)
                    || NTH_NUMERIC.matcher(arg).matches() || NTH_COMPLEX.matcher(arg).matches();
        }
        return CSS3_PSEUDO_CLASSES.contains(value);
    default:
        LOG.warn("Unhandled CSS condition type '" + condition.getConditionType() + "'. Accepting it silently.");
        return true;
    }
}

From source file:cgeo.geocaching.connector.gc.GCParser.java

public static List<TrackableLog> parseTrackableLog(final String page) {
    if (StringUtils.isEmpty(page)) {
        return null;
    }//from  www.  j ava2s.c o m

    String table = StringUtils.substringBetween(page, "<table id=\"tblTravelBugs\"", "</table>");

    // if no trackables are currently in the account, the table is not available, so return an empty list instead of null
    if (StringUtils.isBlank(table)) {
        return Collections.emptyList();
    }

    table = StringUtils.substringBetween(table, "<tbody>", "</tbody>");
    if (StringUtils.isBlank(table)) {
        Log.e("GCParser.parseTrackableLog: tbody not found on page");
        return null;
    }

    final List<TrackableLog> trackableLogs = new ArrayList<TrackableLog>();

    final MatcherWrapper trackableMatcher = new MatcherWrapper(GCConstants.PATTERN_TRACKABLE, page);
    while (trackableMatcher.find()) {
        if (trackableMatcher.groupCount() > 0) {

            final String trackCode = trackableMatcher.group(1);
            final String name = Html.fromHtml(trackableMatcher.group(2)).toString();
            try {
                final Integer ctl = Integer.valueOf(trackableMatcher.group(3));
                final Integer id = Integer.valueOf(trackableMatcher.group(5));
                if (trackCode != null && ctl != null && id != null) {
                    final TrackableLog entry = new TrackableLog(trackCode, name, id, ctl);

                    Log.i("Trackable in inventory (#" + entry.ctl + "/" + entry.id + "): " + entry.trackCode
                            + " - " + entry.name);
                    trackableLogs.add(entry);
                }
            } catch (final NumberFormatException e) {
                Log.e("GCParser.parseTrackableLog", e);
            }
        }
    }

    return trackableLogs;
}

From source file:opennlp.tools.parse_thicket.opinion_processor.LinguisticPhraseManager.java

private ParseTreeChunk parseLingPhraseIntoParseTreeChunk(String phrStr) {
    ParseTreeChunk ch = new ParseTreeChunk();
    List<String> POSs = new ArrayList<String>(), lemmas = new ArrayList<String>();

    String[] parts = phrStr.replace("]", "").split(", <");

    ch.setMainPOS(StringUtils.substringBetween(phrStr, ">", "'"));
    try {/*w ww  . j  av a  2s  .c  om*/
        for (String part : parts) {
            String lemma = StringUtils.substringBetween(part, "P'", "':").toLowerCase();
            String pos = part.substring(part.indexOf(":") + 1, part.length());

            if (pos == null || lemma == null) {
                continue;
            }
            POSs.add(pos.trim());
            lemmas.add(lemma.trim());
            ch.setPOSs(POSs);
            ch.setLemmas(lemmas);
        }
    } catch (Exception e) {
        // we expect exceptions if extracted phrases are NEITHER NP nor VP
        // empty chunk will be given which will not create a new topic
        e.printStackTrace();
    }

    return ch;
}

From source file:opennlp.tools.textsimilarity.ParseTreeChunk.java

public ParseTreeChunk(String phrStr) {
    String[] parts = phrStr.replace("]", "").split(", <");
    this.POSs = new ArrayList<String>();
    this.lemmas = new ArrayList<String>();
    this.mainPOS = StringUtils.substringBetween(phrStr, ">", "'");
    for (String part : parts) {
        String lemma = StringUtils.substringBetween(part, "P'", "':");
        String pos = part.substring(part.indexOf(":") + 1, part.length());

        if (pos == null || lemma == null) {
            continue;
        }//  www.  j  ava  2s .  c  o  m
        this.POSs.add(pos.trim());
        this.lemmas.add(lemma.trim());
    }

}

From source file:org.apache.nifi.web.StandardNiFiContentAccess.java

@Override
public DownloadableContent getContent(final ContentRequestContext request) {
    // if clustered, send request to cluster manager
    if (properties.isClustered() && clusterCoordinator != null && clusterCoordinator.isConnected()) {
        // get the URI
        URI dataUri;//from  ww w .  j a v  a  2  s.  co  m
        try {
            dataUri = new URI(request.getDataUri());
        } catch (final URISyntaxException use) {
            throw new ClusterRequestException(use);
        }

        // set the request parameters
        final MultivaluedMap<String, String> parameters = new MultivaluedMapImpl();
        parameters.add(CLIENT_ID_PARAM, request.getClientId());

        // set the headers
        final Map<String, String> headers = new HashMap<>();

        // ensure we were able to detect the cluster node id
        if (request.getClusterNodeId() == null) {
            throw new IllegalArgumentException("Unable to determine the which node has the content.");
        }

        // get the target node and ensure it exists
        final NodeIdentifier nodeId = clusterCoordinator.getNodeIdentifier(request.getClusterNodeId());

        // replicate the request to the cluster coordinator, indicating the target node
        NodeResponse nodeResponse;
        try {
            headers.put(RequestReplicator.REPLICATION_TARGET_NODE_UUID_HEADER, nodeId.getId());
            final NodeIdentifier coordinatorNode = clusterCoordinator.getElectedActiveCoordinatorNode();
            if (coordinatorNode == null) {
                throw new NoClusterCoordinatorException();
            }
            final Set<NodeIdentifier> coordinatorNodes = Collections.singleton(coordinatorNode);
            nodeResponse = requestReplicator
                    .replicate(coordinatorNodes, HttpMethod.GET, dataUri, parameters, headers, false, true)
                    .awaitMergedResponse();
        } catch (InterruptedException e) {
            throw new IllegalClusterStateException("Interrupted while waiting for a response from node");
        }

        final ClientResponse clientResponse = nodeResponse.getClientResponse();
        final MultivaluedMap<String, String> responseHeaders = clientResponse.getHeaders();

        // ensure an appropriate response
        if (Status.NOT_FOUND.getStatusCode() == clientResponse.getStatusInfo().getStatusCode()) {
            throw new ResourceNotFoundException(clientResponse.getEntity(String.class));
        } else if (Status.FORBIDDEN.getStatusCode() == clientResponse.getStatusInfo().getStatusCode()
                || Status.UNAUTHORIZED.getStatusCode() == clientResponse.getStatusInfo().getStatusCode()) {
            throw new AccessDeniedException(clientResponse.getEntity(String.class));
        } else if (Status.OK.getStatusCode() != clientResponse.getStatusInfo().getStatusCode()) {
            throw new IllegalStateException(clientResponse.getEntity(String.class));
        }

        // get the file name
        final String contentDisposition = responseHeaders.getFirst("Content-Disposition");
        final String filename = StringUtils.substringBetween(contentDisposition, "filename=\"", "\"");

        // get the content type
        final String contentType = responseHeaders.getFirst("Content-Type");

        // create the downloadable content
        return new DownloadableContent(filename, contentType, clientResponse.getEntityInputStream());
    } else {
        // example URIs:
        // http://localhost:8080/nifi-api/provenance/events/{id}/content/{input|output}
        // http://localhost:8080/nifi-api/flowfile-queues/{uuid}/flowfiles/{uuid}/content

        // get just the context path for comparison
        final String dataUri = StringUtils.substringAfter(request.getDataUri(), "/nifi-api");
        if (StringUtils.isBlank(dataUri)) {
            throw new IllegalArgumentException("The specified data reference URI is not valid.");
        }

        // flowfile listing content
        final Matcher flowFileMatcher = FLOWFILE_CONTENT_URI_PATTERN.matcher(dataUri);
        if (flowFileMatcher.matches()) {
            final String connectionId = flowFileMatcher.group(1);
            final String flowfileId = flowFileMatcher.group(2);

            return getFlowFileContent(connectionId, flowfileId, dataUri);
        }

        // provenance event content
        final Matcher provenanceMatcher = PROVENANCE_CONTENT_URI_PATTERN.matcher(dataUri);
        if (provenanceMatcher.matches()) {
            try {
                final Long eventId = Long.parseLong(provenanceMatcher.group(1));
                final ContentDirection direction = ContentDirection
                        .valueOf(provenanceMatcher.group(2).toUpperCase());

                return getProvenanceEventContent(eventId, dataUri, direction);
            } catch (final IllegalArgumentException iae) {
                throw new IllegalArgumentException("The specified data reference URI is not valid.");
            }
        }

        // invalid uri
        throw new IllegalArgumentException("The specified data reference URI is not valid.");
    }
}

From source file:org.apache.syncope.core.logic.CamelRouteLogic.java

@PreAuthorize("isAuthenticated()")
public CamelMetrics metrics() {
    CamelMetrics metrics = new CamelMetrics();

    MetricsRegistryService registryService = context.getContext().hasService(MetricsRegistryService.class);
    if (registryService == null) {
        LOG.warn("Camel metrics not available");
    } else {/* www.ja  v  a  2  s  . c  om*/
        MetricRegistry registry = registryService.getMetricsRegistry();
        registry.getTimers().entrySet().stream().map(entry -> {
            CamelMetrics.MeanRate meanRate = new CamelMetrics.MeanRate();
            meanRate.setRouteId(StringUtils.substringBetween(entry.getKey(), ".", "."));
            meanRate.setValue(entry.getValue().getMeanRate());
            return meanRate;
        }).forEachOrdered(meanRate -> {
            metrics.getResponseMeanRates().add(meanRate);
        });

        Collections.sort(metrics.getResponseMeanRates(), (o1, o2) -> Collections
                .reverseOrder(Comparator.<Double>naturalOrder()).compare(o1.getValue(), o2.getValue()));
    }

    return metrics;
}

From source file:org.apache.syncope.core.misc.serialization.AttributeDeserializer.java

@Override
public Attribute deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException {

    ObjectNode tree = jp.readValueAsTree();

    String name = tree.get("name").asText();

    List<Object> values = new ArrayList<Object>();
    for (Iterator<JsonNode> itor = tree.get("value").iterator(); itor.hasNext();) {
        JsonNode node = itor.next();/*ww w . ja  v a2 s  . com*/
        if (node.isNull()) {
            values.add(null);
        } else if (node.isObject()) {
            values.add(((ObjectNode) node).traverse(jp.getCodec()).readValueAs(GuardedString.class));
        } else if (node.isBoolean()) {
            values.add(node.asBoolean());
        } else if (node.isDouble()) {
            values.add(node.asDouble());
        } else if (node.isLong()) {
            values.add(node.asLong());
        } else if (node.isInt()) {
            values.add(node.asInt());
        } else {
            String text = node.asText();
            if (text.startsWith(AttributeSerializer.BYTE_ARRAY_PREFIX)
                    && text.endsWith(AttributeSerializer.BYTE_ARRAY_SUFFIX)) {

                values.add(Base64.decode(StringUtils.substringBetween(text,
                        AttributeSerializer.BYTE_ARRAY_PREFIX, AttributeSerializer.BYTE_ARRAY_SUFFIX)));
            } else {
                values.add(text);
            }
        }
    }

    return Uid.NAME.equals(name)
            ? new Uid(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString())
            : Name.NAME.equals(name)
                    ? new Name(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString())
                    : AttributeBuilder.build(name, values);
}

From source file:org.apache.syncope.core.provisioning.api.serialization.AttributeDeserializer.java

@Override
public Attribute deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException {

    ObjectNode tree = jp.readValueAsTree();

    String name = tree.get("name").asText();

    List<Object> values = new ArrayList<>();
    for (JsonNode node : tree.get("value")) {
        if (node.isNull()) {
            values.add(null);/*www.  ja v  a  2  s . c om*/
        } else if (node.isObject()) {
            values.add(((ObjectNode) node).traverse(jp.getCodec()).readValueAs(GuardedString.class));
        } else if (node.isBoolean()) {
            values.add(node.asBoolean());
        } else if (node.isDouble()) {
            values.add(node.asDouble());
        } else if (node.isLong()) {
            values.add(node.asLong());
        } else if (node.isInt()) {
            values.add(node.asInt());
        } else {
            String text = node.asText();
            if (text.startsWith(AttributeSerializer.BYTE_ARRAY_PREFIX)
                    && text.endsWith(AttributeSerializer.BYTE_ARRAY_SUFFIX)) {

                values.add(Base64.getDecoder().decode(StringUtils.substringBetween(text,
                        AttributeSerializer.BYTE_ARRAY_PREFIX, AttributeSerializer.BYTE_ARRAY_SUFFIX)));
            } else {
                values.add(text);
            }
        }
    }

    return Uid.NAME.equals(name)
            ? new Uid(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString())
            : Name.NAME.equals(name)
                    ? new Name(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString())
                    : AttributeBuilder.build(name, values);
}

From source file:org.apache.syncope.core.util.AttributeDeserializer.java

@Override
public Attribute deserialize(final JsonParser jp, final DeserializationContext ctx)
        throws IOException, JsonProcessingException {

    ObjectNode tree = jp.readValueAsTree();

    String name = tree.get("name").asText();

    List<Object> values = new ArrayList<Object>();
    for (Iterator<JsonNode> itor = tree.get("value").iterator(); itor.hasNext();) {
        JsonNode node = itor.next();//from  ww  w  .  j  av a  2  s  .c  o m
        if (node.isNull()) {
            values.add(null);
        } else if (node.isObject()) {
            values.add(((ObjectNode) node).traverse(jp.getCodec()).readValueAs(GuardedString.class));
        } else if (node.isBoolean()) {
            values.add(node.asBoolean());
        } else if (node.isDouble()) {
            values.add(node.asDouble());
        } else if (node.isLong()) {
            values.add(node.asLong());
        } else if (node.isInt()) {
            values.add(node.asInt());
        } else {
            String text = node.asText();
            if (text.startsWith(AttributeSerializer.BYTE_ARRAY_PREFIX)
                    && text.endsWith(AttributeSerializer.BYTE_ARRAY_SUFFIX)) {

                values.add(Base64.decode(StringUtils.substringBetween(text,
                        AttributeSerializer.BYTE_ARRAY_PREFIX, AttributeSerializer.BYTE_ARRAY_SUFFIX)));
            } else {
                values.add(text);
            }
        }
    }

    return Uid.NAME.equals(name)
            ? new Uid(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString())
            : Name.NAME.equals(name)
                    ? new Name(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString())
                    : AttributeBuilder.build(name, values);
}