Example usage for java.lang StringBuilder length

List of usage examples for java.lang StringBuilder length

Introduction

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

Prototype

int length();

Source Link

Document

Returns the length of this character sequence.

Usage

From source file:eu.digitisation.idiomaident.utils.ExtractTestSamples.java

private static String nextSample(File inFolder) {
    File[] langFolders = inFolder.listFiles();

    Date now = new Date();
    Random rand = new Random(now.getTime());

    //get a ramdom language       
    int numLangs = langFolders.length;
    int chosenLang = rand.nextInt(numLangs);

    String lang = langFolders[chosenLang].getName();

    //get a ramdom file from the folder        
    File[] langFiles = langFolders[chosenLang].listFiles();
    int numFiles = langFiles.length;
    int chosenFile = rand.nextInt(numFiles);

    File langFile = langFiles[chosenFile];

    //open and read the file
    try {// ww  w  .  j  ava  2s . c  o m
        String text = FileUtils.readFileToString(langFile, Charset.forName("UTF-8"));

        text = StringNormalize.stringNormalize(text);

        text = text.replaceAll("[\\n.,:;]", " ");
        text = text.trim();

        if (text.replaceAll("[\\p{Space}]+", "").length() < 20) {
            return null;
        }

        //split the text in words
        String[] words = text.split("[\\p{Space}]+");

        boolean correct = false;
        StringBuilder sampleBuild = null;

        while (!correct) {
            //chosen the initial position to read the words
            int actualWord = rand.nextInt(words.length);
            correct = true;

            sampleBuild = new StringBuilder();
            while (sampleBuild.length() < 20) {
                if (actualWord < words.length) {
                    sampleBuild.append(words[actualWord]);
                    sampleBuild.append(" ");
                } else {
                    correct = false;
                    break;
                }

                actualWord++;
            }
        }

        //complete the sample
        sampleBuild.deleteCharAt(sampleBuild.length() - 1);
        sampleBuild.append(";").append(lang).append("\n");

        return sampleBuild.toString();

    } catch (IOException ex) {
        System.out.println(ex.toString());
    }

    return null;
}

From source file:net.certiv.json.util.Strings.java

public static String csvValueList(List<Value> valueList, String sep) {
    if (valueList == null)
        return "";
    StringBuilder sb = new StringBuilder();
    for (Value v : valueList) {
        sb.append(v.basis + sep);/*from  ww  w  . j a v  a 2s .co  m*/
    }
    return sb.toString().substring(0, sb.length() - sep.length());
}

From source file:com.ninehcom.userinfo.util.HttpUtils.java

private static String buildUrl(String host, String path, Map<String, String> querys)
        throws UnsupportedEncodingException {
    StringBuilder sbUrl = new StringBuilder();
    sbUrl.append(host);//from  ww  w .  jav  a2s  . com
    if (!StringUtils.isBlank(path)) {
        sbUrl.append(path);
    }
    if (null != querys) {
        StringBuilder sbQuery = new StringBuilder();
        for (Map.Entry<String, String> query : querys.entrySet()) {
            if (0 < sbQuery.length()) {
                sbQuery.append("&");
            }
            if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                sbQuery.append(query.getValue());
            }
            if (!StringUtils.isBlank(query.getKey())) {
                sbQuery.append(query.getKey());
                if (!StringUtils.isBlank(query.getValue())) {
                    sbQuery.append("=");
                    sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                }
            }
        }
        if (0 < sbQuery.length()) {
            sbUrl.append("?").append(sbQuery);
        }
    }

    return sbUrl.toString();
}

From source file:com.appassit.http.ApiRequestFactory.java

/**
 * GETurl/*  w  ww. j a v a  2 s.  c om*/
 * 
 * @param url
 * @param params
 * @return
 */
private static String getGetRequestUrl(String url, ArrayList<BasicNameValuePair> params) {
    if (params == null || params.size() == 0) {
        return url;
    }
    StringBuilder builder = new StringBuilder();
    builder.append(url).append("?");
    for (BasicNameValuePair entry : params) {
        Object obj = entry.getValue();
        if (obj == null)
            continue;
        builder.append(entry.getName()).append("=").append(entry.getValue()).append("&");
    }
    builder.deleteCharAt(builder.length() - 1);
    return builder.toString();

}

From source file:language_engine.bing.BingTranslationApi.java

private static String buildStringArrayParam(Object[] values) {
    StringBuilder targetString = new StringBuilder("[\"");
    String value;//from  w  w  w .  j  a v a2 s  .  c o m
    for (Object obj : values) {
        if (obj != null) {
            value = obj.toString();
            if (value.length() != 0) {
                if (targetString.length() > 2)
                    targetString.append(",\"");
                targetString.append(value);
                targetString.append("\"");
            }
        }
    }
    targetString.append("]");
    return targetString.toString();
}

From source file:eu.e43.impeller.Utils.java

