Example usage for java.lang StringBuilder replace

List of usage examples for java.lang StringBuilder replace

Introduction

In this page you can find the example usage for java.lang StringBuilder replace.

Prototype

@Override
public StringBuilder replace(int start, int end, String str) 

Source Link

Usage

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.index.lucene.RepositoryAwareADMLuceneSearcherImpl.java

private String parameterise(String unparameterised, Map<QName, QueryParameterDefinition> map,
        QueryParameter[] queryParameters, NamespacePrefixResolver nspr) throws QueryParameterisationException {

    Map<QName, List<Serializable>> valueMap = new HashMap<QName, List<Serializable>>();

    if (queryParameters != null) {
        for (QueryParameter parameter : queryParameters) {
            List<Serializable> list = valueMap.get(parameter.getQName());
            if (list == null) {
                list = new ArrayList<Serializable>();
                valueMap.put(parameter.getQName(), list);
            }//from  w  w  w .  j a  va2 s  .  c om
            list.add(parameter.getValue());
        }
    }

    Map<QName, ListIterator<Serializable>> iteratorMap = new HashMap<QName, ListIterator<Serializable>>();

    List<QName> missing = new ArrayList<QName>(1);
    StringBuilder buffer = new StringBuilder(unparameterised);
    int index = 0;
    while ((index = buffer.indexOf("${", index)) != -1) {
        int endIndex = buffer.indexOf("}", index);
        String qNameString = buffer.substring(index + 2, endIndex);
        QName key = QName.createQName(qNameString, nspr);
        QueryParameterDefinition parameterDefinition = map.get(key);
        if (parameterDefinition == null) {
            missing.add(key);
            buffer.replace(index, endIndex + 1, "");
        } else {
            ListIterator<Serializable> it = iteratorMap.get(key);
            if ((it == null) || (!it.hasNext())) {
                List<Serializable> list = valueMap.get(key);
                if ((list != null) && (list.size() > 0)) {
                    it = list.listIterator();
                }
                if (it != null) {
                    iteratorMap.put(key, it);
                }
            }
            String value;
            if (it == null) {
                value = parameterDefinition.getDefault();
            } else {
                value = DefaultTypeConverter.INSTANCE.convert(String.class, it.next());
            }
            buffer.replace(index, endIndex + 1, value);
        }
    }
    if (missing.size() > 0) {
        StringBuilder error = new StringBuilder();
        error.append("The query uses the following parameters which are not defined: ");
        for (QName qName : missing) {
            error.append(qName);
            error.append(", ");
        }
        error.delete(error.length() - 1, error.length() - 1);
        error.delete(error.length() - 1, error.length() - 1);
        throw new QueryParameterisationException(error.toString());
    }
    return buffer.toString();
}

From source file:org.w3.i18n.I18nTestRunnerTest.java

@Test
public void run() {
    boolean passed;
    StringBuilder testSB = new StringBuilder();

    testSB.append("\nRunning test: '").append(i18nTest.getName()).append("' [").append(i18nTest.getUrl())
            .append("].");

    List<Assertion> expectedAssertions = i18nTest.getExpectedAssertions();

    // Generate a list of assertions using the checker.
    List<Assertion> generatedAssertions = new Check(new ParsedDocument(documentResource)).getAssertions();
    Collections.sort(generatedAssertions);

    // Search for and print the expected assertions.
    int expectedAssertionsFound = 0;
    StringBuilder expectedSB = new StringBuilder("Expected: [");
    for (Assertion expectedAssertion : expectedAssertions) {
        boolean found = false;
        int i = 0;
        while (!found && i < generatedAssertions.size()) {
            if (matches(generatedAssertions.get(i), expectedAssertion)) {
                found = true;// ww w  .j  av  a2  s  .c  o  m
            }
            i++;
        }
        if (found) {
            expectedAssertionsFound++;
        }
        expectedSB.append("[").append(expectedAssertion.getId())
                .append(expectedAssertion.getLevel() == Assertion.Level.MESSAGE ? ""
                        : ", " + expectedAssertion.getLevel())
                .append("] (").append(found ? "found" : "MISSING").append("), ");
    }
    if (!expectedAssertions.isEmpty()) {
        expectedSB.replace(expectedSB.length() - 2, expectedSB.length() - 1, "]");
    } else {
        expectedSB.append("]");
    }
    testSB.append("\n").append(expectedSB);

    // Sort generated assertions in to 3 categories and print.
    // (Expected reports.)
    List<Assertion> gFound = new ArrayList<>();
    // (Unexpected reports.)
    List<Assertion> gRepUnexpected = new ArrayList<>();
    // (Other.)
    List<Assertion> gOther = new ArrayList<>();
    for (Assertion generatedAssertion : generatedAssertions) {
        boolean expected = false;
        int i = 0;
        while (!expected && i < expectedAssertions.size()) {
            if (matches(generatedAssertion, expectedAssertions.get(i))) {
                expected = true;
            }
            i++;
        }
        if (expected) {
            gFound.add(generatedAssertion);
        } else if (generatedAssertion.getId().matches("rep_.*")) {
            gRepUnexpected.add(generatedAssertion);
        } else {
            gOther.add(generatedAssertion);
        }
    }

    testSB.append("\nFound: ").append(toString(gFound)).append("\nUnexpected 'rep': ")
            .append(toString(gRepUnexpected)).append("\nOther: ").append(toString(gOther));

    // Determine result.
    passed = expectedAssertionsFound == i18nTest.getExpectedAssertions().size();

    testSB.append("\nResult: ").append(passed ? "Passed" : "FAILED").append(" (generated: ")
            .append(expectedAssertionsFound).append(" of ").append(expectedAssertions.size())
            .append(" expected, ").append(gRepUnexpected.size()).append(" unexpected 'rep', and ")
            .append(gOther.size()).append(" other).\n");
    if (passed) {
        logger.info(testSB.toString());
    } else {
        fail(testSB.toString());
    }
}

