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:Main.java

public static void main(String args[]) {
    StringBuilder sb = new StringBuilder();
    sb.append("java2s.com");
    int index = sb.indexOf("a");
    System.out.println(index);/*from  w w  w .ja  v a  2s. c om*/

}

From source file:gov.nih.nci.caaersinstaller.util.CsmJaasFileCopier.java

public static void main(String args[]) throws Exception {

    //      File csmJaasTemplateFile = new File("/Users/Moni/temp/installer/postgres.csm_jaas.config");
    //      File csmJassConfigFile = new File("/Users/Moni/temp/installer/csm_jaas.config");

    File csmJaasTemplateFile = new File(args[0]);
    File csmJassConfigFile = new File(args[1]);

    if (csmJassConfigFile.exists()) {
        //append content of csmJaasTemplateFile to existing csmJaasConfigFile
        String csmJaasTemplateFileContent = FileUtils.readFileToString(csmJaasTemplateFile);
        StringBuilder stringBuilder = new StringBuilder(FileUtils.readFileToString(csmJassConfigFile));

        int start = stringBuilder.indexOf("caaers {");
        if (start != -1) {
            //If caaers context exisits then replace it.
            int end = stringBuilder.indexOf("};", start);
            end = end + 2;/*from w w  w  .  ja v a2  s  .  c  om*/
            stringBuilder.replace(start, end, csmJaasTemplateFileContent);
        } else {
            //if caaers context does not exist then add it 
            stringBuilder.append("\n");
            stringBuilder.append("\n");
            stringBuilder.append(csmJaasTemplateFileContent);
        }

        FileUtils.writeStringToFile(csmJassConfigFile, stringBuilder.toString());
        System.out.println("Modified csm_jaas.config to add caaers context");

    } else {
        //Create a new File with Contents of csmJaasTemplateFile
        FileUtils.copyFile(csmJaasTemplateFile, csmJassConfigFile);
        System.out.println("Created csm_jaas.config");

    }
}

From source file:icevaluation.BingAPIAccess.java

public static void main(String[] args) {
    String searchText = "arts site:wikipedia.org";
    searchText = searchText.replaceAll(" ", "%20");
    // String accountKey="jTRIJt9d8DR2QT/Z3BJCAvY1BfoXj0zRYgSZ8deqHHo";
    String accountKey = "JfeJSA3x6CtsyVai0+KEP0A6CYEUBT8VWhZmm9CS738";

    byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
    String accountKeyEnc = new String(accountKeyBytes);
    URL url;//from w w  w  . ja  v  a 2 s . c  o  m
    try {
        url = new URL("https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27"
                + searchText + "%27&$format=JSON");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        StringBuilder sb = new StringBuilder();
        String output;
        System.out.println("Output from Server .... \n");
        //write json to string sb
        int c = 0;
        if ((output = br.readLine()) != null) {
            System.out.println("Output is: " + output);
            sb.append(output);
            c++;
            //System.out.println("C:"+c);

        }

        conn.disconnect();
        //find webtotal among output      
        int find = sb.indexOf("\"WebTotal\":\"");
        int startindex = find + 12;
        System.out.println("Find: " + find);

        int lastindex = sb.indexOf("\",\"WebOffset\"");

        System.out.println(sb.substring(startindex, lastindex));

    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }

}

From source file:com.admc.jcreole.JCreole.java

/**
 * Run this method with no parameters to see syntax requirements and the
 * available parameters.//from w w  w  . j a v a 2  s.  com
 *
 * N.b. do not call this method from a persistent program, because it
 * may call System.exit!
 * <p>
 * Any long-running program should use the lower-level methods in this
 * class instead (or directly use CreoleParser and CreoleScanner
 * instances).
 * </p> <p>
 * This method executes with all JCreole privileges.
 * </p> <p>
 * This method sets up the following htmlExpander mappings (therefore you
 * can reference these in both Creole and boilerplate text).<p>
 * <ul>
 *   <li>sys|*: mappings for Java system properties
 *   <li>isoDateTime
 *   <li>isoDate
 *   <li>pageTitle: Value derived from the specified Creole file name.
 * </ul>
 *
 * @throws IOException for any I/O problem that makes it impossible to
 *         satisfy the request.
 * @throws CreoleParseException
 *         if can not generate output, or if the run generates 0 output.
 *         If the problem is due to input formatting, in most cases you
 *         will get a CreoleParseException, which is a RuntimException, and
 *         CreoleParseException has getters for locations in the source
 *         data (though they will be offset for \r's in the provided
 *         Creole source, if any).
 */
