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:org.apereo.openlrs.model.event.EventConversionService.java

private String parseActorXApi(Statement xapi) {
    String actor = null;/*from   ww w . j  a v  a  2s.c o m*/

    XApiActor xApiActor = xapi.getActor();
    if (xApiActor != null) {
        String mbox = xApiActor.getMbox();
        if (StringUtils.isNotBlank(mbox)) {
            actor = StringUtils.substringBetween(mbox, "mailto:", "@");
        }
    }

    return actor;
}

From source file:org.apereo.openlrs.repositories.statements.ElasticSearchStatementRepository.java

private StatementMetadata extractMetadata(Statement statement) {
    StatementMetadata statementMetadata = new StatementMetadata();
    statementMetadata.setId(UUID.randomUUID().toString());
    statementMetadata.setStatementId(statement.getId());

    XApiContext xApiContext = statement.getContext();
    if (xApiContext != null) {
        XApiContextActivities xApiContextActivities = xApiContext.getContextActivities();
        if (xApiContextActivities != null) {
            List<XApiObject> parentContext = xApiContextActivities.getParent();
            if (parentContext != null && !parentContext.isEmpty()) {
                for (XApiObject object : parentContext) {
                    String id = object.getId();
                    if (StringUtils.contains(id, "portal/site/")) {
                        statementMetadata.setContext(StringUtils.substringAfterLast(id, "/"));
                    }/*from ww  w .  j a va2  s.  co  m*/
                }
            }
        }
    }

    XApiActor xApiActor = statement.getActor();
    if (xApiActor != null) {
        String mbox = xApiActor.getMbox();
        if (StringUtils.isNotBlank(mbox)) {
            statementMetadata.setUser(StringUtils.substringBetween(mbox, "mailto:", "@"));
        }
    }

    return statementMetadata;
}

From source file:org.debux.webmotion.test.ExtrasMiscIT.java

@Test
public void noteCreate() throws IOException, URISyntaxException {
    Request request = createRequest("/note/create").addParameter("content", "test").Get();

    String result = executeRequest(request);
    AssertJUnit.assertTrue(result, result.contains("test"));

    String id = StringUtils.substringBetween(result, "?id=", "\"");
    request = createRequest("/note/incLike").addParameter("id", id).Get();

    result = executeRequest(request);/*  ww  w . j  a v  a 2 s  .co m*/
    AssertJUnit.assertTrue(result, result.contains("<td>1</td>"));

    request = createRequest("/note/delete").addParameter("id", id).Get();

    result = executeRequest(request);
    AssertJUnit.assertFalse(result, result.contains(id));
}

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

/**
 * Test the new escapeXml tag attribute.
 *
 * @throws Exception any axception thrown during test.
 *//*ww  w  . j a  v a 2  s .com*/
@Override
@Test
public void doTest() throws Exception {
    WebRequest request = new GetMethodWebRequest(getJspUrl(getJspName()));
    WebResponse response = this.runner.getResponse(request);

    ParamEncoder encoder = new ParamEncoder("table");
    request.setParameter(encoder.encodeParameterName(TableTagParameters.PARAMETER_PAGE), "2");

    if (this.log.isDebugEnabled()) {
        this.log.debug(response.getText());
    }

    WebTable[] tables = response.getTables();
    Assert.assertEquals("Wrong number of tables in result.", 1, tables.length);
    Assert.assertEquals("Wrong number of rows in result.", 2, tables[0].getRowCount());

    if (this.log.isDebugEnabled()) {
        this.log.debug(response.getText());
    }
    this.log.warn(response.getText());

    // note: getCellAsText returns the unescaped value
    String escapedtext = StringUtils.substringBetween(response.getText(), "<td>", "</td>");

    Assert.assertEquals("Wrong column content.", "&lt;strong&gt;&amp;&lt;/strong&gt;", escapedtext);
}

From source file:org.eclipse.jdt.internal.junit.ui.BugTrace.java