From source file:org.meveo.admin.action.BaseBean.java

/**
 * Generating back link.//w  ww . ja v a 2 s. c  o  m
 */
protected String getListViewName() {
    String className = clazz.getSimpleName();
    StringBuilder sb = new StringBuilder(className);
    char[] dst = new char[1];
    sb.getChars(0, 1, dst, 0);
    sb.replace(0, 1, new String(dst).toLowerCase());
    sb.append("s");
    return sb.toString();
}

From source file:org.ambraproject.search.service.SolrSearchService.java

private SearchResultSinglePage readQueryResults(QueryResponse queryResponse, SolrQuery query) {
    SolrDocumentList documentList = queryResponse.getResults();

    if (log.isInfoEnabled()) {
        StringBuilder filterQueriesForLog = new StringBuilder();
        if (query.getFilterQueries() != null && query.getFilterQueries().length > 0) {
            for (String filterQuery : query.getFilterQueries()) {
                filterQueriesForLog.append(filterQuery).append(" , ");
            }//from  w ww  .j  a  va 2  s. com
            if (filterQueriesForLog.length() > 3) {
                filterQueriesForLog.replace(filterQueriesForLog.length() - 3, filterQueriesForLog.length(), "");
            } else {
                filterQueriesForLog.append("No Filter Queries");
            }
        }

        log.info("query.getQuery():{ " + query.getQuery() + " }" + ", query.getSortFields():{ "
                + (query.getSortFields() == null ? null : Arrays.asList(query.getSortFields())) + " }"
                + ", query.getFilterQueries():{ " + filterQueriesForLog.toString() + " }" + ", found:"
                + documentList.getNumFound() + ", start:" + documentList.getStart() + ", max_score:"
                + documentList.getMaxScore() + ", QTime:" + queryResponse.getQTime() + "ms");

        // TODO: implement spell-checking in a meaningful manner.  This loop exists only to generate log output.
        // TODO: Add "spellcheckAlternatives" or something like it to the SearchHits class so it can be displayed to the user like Google's "did you mean..."
        // TODO: Turn off spellchecking for the "author" field.
        if (queryResponse.getSpellCheckResponse() != null
                && queryResponse.getSpellCheckResponse().getSuggestionMap() != null
                && queryResponse.getSpellCheckResponse().getSuggestionMap().keySet().size() > 0) {
            StringBuilder sb = new StringBuilder("Spellcheck alternative suggestions:");
            for (String token : queryResponse.getSpellCheckResponse().getSuggestionMap().keySet()) {
                sb.append(" { ").append(token).append(" : ");
                if (queryResponse.getSpellCheckResponse().getSuggestionMap().get(token).getAlternatives()
                        .size() < 1) {
                    sb.append("NO ALTERNATIVES");
                } else {
                    for (String alternative : queryResponse.getSpellCheckResponse().getSuggestionMap()
                            .get(token).getAlternatives()) {
                        sb.append(alternative).append(", ");
                    }
                    sb.replace(sb.length() - 2, sb.length(), ""); // Remove last comma and space.
                }
                sb.append(" } ,");
            }
            log.info(sb.replace(sb.length() - 2, sb.length(), "").toString()); // Remove last comma and space.
        } else {
            log.info("Solr thinks everything in the query is spelled correctly.");
        }
    }

    Map<String, Map<String, List<String>>> highlightings = queryResponse.getHighlighting();

    List<SearchHit> searchResults = new ArrayList<SearchHit>();
    for (SolrDocument document : documentList) {

        String id = getFieldValue(document, "id", String.class, query.toString());
        String message = id == null ? query.toString() : id;
        Float score = getFieldValue(document, "score", Float.class, message);
        String title = getFieldValue(document, "title_display", String.class, message);
        Date publicationDate = getFieldValue(document, "publication_date", Date.class, message);
        String eissn = getFieldValue(document, "eissn", String.class, message);
        String journal = getFieldValue(document, "journal", String.class, message);
        String articleType = getFieldValue(document, "article_type", String.class, message);

        List<String> authorList = getFieldMultiValue(document, message, String.class, "author_display");

        String highlights = null;
        if (query.getHighlight()) {
            highlights = getHighlights(highlightings.get(id));
        }

        SearchHit hit = new SearchHit(score, id, title, highlights, authorList, publicationDate, eissn, journal,
                articleType);

        if (log.isDebugEnabled())
            log.debug(hit.toString());

        searchResults.add(hit);
    }

    //here we assume that number of hits is always going to be withing range of int
    SearchResultSinglePage results = new SearchResultSinglePage((int) documentList.getNumFound(), -1,
            searchResults, query.getQuery());

    if (queryResponse.getFacetField("subject_facet") != null) {
        results.setSubjectFacet(facetCountsToHashMap(queryResponse.getFacetField("subject_facet")));
    }

    if (queryResponse.getFacetField("author_facet") != null) {
        results.setAuthorFacet(facetCountsToHashMap(queryResponse.getFacetField("author_facet")));
    }

    if (queryResponse.getFacetField("editor_facet") != null) {
        results.setEditorFacet(facetCountsToHashMap(queryResponse.getFacetField("editor_facet")));
    }

    if (queryResponse.getFacetField("article_type_facet") != null) {
        results.setArticleTypeFacet(facetCountsToHashMap(queryResponse.getFacetField("article_type_facet")));
    }

    if (queryResponse.getFacetField("affiliate_facet") != null) {
        results.setInstitutionFacet(facetCountsToHashMap(queryResponse.getFacetField("affiliate_facet")));
    }

    if (queryResponse.getFacetField("cross_published_journal_key") != null) {
        results.setJournalFacet(
                facetCountsToHashMap(queryResponse.getFacetField("cross_published_journal_key")));
    }

    return results;
}