public static void main(String[] sa) throws IOException {
    String bpResPath = null;
    String bpFsPath = null;
    String outPath = null;
    String inPath = null;
    boolean debugs = false;
    boolean troubleshoot = false;
    boolean noBp = false;
    int param = -1;
    try {
        while (++param < sa.length) {
            if (sa[param].equals("-d")) {
                debugs = true;
                continue;
            }
            if (sa[param].equals("-t")) {
                troubleshoot = true;
                continue;
            }
            if (sa[param].equals("-r") && param + 1 < sa.length) {
                if (bpFsPath != null || bpResPath != null || noBp)
                    throw new IllegalArgumentException();
                bpResPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-f") && param + 1 < sa.length) {
                if (bpResPath != null || bpFsPath != null || noBp)
                    throw new IllegalArgumentException();
                bpFsPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-")) {
                if (noBp || bpFsPath != null || bpResPath != null)
                    throw new IllegalArgumentException();
                noBp = true;
                continue;
            }
            if (sa[param].equals("-o") && param + 1 < sa.length) {
                if (outPath != null)
                    throw new IllegalArgumentException();
                outPath = sa[++param];
                continue;
            }
            if (inPath != null)
                throw new IllegalArgumentException();
            inPath = sa[param];
        }
        if (inPath == null)
            throw new IllegalArgumentException();
    } catch (IllegalArgumentException iae) {
        System.err.println(SYNTAX_MSG);
        System.exit(1);
    }
    if (!noBp && bpResPath == null && bpFsPath == null)
        bpResPath = DEFAULT_BP_RES_PATH;
    String rawBoilerPlate = null;
    if (bpResPath != null) {
        if (bpResPath.length() > 0 && bpResPath.charAt(0) == '/')
            // Classloader lookups are ALWAYS relative to CLASSPATH roots,
            // and will abort if you specify a beginning "/".
            bpResPath = bpResPath.substring(1);
        InputStream iStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(bpResPath);
        if (iStream == null)
            throw new IOException("Boilerplate inaccessible: " + bpResPath);
        rawBoilerPlate = IOUtil.toString(iStream);
    } else if (bpFsPath != null) {
        rawBoilerPlate = IOUtil.toString(new File(bpFsPath));
    }
    String creoleResPath = (inPath.length() > 0 && inPath.charAt(0) == '/') ? inPath.substring(1) : inPath;
    // Classloader lookups are ALWAYS relative to CLASSPATH roots,
    // and will abort if you specify a beginning "/".
    InputStream creoleStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(creoleResPath);
    File inFile = (creoleStream == null) ? new File(inPath) : null;
    JCreole jCreole = (rawBoilerPlate == null) ? (new JCreole()) : (new JCreole(rawBoilerPlate));
    if (debugs) {
        jCreole.setInterWikiMapper(new InterWikiMapper() {
            // This InterWikiMapper is just for prototyping.
            // Use wiki name of "nil" to force lookup failure for path.
            // Use wiki page of "nil" to force lookup failure for label.
            public String toPath(String wikiName, String wikiPage) {
                if (wikiName != null && wikiName.equals("nil"))
                    return null;
                return "{WIKI-LINK to: " + wikiName + '|' + wikiPage + '}';
            }

            public String toLabel(String wikiName, String wikiPage) {
                if (wikiPage == null)
                    throw new RuntimeException("Null page name sent to InterWikiMapper");
                if (wikiPage.equals("nil"))
                    return null;
                return "{LABEL for: " + wikiName + '|' + wikiPage + '}';
            }
        });
        Expander creoleExpander = new Expander(Expander.PairedDelims.RECTANGULAR);
        creoleExpander.put("testMacro",
                "\n\n<<prettyPrint>>\n{{{\n" + "!/bin/bash -p\n\ncp /etc/inittab /tmp\n}}}\n");
        jCreole.setCreoleExpander(creoleExpander);
    }
    jCreole.setPrivileges(EnumSet.allOf(JCreolePrivilege.class));
    Expander exp = jCreole.getHtmlExpander();
    Date now = new Date();
    exp.putAll("sys", System.getProperties(), false);
    exp.put("isoDateTime", isoDateTimeFormatter.format(now), false);
    exp.put("isoDate", isoDateFormatter.format(now), false);
    exp.put("pageTitle",
            (inFile == null) ? creoleResPath.replaceFirst("[.][^.]*$", "").replaceFirst(".*[/\\\\.]", "")
                    : inFile.getName().replaceFirst("[.][^.]*$", ""));
    if (troubleshoot) {
        // We don't write any HMTL output here.
        // Goal is just to output diagnostics.
        StringBuilder builder = (creoleStream == null) ? IOUtil.toStringBuilder(inFile)
                : IOUtil.toStringBuilder(creoleStream);
        int newlineCount = 0;
        int lastOffset = -1;
        int offset = builder.indexOf("\n");
        for (; offset >= 0; offset = builder.indexOf("\n", offset + 1)) {
            lastOffset = offset;
            newlineCount++;
        }
        // Accommodate input files with no terminating newline:
        if (builder.length() > lastOffset + 1)
            newlineCount++;
        System.out.println("Input lines:  " + newlineCount);
        Exception lastException = null;
        while (true) {
            try {
                jCreole.parseCreole(builder);
                break;
            } catch (Exception e) {
                lastException = e;
            }
            if (builder.charAt(builder.length() - 1) == '\n')
                builder.setLength(builder.length() - 1);
            offset = builder.lastIndexOf("\n");
            if (offset < 1)
                break;
            newlineCount--;
            builder.setLength(builder.lastIndexOf("\n"));
        }
        System.out.println((lastException == null) ? "Input validates"
                : String.format("Error around input line %d:  %s", newlineCount, lastException.getMessage()));
        return;
    }
    String generatedHtml = (creoleStream == null) ? jCreole.parseCreole(inFile)
            : jCreole.parseCreole(IOUtil.toStringBuilder(creoleStream));
    String html = jCreole.postProcess(generatedHtml, SystemUtils.LINE_SEPARATOR);
    if (outPath == null) {
        System.out.print(html);
    } else {
        FileUtils.writeStringToFile(new File(outPath), html, "UTF-8");
    }
}