public BugTrace(Composite parent, final TestRunnerViewPart testRunnerPart) {
    this.fTestRunnerPart = testRunnerPart;
    try {//  w w  w  .j a va 2s.  c  o  m
        fFormattedMessage = new Browser(parent, SWT.WRAP);
        fFormattedMessage.setFont(parent.getFont());
        fFormattedMessage.addLocationListener(new LocationAdapter() {
            @Override
            public void changing(LocationEvent event) {
                if (fFormattedMessage.isDisposed())
                    return;

                if (event.location.contains("openTest#")) { //$NON-NLS-1$
                    String testHash = StringUtils.substringBetween(event.location, "openTest#", "?"); //$NON-NLS-1$//$NON-NLS-2$
                    openTest(testHash);
                    event.doit = false;
                } else
                    event.doit = true;
            }

        });
    } catch (SWTError e) {
        //browser is not available
        fFormattedMessage = null;
    }

}

From source file:org.eclipse.jdt.internal.junit.ui.BugTrace.java

/**
 * Generate a simple message for an unknown error
 * /*from w  w  w .  jav  a  2 s.co m*/
 * @param test element
 * @return HTML string
 */
private String getUknownError(ITestElement test) {
    StringBuilder b = new StringBuilder();
    b.append("<td></td><td class='err'>"); //$NON-NLS-1$
    if (test.getFailureTrace() != null && test.getFailureTrace().getTrace() != null) {
        b.append(StringUtils.substringBetween(test.getFailureTrace().getTrace(), ":", "at")); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        b.append(test);
    }
    b.append("</td>"); //$NON-NLS-1$
    return b.toString();
}

From source file:org.eclipse.jdt.internal.junit.ui.TestRunnerViewPart.java