From source file:org.wso2.carbon.identity.authenticator.inbound.saml2sso.test.SPInitTests.java

/**
 * Test inbound authentication with redirect binding with invalid signature algorithm parameter.
 *//* w  w w .  java  2 s  .  c  o  m*/
@Test
public void testAuthnRequestSignatureValidationWithInvalidSigAlgForRedirect() {

    ServiceProviderConfig serviceProviderConfig = TestUtils
            .getServiceProviderConfigs(TestConstants.SAMPLE_ISSUER_NAME, bundleContext);
    serviceProviderConfig.getRequestValidationConfig().getRequestValidatorConfigs().get(0).getProperties()
            .setProperty(SAML2AuthConstants.Config.Name.AUTHN_REQUEST_SIGNED, "true");
    try {
        AuthnRequest samlRequest = TestUtils.buildAuthnRequest("https://localhost:9292/gateway", false, false,
                TestConstants.SAMPLE_ISSUER_NAME, TestConstants.ACS_URL);
        String samlRequestString = SAML2AuthUtils.encodeForRedirect(samlRequest);

        StringBuilder httpQueryString = new StringBuilder(
                SAML2AuthConstants.SAML_REQUEST + "=" + samlRequestString);
        httpQueryString.append("&" + SAML2AuthConstants.RELAY_STATE + "="
                + URLEncoder.encode("relayState", StandardCharsets.UTF_8.name()).trim());
        SAML2AuthUtils.addSignatureToHTTPQueryString(httpQueryString,
                "http://www.w3.org/2000/09/xmldsig#rsa-sha1", SAML2AuthUtils.getServerCredentials());

        httpQueryString.replace(httpQueryString.indexOf("SigAlg=") + 7, httpQueryString.indexOf("&Signature="),
                "sig_alg");
        HttpURLConnection urlConnection = TestUtils.request(
                TestConstants.GATEWAY_ENDPOINT + "?" + httpQueryString.toString(), HttpMethod.GET, false);
        String postBody = TestUtils.getContent(urlConnection);
        //          Relay state must be returned for error scenarios as well
        //          Assert.assertTrue(postBody.contains(TestConstants.RELAY_STATE));

        Assert.assertEquals(urlConnection.getResponseCode(), 200);
        Assert.assertNotNull(postBody);
        String samlResponse = postBody.split("SAMLResponse' value='")[1].split("'>")[0];
        Response samlResponseObject = TestUtils.getSAMLResponse(samlResponse);
        Assert.assertEquals(samlResponseObject.getAssertions().size(), 0);

    } catch (IOException e) {
        Assert.fail("Error while running testSAMLInboundAuthentication test case", e);
    } catch (SAML2SSOServerException e) {
        Assert.fail("Error while building response object", e);
    } finally {
        serviceProviderConfig.getRequestValidationConfig().getRequestValidatorConfigs().get(0).getProperties()
                .setProperty(SAML2AuthConstants.Config.Name.AUTHN_REQUEST_SIGNED, "false");
    }
}