From source file:Main.java

public static String aniadeCabecera(StringBuilder documento) {
    if (documento.indexOf("<?xml version=\"1.0\"") != -1) //si tiene cabecera ni lo tocamos
        return documento.toString();
    StringBuilder sb = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>").append(documento);
    return sb.toString();
}

From source file:Main.java

/**
 * use ? & make a full url//from ww  w. j  a  v a 2 s  . c o m
 * @param p_url
 * @param params
 * @return
 */
public static String makeURL(String p_url, Map<String, String> params) {
    StringBuilder url = new StringBuilder(p_url);
    if (url.indexOf("?") < 0)
        url.append('?');

    for (String name : params.keySet()) {
        url.append('&');
        url.append(name);
        url.append('=');
        url.append(String.valueOf(params.get(name)));
    }

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

From source file:Main.java

public static void replace(StringBuilder sb, String source, String target) {
    int index = sb.indexOf(source);
    int endIndex = index + source.length();
    sb.replace(index, endIndex, target);
}

From source file:Main.java

/**
 * Replaces all occurrences of the given string in the string builder
 * @param   stringBuilder The string builder to update with replaced strings
 * @param    toReplace The string to replace in the string builder
 * @param   replaceWith   The string to replace with */
public static void replaceAll(StringBuilder stringBuilder, String toReplace, String replaceWith) {
    int index = stringBuilder.indexOf(toReplace);

    while (index != -1) {
        stringBuilder.replace(index, index + toReplace.length(), replaceWith);
        index += replaceWith.length(); // Move to the end of the replacement
        index = stringBuilder.indexOf(toReplace, index);
    }/*from   w  w w  .  j a v a 2s  .c o  m*/
}

From source file:Main.java

public static Spannable replaceTags(String str, Context context) {
    try {/*  w  w  w .j a va2 s. c  o  m*/
        int start = -1;
        int startColor = -1;
        int end = -1;
        StringBuilder stringBuilder = new StringBuilder(str);
        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<>();
        ArrayList<Integer> colors = new ArrayList<>();
        while ((start = stringBuilder.indexOf("<b>")) != -1
                || (startColor = stringBuilder.indexOf("<c")) != -1) {
            if (start != -1) {
                stringBuilder.replace(start, start + 3, "");
                end = stringBuilder.indexOf("</b>");
                stringBuilder.replace(end, end + 4, "");
                bolds.add(start);
                bolds.add(end);
            } else if (startColor != -1) {
                stringBuilder.replace(startColor, startColor + 2, "");
                end = stringBuilder.indexOf(">", startColor);
                int color = Color.parseColor(stringBuilder.substring(startColor, end));
                stringBuilder.replace(startColor, end + 1, "");
                end = stringBuilder.indexOf("</c>");
                stringBuilder.replace(end, end + 4, "");
                colors.add(startColor);
                colors.add(end);
                colors.add(color);
            }
        }
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(stringBuilder);
        for (int a = 0; a < colors.size() / 3; a++) {
            spannableStringBuilder.setSpan(new ForegroundColorSpan(colors.get(a * 3 + 2)), colors.get(a * 3),
                    colors.get(a * 3 + 1), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return spannableStringBuilder;
    } catch (Exception e) {

    }
    return new SpannableStringBuilder(str);
}

From source file:Main.java

/**
 * Make a replacement of first "find" string by "replace" string into the StringBuilder
 * //ww  w.  j a v  a  2 s.  co  m
 * @param builder
 * @param find
 * @param replace
 * @return True if one element is found
 */
public final static boolean replace(StringBuilder builder, String find, String replace) {
    if (find == null) {
        return false;
    }
    int start = builder.indexOf(find);
    if (start == -1) {
        return false;
    }
    int end = start + find.length();
    if (replace != null) {
        builder.replace(start, end, replace);
    } else {
        builder.replace(start, end, "");
    }
    return true;
}