@Override
public void saveState(IMemento memento) {
    if (fSashForm == null) {
        // part has not been created
        if (fMemento != null) //Keep the old state;
            memento.putMemento(fMemento);
        return;/*from   w  w w. ja  v  a 2  s .c o m*/
    }

    //      int activePage= fTabFolder.getSelectionIndex();
    //      memento.putInteger(TAG_PAGE, activePage);
    memento.putString(TAG_SCROLL, fScrollLockAction.isChecked() ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$
    memento.putString(TAG_WEIGTHS, StringUtils.substringBetween(fSashForm.getWeights().toString(), "[", "]")); //$NON-NLS-1$//$NON-NLS-2$
    memento.putString(TAG_WEIGTHS + "2", //$NON-NLS-1$
            StringUtils.substringBetween(fSashFormFailureReason.getWeights().toString(), "[", "]")); //$NON-NLS-1$ //$NON-NLS-2$
    memento.putInteger(TAG_ORIENTATION, fOrientation);

    memento.putString(TAG_FAILURES_ONLY, fFailuresOnlyFilterAction.isChecked() ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$
    memento.putString(TAG_IGNORED_ONLY, fIgnoredOnlyFilterAction.isChecked() ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$
    memento.putInteger(TAG_LAYOUT, fLayout);
    memento.putString(TAG_SHOW_TIME, fShowTimeAction.isChecked() ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$
    memento.putBoolean(TAG_SHOW_BUGTRACE, fShowBugTrace.isChecked());
    memento.putBoolean(TAG_SHOW_STACKTRACE, fShowFailureTrace.isChecked());
    memento.putBoolean(TAG_SHOW_AUTOMATIC_REASON, fShowAutomaticFailureWidget.isChecked());
}

From source file:org.gbif.ipt.action.manage.MetadataAction.java

@Override
public void prepare() {
    super.prepare();
    // somehow the action params in struts.xml dont seem to work right
    // we therefore take the section parameter from the requested url
    section = StringUtils.substringBetween(req.getRequestURI(), "metadata-", ".");
    int idx = SECTIONS.indexOf(section);
    if (idx < 0 || idx == SECTIONS.size()) {
        idx = 0;/*w  w  w.  j  a v  a 2  s  . c om*/
    }
    next = idx + 1 < SECTIONS.size() ? SECTIONS.get(idx + 1) : SECTIONS.get(0);

    // licenses - Additional Metadata Page
    licenses = new LinkedHashMap<String, String>();
    licenses.put(getText("eml.intellectualRights.nolicenses"), "");
    //licenses.put(getText("eml.intellectualRights.license.i2d"), getText("eml.intellectualRights.license.i2d.text"));
    licenses.put(getText("eml.intellectualRights.license.i2d"), "");
    //licenses.put(getText("eml.intellectualRights.license.cczero"), getText("eml.intellectualRights.license.cczero.text"));
    //licenses.put(getText("eml.intellectualRights.license.pddl"), getText("eml.intellectualRights.license.pddl.text"));
    //licenses.put(getText("eml.intellectualRights.license.odcby"), getText("eml.intellectualRights.license.odcby.text"));
    //licenses.put(getText("eml.intellectualRights.license.odbl"), getText("eml.intellectualRights.license.odbl.text"));

    // Dataset core type list, derived from XML vocabulary, and displayed in drop-down on Basic Metadata page
    types = new LinkedHashMap<String, String>();
    types.put("", getText("resource.coreType.selection"));
    types.putAll(vocabManager.getI18nVocab(Constants.VOCAB_URI_DATASET_TYPE, getLocaleLanguage(), false));
    // convert all keys in Map to lowercase, in order to standardize keys across different versions of the IPT, as well
    // as to facilitate grouping of subtypes, please see groupDatasetSubtypes()
    types = MapUtils.getMapWithLowercaseKeys(types);

    // languages list, derived from XML vocabulary, and displayed in drop-down on Basic Metadata page
    languages = vocabManager.getI18nVocab(Constants.VOCAB_URI_LANGUAGE, getLocaleLanguage(), true);

    // countries list, derived from XML vocabulary, and displayed in drop-down where new contacts are created
    countries = new LinkedHashMap<String, String>();
    countries.put("", getText("eml.country.selection"));
    countries.putAll(vocabManager.getI18nVocab(Constants.VOCAB_URI_COUNTRY, getLocaleLanguage(), true));

    // ranks list, derived from XML vocabulary, and displayed on Taxonomic Coverage Page
    ranks = new LinkedHashMap<String, String>();
    ranks.put("", getText("eml.rank.selection"));
    ranks.putAll(vocabManager.getI18nVocab(Constants.VOCAB_URI_RANKS, getLocaleLanguage(), false));

    // roles list, derived from XML vocabulary, and displayed in drop-down where new contacts are created
    roles = new LinkedHashMap<String, String>();
    roles.put("", getText("eml.agent.role.selection"));
    roles.putAll(vocabManager.getI18nVocab(Constants.VOCAB_URI_ROLES, getLocaleLanguage(), false));

    // Dataset Subtypes list, derived from XML vocabulary, and displayed in drop-down on Basic Metadata page
    datasetSubtypes = new LinkedHashMap<String, String>();
    datasetSubtypes.put("", getText("resource.subtype.selection"));
    datasetSubtypes.putAll(
            vocabManager.getI18nVocab(Constants.VOCAB_URI_DATASET_SUBTYPES, getLocaleLanguage(), false));
    // convert all keys in Map to lowercase, in order to standardize keys across different versions of the IPT, as well
    // as to facilitate grouping of subtypes, please see groupDatasetSubtypes()
    datasetSubtypes = MapUtils.getMapWithLowercaseKeys(datasetSubtypes);
    // group subtypes into Checklist and Occurrence - used for getOccurrenceSubtypeKeys() and getChecklistSubtypeKeys()
    groupDatasetSubtypes();

    // preservation methods list, derived from XML vocabulary, and displayed in drop-down on Collections Data Page.
    preservationMethods = new LinkedHashMap<String, String>();
    preservationMethods.put("", getText("eml.preservation.methods.selection"));
    preservationMethods.putAll(
            vocabManager.getI18nVocab(Constants.VOCAB_URI_PRESERVATION_METHOD, getLocaleLanguage(), false));

    // update frequencies list, derived from XML vocabulary, and displayed in drop-down on basic metadata page
    frequencies = new LinkedHashMap<String, String>();
    frequencies.put("", getText("resource.updateFrequency.selection"));
    frequencies.putAll(
            vocabManager.getI18nVocab(Constants.VOCAB_URI_UPDATE_FREQUENCIES, getLocaleLanguage(), false));

    if (resource != null && resource.getEml() != null) {
        // contact
        Agent contact = resource.getEml().getContact();
        if (contact != null) {
            String countryValue = contact.getAddress().getCountry();
            if (countryValue != null) {
                ParseResult<Country> result = COUNTRY_PARSER.parse(countryValue);
                if (result.isSuccessful()) {
                    contact.getAddress().setCountry(result.getPayload().getIso2LetterCode());
                }
            }
        }
        // creator
        Agent creator = resource.getEml().resourceCreator();
        if (creator != null) {
            String countryValue = creator.getAddress().getCountry();
            if (countryValue != null) {
                ParseResult<Country> result = COUNTRY_PARSER.parse(countryValue);
                creator.getAddress().setCountry(result.getPayload().getIso2LetterCode());
            }
        }

        // metadata provider
        Agent metadataProvider = resource.getEml().getMetadataProvider();

        // create Agent equal to current user
        Agent current = new Agent();
        current.setFirstName(getCurrentUser().getFirstname());
        current.setLastName(getCurrentUser().getLastname());
        current.setEmail(getCurrentUser().getEmail());

        if (!isAgentWithoutRoleEmpty(metadataProvider)) {
            String countryValue = metadataProvider.getAddress().getCountry();
            if (countryValue != null) {
                ParseResult<Country> result = COUNTRY_PARSER.parse(countryValue);
                metadataProvider.getAddress().setCountry(result.getPayload().getIso2LetterCode());
            }
        } else {
            // auto populate with current user
            resource.getEml().setMetadataProvider(current);
        }

        // auto populate user with current user if associated parties list is empty, and eml.xml hasn't been written yet
        if (!resourceManager.isEmlExisting(resource.getShortname())
                && resource.getEml().getAssociatedParties().isEmpty()) {
            current.setRole("user");
            resource.getEml().getAssociatedParties().add(current);
        }
        // otherwise, ensure associated parties' country value get converted into 2 letter iso code for proper display
        else if (!resource.getEml().getAssociatedParties().isEmpty()) {
            for (Agent party : resource.getEml().getAssociatedParties()) {
                String countryValue = party.getAddress().getCountry();
                if (countryValue != null) {
                    ParseResult<Country> result = COUNTRY_PARSER.parse(countryValue);
                    if (result.isSuccessful()) {
                        party.getAddress().setCountry(result.getPayload().getIso2LetterCode());
                    }
                }
            }
        }

        // if it is a submission of the taxonomic coverage, clear the session list
        if (isHttpPost()) {
            if ("parties".equals(section)) {
                resource.getEml().getAssociatedParties().clear();
            }
            if ("geocoverage".equals(section)) {
                resource.getEml().getGeospatialCoverages().clear();
            }
            if ("taxcoverage".equals(section)) {
                resource.getEml().getTaxonomicCoverages().clear();
            }
            if ("tempcoverage".equals(section)) {
                resource.getEml().getTemporalCoverages().clear();
            }
            if ("methods".equals(section)) {
                resource.getEml().getMethodSteps().clear();
            }
            if ("citations".equals(section)) {
                resource.getEml().getBibliographicCitationSet().getBibliographicCitations().clear();
            }
            if ("physical".equals(section)) {
                resource.getEml().getPhysicalData().clear();
            }
            if ("keywords".equals(section)) {
                resource.getEml().getKeywords().clear();
            }
            if ("collections".equals(section)) {
                resource.getEml().getJgtiCuratorialUnits().clear();
            }
            if ("additional".equals(section)) {
                resource.getEml().getAlternateIdentifiers().clear();
            }
        }
    }
}

From source file:org.goko.controller.grbl.v08.GrblCommunicator.java

/**
 * Handling of incoming data//from  www .  ja  va  2  s . com
 * @param data the received data
 * @throws GkException GkException
 */
protected void handleIncomingData(String data) throws GkException {
    String trimmedData = StringUtils.trim(data);
    if (StringUtils.isNotEmpty(trimmedData)) {
        /* Received OK response */
        if (StringUtils.equals(trimmedData, Grbl.OK_RESPONSE)) {
            grbl.handleOkResponse();

            /* Received error  */
        } else if (StringUtils.startsWith(trimmedData, "error:")) {
            grbl.handleError(trimmedData);

            /* Received status report  */
        } else if (StringUtils.startsWith(trimmedData, "<") && StringUtils.endsWith(trimmedData, ">")) {
            grbl.handleStatusReport(parseStatusReport(trimmedData));

            /* Received Grbl header */
        } else if (StringUtils.startsWith(trimmedData, "Grbl")) {
            handleHeader(trimmedData);
            grbl.initialiseConnectedState();
            //   refreshStatus();

            /* Received a configuration confirmation */
        } else if (StringUtils.defaultString(trimmedData).matches("\\$[0-9]*=.*")) {
            grbl.handleConfigurationReading(trimmedData);

            /* Received a work position report */
        } else if (StringUtils.defaultString(trimmedData).matches("\\[G5.*\\]")) {
            Tuple6b targetPoint = new Tuple6b().setNull();
            String offsetName = parseCoordinateSystem(trimmedData, targetPoint);
            grbl.setOffsetCoordinate(offsetName, targetPoint);

            /* Received an offset position report */
        } else if (StringUtils.defaultString(trimmedData).matches("\\[(G92|G28|G30).*\\]")) {
            //            Tuple6b targetPoint = new Tuple6b().setNull();
            //            String coordinateSystemName = parseCoordinateSystem(trimmedData, targetPoint);
            //            grbl.setOffsetCoordinate(coordinateSystemName, targetPoint);
            // TODO Handle G92
            /* Parser state report */
        } else if (StringUtils.defaultString(trimmedData).matches("\\[(G0|G1|G2|G3).*\\]")) {
            grbl.receiveParserState(StringUtils.substringBetween(trimmedData, "[", "]"));
            /* Unkown format received */
        } else {
            LOG.error("Ignoring received data " + trimmedData);
            grbl.getApplicativeLogService().warning("Ignoring received data " + trimmedData,
                    GrblControllerService.SERVICE_ID);
        }
    }
}

From source file:org.goko.controller.grbl.v08.GrblCommunicator.java

/**
 * Create a status report from the given string
 * @param strStatusReport the String representing the status report
 * @return {@link StatusReport}//from www. j a v  a  2s  .  c o  m
 * @throws GkException
 */
private StatusReport parseStatusReport(String strStatusReport) throws GkException {
    StatusReport result = new StatusReport();
    int comma = StringUtils.indexOf(strStatusReport, ",");
    String state = StringUtils.substring(strStatusReport, 1, comma);
    GrblMachineState grblState = grbl.getGrblStateFromString(state);
    result.setState(grblState);

    // Looking for MPosition
    String mpos = StringUtils.substringBetween(strStatusReport, "MPos:", ",WPos");
    String wpos = StringUtils.substringBetween(strStatusReport, "WPos:", ">");
    Tuple6b machinePosition = new Tuple6b().setNull();
    Tuple6b workPosition = new Tuple6b().setNull();
    String[] machineCoordinates = StringUtils.split(mpos, ",");

    parseTuple(machineCoordinates, machinePosition);
    result.setMachinePosition(machinePosition);

    String[] workCoordinates = StringUtils.split(wpos, ",");
    parseTuple(workCoordinates, workPosition);
    result.setWorkPosition(workPosition);

    return result;
}