static public String encode(Map<String, String> params) {
    try {// www .j  a  v  a  2 s  .c  o m
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (sb.length() > 0) {
                sb.append('&');
            }
            sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            sb.append('=');
            sb.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        return sb.toString();
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.netflix.spinnaker.orca.pipelinetemplate.v1schema.render.tags.ModuleTag.java

/**
 * Look at this ungodly code. It's gross. Thanks to poor foresight, we tokenize on
 * whitespace, which can break concatenation, and definitely breaks usage of filters.
 * Sooo, we take the tokenized module definition and best-guess our way through collapsing
 * whitespace to arrive at the real key/value pairs that we later parse for populating
 * the module's internal context./*from  ww  w .ja va 2 s  .co m*/
 */
private static List<String> collapseWhitespaceInTokenPairs(List<String> tokens) {
    List<String> combinedTokens = new ArrayList<>();
    combinedTokens.add(tokens.get(0));

    StringBuilder buffer = new StringBuilder();
    // idx 0 is `moduleName`. Skip that guy.
    for (int i = 1; i < tokens.size(); i++) {
        String token = tokens.get(i);
        if (token.contains("=")) {
            if (buffer.length() > 0) {
                combinedTokens.add(buffer.toString());
            }
            buffer = new StringBuilder();
            combinedTokens.add(token);
        } else {
            String lastToken = combinedTokens.get(combinedTokens.size() - 1);
            if (lastToken.contains("=") && !lastToken.endsWith(",")) {
                buffer.append(combinedTokens.remove(combinedTokens.size() - 1));
            }
            buffer.append(token);
        }
    }

    if (buffer.length() > 0) {
        int i = combinedTokens.size() - 1;
        combinedTokens.set(i, combinedTokens.get(i) + buffer.toString());
    }

    return combinedTokens.stream().map(ModuleTag::removeTrailingCommas).collect(Collectors.toList());
}

From source file:eu.eidas.auth.commons.AttributeUtil.java

/**
 * Obtain the list of missing mandatory attributes.
 *
 * @param personalAttrList The Personal Attributes List.
 * @return the comma separated list of mandatory attributes that doesn't have value.
 *///from   w  ww.  j  a  v a 2  s .c om
public static String getMissingMandatoryAttributes(final IPersonalAttributeList personalAttrList) {
    StringBuilder listOfMissingAttributes = new StringBuilder();
    for (final PersonalAttribute personalAttribute : personalAttrList) {
        if (personalAttribute.isRequired() && personalAttribute.isEmpty()) {
            if (listOfMissingAttributes.length() > 0) {
                listOfMissingAttributes.append(", ");
            }
            listOfMissingAttributes.append(personalAttribute.getName());
        }
    }
    return listOfMissingAttributes.toString();
}

From source file:at.bestsolution.persistence.java.Util.java

public static final ProcessedSQL processSQL(String sql, final Function<String, List<?>> listLookup) {
    final List<String> dynamicParameterNames = new ArrayList<String>();
    final Map<String, List<TypedValue>> typedValuesMap = new HashMap<String, List<TypedValue>>();
    String s = new StrSubstitutor(new StrLookup() {

        @Override//from  w  w w  .j a  v  a  2  s.c  o  m
        public String lookup(String key) {
            List<?> data = listLookup.execute(key);
            if (data == null) {
                dynamicParameterNames.add(key);
                return "?";
            } else {
                List<TypedValue> list = null;
                StringBuilder rv = new StringBuilder();
                for (Object o : data) {
                    if (rv.length() > 0) {
                        rv.append(", ");
                    }

                    if (o == null) {
                        rv.append("NULL");
                    } else if (o instanceof Long || o instanceof Integer) {
                        rv.append(o);
                    } else {
                        if (list == null) {
                            list = new ArrayList<TypedValue>();
                            typedValuesMap.put(key, list);
                        }
                        list.add(new TypedValue(o, JDBCType.fromJavaType(o.getClass())));
                        rv.append("?");
                    }
                }
                return rv.toString();
            }
        }
    }, "#{", "}", '#').replace(sql);
    return new ProcessedSQL(s, dynamicParameterNames, null);
}

From source file:org.pixmob.fm2.util.HttpUtils.java

/**
 * Create a new Http connection for an URI.
 *///  w  w  w.ja  va2s. c o  m
public static HttpURLConnection newRequest(Context context, String uri, Set<String> cookies)
        throws IOException {
    if (DEBUG) {
        Log.d(TAG, "Setup connection to " + uri);
    }

    final HttpURLConnection conn = (HttpURLConnection) new URL(uri).openConnection();
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(false);
    conn.setConnectTimeout(30000);
    conn.setReadTimeout(60000);
    conn.setRequestProperty("Accept-Encoding", "gzip");
    conn.setRequestProperty("User-Agent", getUserAgent(context));
    conn.setRequestProperty("Cache-Control", "max-age=0");
    conn.setDoInput(true);

    // Close the connection when the request is done, or the application may
    // freeze due to a bug in some Android versions.
    conn.setRequestProperty("Connection", "close");

    if (conn instanceof HttpsURLConnection) {
        setupSecureConnection(context, (HttpsURLConnection) conn);
    }

    if (cookies != null && !cookies.isEmpty()) {
        final StringBuilder buf = new StringBuilder(256);
        for (final String cookie : cookies) {
            if (buf.length() != 0) {
                buf.append("; ");
            }
            buf.append(cookie);
        }
        conn.addRequestProperty("Cookie", buf.toString());
    }

    return conn;
}