From source file:org.ambraproject.service.search.SolrSearchService.java

private String createFilterLimitForAuthor(String[] authors) {
    Arrays.sort(authors); // Consistent order so that each filter will only be cached once.
    StringBuilder fq = new StringBuilder();
    for (String author : authors) {
        fq.append("author:\"").append(author).append("\" AND ");
    }//from www  .  j a va2s.  c o  m
    return fq.replace(fq.length() - 5, fq.length(), "").toString(); // Remove last " AND".
}

From source file:org.ambraproject.service.search.SolrSearchService.java

private String createFilterLimitForSubjectDisjunction(String[] subjects) {
    Arrays.sort(subjects); // Consistent order so that each filter will only be cached once.
    StringBuilder fq = new StringBuilder();
    for (String category : subjects) {
        fq.append("subject:\"").append(category).append("\" OR ");
    }//ww w. j ava 2  s.c o  m
    return fq.replace(fq.length() - 4, fq.length(), "").toString(); // Remove last " OR".
}

From source file:org.ambraproject.service.search.SolrSearchService.java

private String createFilterLimitForSubject(String[] subjects) {
    Arrays.sort(subjects); // Consistent order so that each filter will only be cached once.
    StringBuilder fq = new StringBuilder();
    for (String category : subjects) {
        fq.append("subject:\"").append(category).append("\" AND ");
    }/*from w  ww  . j  a v a2s .c o m*/
    return fq.replace(fq.length() - 5, fq.length(), "").toString(); // Remove last " AND".
}

From source file:org.jumpmind.db.platform.AbstractDatabasePlatform.java

public void alterTables(boolean continueOnError, Table... desiredTables) {
    Database currentDatabase = new Database();
    Database desiredDatabase = new Database();
    StringBuilder tablesProcessed = new StringBuilder();
    for (Table table : desiredTables) {
        tablesProcessed.append(table.getFullyQualifiedTableName());
        tablesProcessed.append(", ");
        desiredDatabase.addTable(table);
        Table currentTable = ddlReader.readTable(table.getCatalog(), table.getSchema(), table.getName());
        if (currentTable != null) {
            currentDatabase.addTable(currentTable);
        }//from  ww w .  ja v a  2  s.co  m
    }

    if (tablesProcessed.length() > 1) {
        tablesProcessed.replace(tablesProcessed.length() - 2, tablesProcessed.length(), "");
    }

    String alterSql = ddlBuilder.alterDatabase(currentDatabase, desiredDatabase);

    if (StringUtils.isNotBlank(alterSql.trim())) {
        log.info("Running alter sql:\n{}", alterSql);
        String delimiter = getDdlBuilder().getDatabaseInfo().getSqlCommandDelimiter();
        new SqlScript(alterSql, getSqlTemplate(), !continueOnError, false, false, delimiter, null)
                .execute(getDatabaseInfo().isRequiresAutoCommitForDdl());
    } else {
        log.info("Tables up to date.  No alters found for {}", tablesProcessed);
    }

}

From source file:org.meveo.admin.action.BaseBean.java

public String getIdParameterName() {
    String className = clazz.getSimpleName();
    StringBuilder sb = new StringBuilder(className);
    sb.append("Id");
    char[] dst = new char[1];
    sb.getChars(0, 1, dst, 0);/*w  w w. j  a v  a  2 s. c  om*/
    sb.replace(0, 1, new String(dst).toLowerCase());
    return sb.toString();
}