Example usage for java.lang StringBuilder indexOf

List of usage examples for java.lang StringBuilder indexOf

Introduction

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

Prototype

@Override
    public int indexOf(String str) 

Source Link

Usage

From source file:fr.landel.utils.scripts.ScriptsReplacer.java

private void clearUnknownSimples(final StringBuilder sb) {
    String simple;/*from   w w  w  . ja v a 2  s .c om*/
    int indexValid;
    int indexDefault;

    final int startLen = this.template.getVariableOpen().length();
    final int stopLen = this.template.getVariableClose().length();

    // get first
    int index = sb.indexOf(this.template.getVariableOpen());
    int indexStop = sb.indexOf(this.template.getVariableClose(), index + startLen);

    for (; index > -1 && indexStop > -1;) {
        simple = sb.substring(index + startLen, indexStop);

        indexValid = simple.indexOf(this.template.getOperatorThen());
        indexDefault = simple.indexOf(this.template.getOperatorElse());

        if (indexValid == -1 && indexDefault == -1) {
            sb.replace(index, indexStop + stopLen, "");
        }

        // get next
        index = sb.indexOf(this.template.getVariableOpen(), index + 1);
        if (index > -1) {
            indexStop = sb.indexOf(this.template.getVariableClose(), index + startLen);
        }
    }
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

public StringBuilder normalizeKommataString(StringBuilder pKommataStr) {
    if ((pKommataStr != null) && (pKommataStr.length() > 0)) {
        if (pKommataStr.indexOf(",") > 0) {
            String[] vStrLst = pKommataStr.toString().split(",");
            pKommataStr.delete(0, pKommataStr.length());
            for (int i = 0; i < vStrLst.length; i++) {
                if (pKommataStr.length() > 0) {
                    pKommataStr.append(",");
                }/*w w  w  .j a va2  s  .  c o  m*/
                pKommataStr.append(vStrLst[i].trim());
            }
        }
    }
    return pKommataStr;
}

From source file:org.shredzone.commons.view.manager.ViewPattern.java

/**
 * Evaluates the given {@link EvaluationContext} and builds an URL to the appropriate
 * view./*from  w  w  w  .  j a v  a2 s . co m*/
 *
 * @param context
 *            {@link EvaluationContext} to be used
 * @param data
 *            {@link PathContext} containing all data required for building the URL
 * @return URL that was built, or {@code null} if the {@link PathContext} did not
 *         contain all necessary data for building the URL
 */
public String evaluate(EvaluationContext context, PathContext data) {
    StringBuilder sb = new StringBuilder();
    for (Expression expr : expression) {
        String value = expr.getValue(context, data, String.class);
        if (value == null) {
            // A part resolved to null, so this ViewPattern is unable
            // to build a path from the given PathData.
            return null;
        }
        sb.append(value);
    }

    // Remove ugly double slashes
    int pos;
    while ((pos = sb.indexOf("//")) >= 0) {
        sb.deleteCharAt(pos);
    }

    return sb.toString();
}

From source file:com.nadmm.airports.notams.NotamService.java

private ArrayList<String> parseNotamsFromHtml(InputStream in) throws IOException {
    ArrayList<String> notams = new ArrayList<>();

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

    String line;/*  ww  w  .  j a  v a2s .c  o  m*/
    boolean inside = false;
    StringBuilder builder = null;
    while ((line = reader.readLine()) != null) {
        if (!inside) {
            // Inspect the contents of all <pre> tags to find NOTAMs
            if (line.toUpperCase(Locale.US).contains("<PRE>")) {
                builder = new StringBuilder();
                inside = true;
            }
        }
        if (inside) {
            builder.append(line);
            builder.append(" ");
            if (line.toUpperCase(Locale.US).contains("</PRE>")) {
                inside = false;
                int start = builder.indexOf("!");
                if (start >= 0) {
                    // Now get the actual inner contents
                    int end = builder.indexOf("SOURCE:");
                    String notam = builder.substring(start, end).trim();
                    // Normalize the whitespaces
                    //notam = whitespaces.matcher( notam ).replaceAll( " " );
                    notams.add(notam);
                }
            }
        }
    }

    return notams;
}

From source file:org.icefaces.samples.showcase.util.SourceCodeLoaderConnection.java

/**
 * Returns formatted source located in the cache, or adds to the cache and
 * returns the source found at sourceCodePath, removing oldest cached files
 * if MAX_CACHE_SIZE exceeded.           
 * //from  w w  w  . j  av  a  2 s  .  co  m
 * Implementing the map interface method `get` to allow parameter passing 
 * in EL versions prior to 2.0
 *
 * @param sourceCodePathObj The String location of the source file relative
 * to the web application root.
 * @return The XHTML formatted source code or a stack trace if the URL 
 * could not be UTF-8 encoded.
 */
public String get(Object sourceCodePathObj) {
    if (SOURCE_SERVLET_URL == null || MAX_CACHE_SIZE == null || !(sourceCodePathObj instanceof String)) {
        return null;
    }

    String sourceCodePath;
    // Try encoding sourceCodePathObj parameter, return a stack trace
    // instead of source if it fails.
    try {
        sourceCodePath = URLEncoder.encode((String) sourceCodePathObj, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        logger.severe("UTF-8 is not supported by this platform.");
        return "";
    }

    CachedSource cs;
    // Only allow the cache to be accessed by a single user when being used
    // within one of these blocks.   
    synchronized (cache) {
        // Search the cache for formatted source code from this path. If it is 
        // found, update the formatted source code with the current timestamp 
        // and return the cached source.  
        if ((cs = (CachedSource) cache.get(sourceCodePath)) != null) {
            logger.finer("Source Cache Hit.");
            logger.finest("Hit: " + sourceCodePath);
            cs.timestamp = System.currentTimeMillis() / 1000;
            cache.put(cs.path, cs);
            return cs.source;
        }
    }

    logger.finer("Source Cache Miss.");
    logger.finest("Miss: " + sourceCodePath);

    URL servletUrl = null;
    InputStream inputStream = null;
    InputStreamReader inputReader = null;
    try {
        if (!IS_SECURE) {
            servletUrl = new URL(SOURCE_SERVLET_URL + sourceCodePath);
            inputStream = (InputStream) servletUrl.getContent();
        } else {
            // don't use a connection, just access methods directly
            inputStream = SourceCodeLoaderServlet.getServlet().getSource((String) sourceCodePathObj);
        }

        brokenUrl = false;
    } catch (Exception e) {
        e.printStackTrace();
        logger.severe(
                "Broken URL for the source code loader (" + SOURCE_SERVLET_URL + "), check your web.xml.");
        brokenUrl = true;
    }

    if (!brokenUrl) {
        try {
            // Set up streams and buffers for source servlet reading
            inputReader = new InputStreamReader(inputStream, "UTF-8");
            StringBuilder buf = new StringBuilder(16384);

            // Read into stringBuilder until EOF
            int readChar;
            while ((readChar = inputReader.read()) != -1) {
                buf.append((char) readChar);
            }

            // Extract page content from <body> tag and fix nbsp for valid XHTML
            String ret = buf.indexOf("&nbsp;") != -1
                    ? buf.substring(buf.indexOf("<body>") + 6, buf.lastIndexOf("</body>")).replace("&nbsp;",
                            "&#160;")
                    : buf.toString();

            synchronized (cache) {
                // If cache is full, remove files until the newly loaded string
                // will fit and add it to the cache
                while ((ret.length() * 16) + cacheSize > MAX_CACHE_SIZE) {
                    OrderedBidiMap iCache = cache.inverseOrderedBidiMap();
                    CachedSource c = (CachedSource) iCache.firstKey();
                    cache.remove(c.path);
                    cacheSize -= c.source.length() * 16;
                    logger.finer("Cache Oversized. Removing oldest file.");
                    logger.finest("Removed: " + c.path);
                }
                cache.put(sourceCodePath, new CachedSource(sourceCodePath, ret));
                cacheSize += ret.length() * 16;
            }

            // Return newly loaded and cached source
            return ret;
        } catch (MalformedURLException e) {
            logger.severe("Attempted to connect to malformed URL.");
            logger.severe("Likely either EL param or web.xml SOURCE_SERVLET_URL param is incorrectly set");
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            logger.severe("UTF-8 is not supported by this platform.");
            e.printStackTrace();
        } catch (IOException e) {
            logger.severe("IOException raised while reading characters from Servlet response stream.");
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception ignoredClose) {
                }
            }
            if (inputReader != null) {
                try {
                    inputReader.close();
                } catch (Exception ignoredClose) {
                }
            }
        }
    }

    return "";
}

