Example usage for java.lang StringBuilder insert

List of usage examples for java.lang StringBuilder insert

Introduction

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

Prototype

@Override
public StringBuilder insert(int offset, double d) 

Source Link

Usage

From source file:com.redhat.rhn.common.util.StringUtil.java

/**
 * Convert the passed in string to a valid java method name. This basically
 * capitalizes each word and removes all word delimiters.
 * @param strIn The string to convert//from  www. j  a v  a2 s. c  o  m
 * @return The converted string
 */
public static String beanify(String strIn) {
    String str = strIn.trim();
    StringBuilder result = new StringBuilder(str.length());
    boolean wasWhitespace = false;

    for (int i = 0, j = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (Character.isLetterOrDigit(c)) {
            if (wasWhitespace) {
                c = Character.toUpperCase(c);
                wasWhitespace = false;
            }
            result.insert(j, c);
            j++;
            continue;
        }
        wasWhitespace = true;
    }
    return result.toString();
}

From source file:com.moviejukebox.tools.DOMHelper.java

/**
 * Take a file and wrap it in a new root element
 *
 * @param fileString//w  ww.  ja va 2 s .c  om
 * @return
 */
public static String wrapInXml(String fileString) {
    StringBuilder newOutput = new StringBuilder(fileString);

    int posMovie = fileString.indexOf("<" + MovieNFOReader.TYPE_MOVIE);
    int posTvShow = fileString.indexOf("<" + MovieNFOReader.TYPE_TVSHOW);
    int posEpisode = fileString.indexOf("<" + MovieNFOReader.TYPE_EPISODE);

    boolean posValid = Boolean.FALSE;

    if (posMovie == -1) {
        posMovie = fileString.length();
    } else {
        posValid = Boolean.TRUE;
    }

    if (posTvShow == -1) {
        posTvShow = fileString.length();
    } else {
        posValid = Boolean.TRUE;
    }

    if (posEpisode == -1) {
        posEpisode = fileString.length();
    } else {
        posValid = Boolean.TRUE;
    }

    if (posValid) {
        int pos = Math.min(posMovie, Math.min(posTvShow, posEpisode));
        newOutput.insert(pos, "<" + TYPE_ROOT + ">");
        newOutput.append("</").append(TYPE_ROOT).append(">");
    }

    return newOutput.toString();
}

From source file:com.fortinet.qcdb.AscenLinkKey.java