From source file:com.ferdi2005.secondgram.AndroidUtilities.java

public static SpannableStringBuilder replaceTags(String str, int flag) {
    try {/*www .j  a va  2 s  .  c o m*/
        int start;
        int end;
        StringBuilder stringBuilder = new StringBuilder(str);
        if ((flag & FLAG_TAG_BR) != 0) {
            while ((start = stringBuilder.indexOf("<br>")) != -1) {
                stringBuilder.replace(start, start + 4, "\n");
            }
            while ((start = stringBuilder.indexOf("<br/>")) != -1) {
                stringBuilder.replace(start, start + 5, "\n");
            }
        }
        ArrayList<Integer> bolds = new ArrayList<>();
        if ((flag & FLAG_TAG_BOLD) != 0) {
            while ((start = stringBuilder.indexOf("<b>")) != -1) {
                stringBuilder.replace(start, start + 3, "");
                end = stringBuilder.indexOf("</b>");
                if (end == -1) {
                    end = stringBuilder.indexOf("<b>");
                }
                stringBuilder.replace(end, end + 4, "");
                bolds.add(start);
                bolds.add(end);
            }
        }
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(stringBuilder);
        for (int a = 0; a < bolds.size() / 2; a++) {
            spannableStringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")),
                    bolds.get(a * 2), bolds.get(a * 2 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableStringBuilder;
    } catch (Exception e) {
        FileLog.e(e);
    }
    return new SpannableStringBuilder(str);
}

From source file:fr.landel.utils.scripts.ScriptsReplacer.java

private void replaceSimples(final StringBuilder sb, final String key, final String value) {
    String simple;/* www  .j  ava  2 s .  c  o m*/

    final int valueLen = value.length();
    final int startLen = this.template.getVariableOpen().length();
    final int stopLen = this.template.getVariableClose().length();

    // get first
    int index = sb.indexOf(this.template.getVariableOpen());
    int indexStop = sb.indexOf(this.template.getVariableClose(), index + startLen);

    for (; index > -1 && indexStop > -1;) {
        simple = sb.substring(index + startLen, indexStop);

        if (key.equals(simple.trim())) {
            sb.replace(index, indexStop + stopLen, value);
            index += valueLen;
        }

        // get next
        index = sb.indexOf(this.template.getVariableOpen(), index + startLen);
        if (index > -1) {
            indexStop = sb.indexOf(this.template.getVariableClose(), index + startLen);
        }
    }
}

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

/**
 * Test inbound authentication with redirect binding with invalid signature parameter.
 *//*from  w  w w.  j  av  a 2s .c o  m*/
@Test
public void testAuthnRequestSignatureValidationWithInvalidSignatureForRedirect() {

    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("Signature=") + 10, httpQueryString.length(),
                "invalid_signature");
        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:com.ihelpoo.app.api.ApiClient.java

private static String _MakeURL(String p_url, Map<String, Object> params) {
    StringBuilder url = new StringBuilder(p_url);
    if (url.indexOf("?") < 0)
        url.append('?');

    for (String name : params.keySet()) {
        url.append('&');
        url.append(name);/*from   w ww.  ja v a  2  s.c  om*/
        url.append('=');
        url.append(String.valueOf(params.get(name)));
        //??URLEncoder?
        //url.append(URLEncoder.encode(String.valueOf(params.get(name)), UTF_8));
    }

    return url.toString().replace("?&", "?");
}

From source file:org.jahia.services.mail.MailServiceImpl.java

public String getEndpointUri() {
    if (sendMailEndpointUri == null) {
        StringBuilder uri = new StringBuilder();
        if (!settings.getUri().startsWith("smtp://") && !settings.getUri().startsWith("smtps://")) {
            uri.append("smtp://");
        }/*from  w w w.j a va2  s.c  o m*/
        uri.append(settings.getUri());
        if (StringUtils.isNotEmpty(settings.getFrom())) {
            uri.append(uri.indexOf("?") != -1 ? "&" : "?").append("from=").append(settings.getFrom());
        }
        if (StringUtils.isNotEmpty(settings.getTo())) {
            uri.append(uri.indexOf("?") != -1 ? "&" : "?").append("to=").append(settings.getTo());
        }

        sendMailEndpointUri = uri.toString();

        logger.debug("Using mail endpoint: {}", sendMailEndpointUri);
    }

    return sendMailEndpointUri;
}