private String do_md5_TR_L7BM(String sn, String func) {
    try {// ww w .j a v a 2  s  . co  m
        String seed = "dkru4shelob" + sn + func;
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(seed.getBytes());
        StringBuilder k = new StringBuilder(b32encode_TR_L7BM(m.digest()));
        for (int i = 24; i > 0; i -= 4) {
            k.insert(i, '-');
        }

        return k.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.craftercms.commons.rest.RestClientUtils.java

/**
 * Converts a map of params to a query string.
 *
 * @param params the params to convert to a query string
 * @param encode if the param values should be encoded
 * @return the params as a query string/*from  w w w.  jav  a2s.  co  m*/
 */
public static String createQueryStringFromParams(MultiValueMap<String, String> params, boolean encode) {
    StringBuilder queryString = new StringBuilder();

    if (MapUtils.isNotEmpty(params)) {
        for (Map.Entry<String, List<String>> entry : params.entrySet()) {
            String paramName;
            try {
                paramName = URLEncoder.encode(entry.getKey(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // Should NEVER happen
                throw new RuntimeException(e);
            }

            for (String paramValue : entry.getValue()) {
                if (queryString.length() > 0) {
                    queryString.append('&');
                }

                if (encode) {
                    try {
                        paramValue = URLEncoder.encode(paramValue, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        // Should NEVER happen
                        throw new RuntimeException(e);
                    }
                }

                queryString.append(paramName).append('=').append(paramValue);
            }
        }

        queryString.insert(0, '?');
    }

    return queryString.toString();
}

From source file:org.apache.taverna.activities.rest.RESTActivityCredentialsProvider.java

@Override
public Credentials getCredentials(AuthScope authscope) {
    logger.info("Looking for credentials for: Host - " + authscope.getHost() + ";" + "Port - "
            + authscope.getPort() + ";" + "Realm - " + authscope.getRealm() + ";" + "Authentication scheme - "
            + authscope.getScheme());/*from www. j a v a2s  . c  o m*/

    // Ask the superclass first
    Credentials creds = super.getCredentials(authscope);
    if (creds != null) {
        /*
         * We have used setCredentials() on this class (for proxy host,
         * port, username,password) just before we invoked the http request,
         * which will then pick the proxy credentials up from here.
         */
        return creds;
    }

    // Otherwise, ask Credential Manager if is can provide the credential
    String AUTHENTICATION_REQUEST_MSG = "This REST service requires authentication in " + authscope.getRealm();

    try {
        UsernamePassword credentials = null;

        /*
         * if port is 80 - use HTTP, don't append port if port is 443 - use
         * HTTPS, don't append port any other port - append port + do 2
         * tests:
         * 
         * --- test HTTPS first has...()
         * --- if not there, do get...() for HTTP (which will save the thing)
         *
         * (save both these entries for HTTP + HTTPS if not there)
         */

        // build the service URI back to front
        StringBuilder serviceURI = new StringBuilder();
        serviceURI.insert(0, "/#" + URLEncoder.encode(authscope.getRealm(), "UTF-16"));
        if (authscope.getPort() != DEFAULT_HTTP_PORT && authscope.getPort() != DEFAULT_HTTPS_PORT) {
            // non-default port - add port name to the URI
            serviceURI.insert(0, ":" + authscope.getPort());
        }
        serviceURI.insert(0, authscope.getHost());
        serviceURI.insert(0, "://");

        // now the URI is complete, apart from the protocol name
        if (authscope.getPort() == DEFAULT_HTTP_PORT || authscope.getPort() == DEFAULT_HTTPS_PORT) {
            // definitely HTTP or HTTPS
            serviceURI.insert(0, (authscope.getPort() == DEFAULT_HTTP_PORT ? HTTP_PROTOCOL : HTTPS_PROTOCOL));

            // request credentials from CrendentialManager
            credentials = credentialManager.getUsernameAndPasswordForService(URI.create(serviceURI.toString()),
                    true, AUTHENTICATION_REQUEST_MSG);
        } else {
            /*
             * non-default port - will need to try both HTTP and HTTPS; just
             * check (no pop-up will be shown) if credentials are there -
             * one protocol that matched will be used; if
             */
            if (credentialManager
                    .hasUsernamePasswordForService(URI.create(HTTPS_PROTOCOL + serviceURI.toString()))) {
                credentials = credentialManager.getUsernameAndPasswordForService(
                        URI.create(HTTPS_PROTOCOL + serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG);
            } else if (credentialManager
                    .hasUsernamePasswordForService(URI.create(HTTP_PROTOCOL + serviceURI.toString()))) {
                credentials = credentialManager.getUsernameAndPasswordForService(
                        URI.create(HTTP_PROTOCOL + serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG);
            } else {
                /*
                 * Neither of the two options succeeded, request details with a
                 * popup for HTTP...
                 */
                credentials = credentialManager.getUsernameAndPasswordForService(
                        URI.create(HTTP_PROTOCOL + serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG);

                /*
                 * ...then save a second entry with HTTPS protocol (if the
                 * user has chosen to save the credentials)
                 */
                if (credentials != null && credentials.isShouldSave()) {
                    credentialManager.addUsernameAndPasswordForService(credentials,
                            URI.create(HTTPS_PROTOCOL + serviceURI.toString()));
                }
            }
        }

        if (credentials != null) {
            logger.info("Credentials obtained successfully");
            return new RESTActivityCredentials(credentials.getUsername(), credentials.getPasswordAsString());
        }
    } catch (Exception e) {
        logger.error("Unexpected error while trying to obtain user's credential from CredentialManager", e);
    }

    // error or nothing was found
    logger.info("Credentials not found - the user must have refused to enter them.");
    return null;
}

From source file:org.craftercms.core.util.HttpServletUtils.java

public static String getQueryStringFromParams(Map<String, Object> queryParams, String charset)
        throws UnsupportedEncodingException {
    StringBuilder queryString = new StringBuilder();

    if (MapUtils.isNotEmpty(queryParams)) {
        for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
            String paramName = URLEncoder.encode(entry.getKey(), charset);

            if (entry.getValue() instanceof List) {
                for (String paramValue : (List<String>) entry.getValue()) {
                    if (queryString.length() > 0) {
                        queryString.append('&');
                    }/*from w  w w  . ja va2s  .co m*/

                    paramValue = URLEncoder.encode(paramValue, charset);

                    queryString.append(paramName).append('=').append(paramValue);
                }
            } else {
                if (queryString.length() > 0) {
                    queryString.append('&');
                }

                String paramValue = URLEncoder.encode((String) entry.getValue(), charset);

                queryString.append(paramName).append('=').append(paramValue);
            }
        }

        queryString.insert(0, '?');
    }

    return queryString.toString();
}

From source file:io.github.tavernaextras.biocatalogue.model.Util.java

/**
 * Makes sure that the supplied string doesn't have any lines (separated by HTML line break tag) longer
 * than specified; assumes that there are no line breaks in the source line.
 * //from  w ww . jav  a  2s.  c  o m
 * @param str The string to work with.
 * @param iLineLength Desired length of each line.
 * @param bIgnoreBrokenWords True if line breaks are to be inserted exactly each <code>iLineLength</code>
 *                           symbols (which will most likely cause broken words); false to insert line breaks
 *                           at the first space after <code>iLineLength</code> symbols since last line break.
 * @return New string with inserted HTML line breaks.
 */
public static String ensureLineLengthWithinString(String str, int iLineLength, boolean bIgnoreBrokenWords) {
    StringBuilder out = new StringBuilder(str);

    // keep inserting line breaks from end of the line till the beginning until all done
    int iLineBreakPosition = 0;
    while (iLineBreakPosition >= 0 && iLineBreakPosition < out.length()) {
        // insert line break either exactly at calculated position or 
        iLineBreakPosition += iLineLength;
        iLineBreakPosition = (bIgnoreBrokenWords ? iLineBreakPosition : out.indexOf(" ", iLineBreakPosition));

        if (iLineBreakPosition > 0 && iLineBreakPosition < out.length()) {
            out.insert(iLineBreakPosition, "<br>");
            iLineBreakPosition += 4; // -- four is the length of "<br>"
        }
    }

    return (out.toString());
}

From source file:com.metinkale.prayerapp.hadis.Frag.java

public void setQuery(String query) {
    if ((query == null) || (mText == null)) {
        mQuery = query;/* ww w .  j  a  va  2 s  .  c  o  m*/
        return;
    }
    if ("".equals(query)) {
        mTv.setText(Html.fromHtml(mText));
    } else {
        query = normalize(query);

        StringBuilder st = new StringBuilder(mText);
        String normalized = mText;
        int i = normalized.indexOf(normalize(query));
        int p = 0;
        while (i >= 0) {
            st.insert(i + p, "<b>");
            p += 3;
            st.insert(i + query.length() + p, "</b>");
            p += 4;
            i = normalized.indexOf(normalize(query), i + 1);
        }
        mTv.setText(Html.fromHtml(st.toString()));
    }

}

From source file:ar.com.init.agros.license.LicenseVerifier.java

public String generateUniqueKey() {
    String result = "";
    try {//from w w w. j  ava 2s.  c o m
        File file = File.createTempFile("realhowto", ".vbs");
        file.deleteOnExit();
        FileWriter fw = new java.io.FileWriter(file);

        String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
                + "Set colDrives = objFSO.Drives\n" + "Set objDrive = colDrives.item(\"" + "C" + "\")\n"
                + "Wscript.Echo objDrive.SerialNumber"; // see note
        fw.write(vbs);
        fw.close();
        Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = input.readLine()) != null) {
            result += line;
        }
        input.close();
    } catch (Exception e) {
        Logger.getLogger(LicenseVerifier.class.getName()).log(Level.SEVERE, e.getMessage(), e);

    }

    result = DigestUtils.md5Hex(result);
    result = result.toUpperCase();

    StringBuilder buff = new StringBuilder(result);

    for (int i = buff.length() - 4; i > 0; i = i - 4) {
        buff.insert(i, "-");
    }

    return buff.toString();
}

From source file:de.jcup.egradle.sdk.builder.action.type.SaveTypesToSDKTargetFolder.java

String extractSubPathFromFile(File file, File parent) throws IOException {
    StringBuilder sb = new StringBuilder();
    File current = file;//from  w w w.ja  v  a 2s.c o  m
    boolean parentFound = false;

    while (current != null) {
        if (current.equals(parent)) {
            parentFound = true;
            break;
        }
        sb.insert(0, current.getName());
        sb.insert(0, '/');
        current = current.getParentFile();
    }
    if (!parentFound) {
        throw new IllegalArgumentException("Parent:" + parent + "\ndoes not contain\nFile:" + file);
    }
    String result = sb.toString();
    if (result.startsWith("/")) {
        result = StringUtils.substring(result, 1);
    }
    return result;
}