Example usage for org.apache.commons.lang3 StringUtils repeat

List of usage examples for org.apache.commons.lang3 StringUtils repeat

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils repeat.

Prototype

public static String repeat(final char ch, final int repeat) 

Source Link

Document

<p>Returns padding using the specified delimiter repeated to a given length.</p> <pre> StringUtils.repeat('e', 0) = "" StringUtils.repeat('e', 3) = "eee" StringUtils.repeat('e', -2) = "" </pre> <p>Note: this method doesn't not support padding with <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a> as they require a pair of char s to be represented.

Usage

From source file:org.drftpd.protocol.speedtest.net.slave.SpeedTestHandler.java

/**
 * Load conf/plugins/speedtest.net.slave.conf
 * @throws Exception// ww w.  ja v a  2 s .  c om
 */
private void readConf() throws Exception {
    logger.info("Loading speedtest.net slave configuration...");
    Properties p = new Properties();
    FileInputStream fis = null;
    try {
        fis = new FileInputStream("conf/plugins/speedtest.net.slave.conf");
        p.load(fis);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
    if (p.getProperty("sizes") != null) {
        String[] strArray = p.getProperty("sizes").split(",");
        _sizes = new int[strArray.length];
        for (int i = 0; i < strArray.length; i++) {
            _sizes[i] = Integer.parseInt(strArray[i]);
        }
    }
    if (p.getProperty("size.loop") != null) {
        _sizeLoop = Integer.parseInt(p.getProperty("size.loop"));
    }
    if (p.getProperty("max.down.time") != null) {
        _downTime = Integer.parseInt(p.getProperty("max.down.time")) * 1000;
    }
    if (p.getProperty("max.up.time") != null) {
        _upTime = Integer.parseInt(p.getProperty("max.up.time")) * 1000;
    }
    String payloadString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if (p.getProperty("payload.string") != null) {
        payloadString = p.getProperty("payload.string");
    }
    int payloadRepeat = 7000;
    if (p.getProperty("payload.repeat") != null) {
        payloadRepeat = Integer.parseInt(p.getProperty("payload.repeat"));
    }
    _payload = StringUtils.repeat(payloadString, payloadRepeat);
    if (p.getProperty("payload.loop") != null) {
        _payloadLoop = Integer.parseInt(p.getProperty("payload.loop"));
    }
    if (p.getProperty("threads.up") != null) {
        _upThreads = Integer.parseInt(p.getProperty("threads.up"));
    }
    if (p.getProperty("threads.down") != null) {
        _downThreads = Integer.parseInt(p.getProperty("threads.down"));
    }
    if (p.getProperty("sleep") != null) {
        _sleep = Integer.parseInt(p.getProperty("sleep"));
    }
}

From source file:org.drftpd.protocol.speedtest.net.slave.SpeedTestHandler.java

private float getUploadSpeed(String url) {
    long totalTime = 0L;
    long totalBytes = 0L;

    long startTime = System.currentTimeMillis();

    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();

    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("content-type", "application/x-www-form-urlencoded");
    httpPost.setConfig(requestConfig);/* www.jav  a 2s .  c  o m*/

    String payload = _payload; // Initial payload

    StopWatch watch = new StopWatch();

    SpeedTestCallable[] speedTestCallables = new SpeedTestCallable[_upThreads];
    for (int i = 0; i < _upThreads; i++) {
        speedTestCallables[i] = new SpeedTestCallable();
    }

    ExecutorService executor = Executors.newFixedThreadPool(_upThreads);
    List<Future<Long>> threadList;
    Set<Callable<Long>> callables = new HashSet<Callable<Long>>();

    boolean limitReached = false;

    int i = 2;
    while (true) {
        if ((System.currentTimeMillis() - startTime) > _upTime) {
            break;
        }

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("content1", payload));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        } catch (UnsupportedEncodingException e) {
            logger.error("Unsupported encoding of payload for speedtest upload: " + e.getMessage());
            close(executor, callables);
            return 0;
        }

        callables.clear();
        for (int k = 0; k < _upThreads; k++) {
            speedTestCallables[k].setHttpPost(httpPost);
            callables.add(speedTestCallables[k]);
        }

        for (int j = 0; j < _payloadLoop; j++) {
            try {
                watch.reset();
                Thread.sleep(_sleep);
                watch.start();
                threadList = executor.invokeAll(callables);
                for (Future<Long> fut : threadList) {
                    Long bytes = fut.get();
                    totalBytes += bytes;
                }
                watch.stop();
                totalTime += watch.getTime();
            } catch (InterruptedException e) {
                logger.error(e.getMessage());
                close(executor, callables);
                return 0;
            } catch (ExecutionException e) {
                if (e.getMessage().contains("Error code 413")) {
                    limitReached = true;
                    payload = StringUtils.repeat(_payload, i - 2);
                } else {
                    logger.error(e.getMessage());
                    close(executor, callables);
                    return 0;
                }
            }
            if ((System.currentTimeMillis() - startTime) > _upTime) {
                break;
            }
        }

        if (!limitReached) { // Increase payload size if not too big
            payload = StringUtils.repeat(_payload, i);
            i++;
        }
    }

    if (totalBytes == 0L || totalTime == 0L) {
        close(executor, callables);
        return 0;
    }

    close(executor, callables);

    return (float) (((totalBytes * 8) / totalTime) * 1000) / 1000000;
}

From source file:org.easyxml.xml.Element.java

/**
 * //from w w w . j  a v a 2 s  . c om
 * Method to display this element as a well-formatted String.
 * 
 * @param indent
 *            - Indent count for this element.
 * 
 * @param outputEmptyAttribute
 *            - Specify if empty attribute shall be displayed.
 * 
 * @param outputEmptyElement
 *            - Specify if empty children element shall be displayed.
 * 
 * @return String form of this XML element.
 */

public String toString(int indent, Boolean outputEmptyAttribute, Boolean outputEmptyElement) {

    // If this is an empty element and no need to output empty element,
    // return "" immediately.

    if (!outputEmptyElement && this.isEmpty())

        return "";

    String indentString = StringUtils.repeat(DefaultIndentHolder, indent);

    StringBuilder sb = new StringBuilder(indentString + "<" + name);

    // If this element has only attributes

    if ((children == null || children.size() == 0) && (value == null || value.trim().length() == 0)) {

        // Compose the empty element tag

        if (attributes != null) {

            sb.append(allAttributesAsString(outputEmptyAttribute));

        }

        sb.append("/>");

    } else {

        // Compose the opening tag

        if (attributes != null) {

            sb.append(allAttributesAsString(outputEmptyAttribute));

        }

        sb.append('>');

        // Include the children elements by order

        if (children != null && !children.isEmpty()) {

            sb.append(NewLine);

            Iterator<Entry<String, List<Element>>> iterator2 = children.entrySet().iterator();

            while (iterator2.hasNext()) {

                Entry<String, List<Element>> next = iterator2.next();

                String path = next.getKey();

                if (path.contains(DefaultElementPathSign))

                    continue;

                List<Element> elements = next.getValue();

                for (int i = 0; i < elements.size(); i++) {

                    Element element = elements.get(i);

                    if (outputEmptyElement || !elements.get(i).isEmpty()) {

                        sb.append(element.toString(indent + 1, outputEmptyAttribute, outputEmptyElement)
                                + NewLine);

                    }

                }

            }

        }

        // Include the inner text of this element

        if (StringUtils.isNotBlank(value)) {

            if (children != null && !children.isEmpty()) {

                sb.append(IgnoreLeadingSpace ? indentString + DefaultIndentHolder + value + NewLine
                        : value + NewLine);

            } else {

                sb.append(value);

            }

        }

        // Include the closing tag

        if (children != null && !children.isEmpty()) {

            sb.append(indentString);

        }

        sb.append(String.format(ClosingTagFormat, name));

    }

    return sb.toString();

}

From source file:org.easyxml.xml.Element.java

public String toJSON(int indent) {

    String indentString = StringUtils.repeat(DefaultIndentHolder, indent);

    StringBuilder sb = new StringBuilder();

    sb.append(String.format("%s\"%s\":", indentString, this.getName()));

    String thisPath = this.getPath();

    // If there is valid text node, return it immediately

    if (!StringUtils.isBlank(this.value)) {

        sb.append(String.format("\"%s\"", this.getValue()));

        return sb.toString();

    }/* w  ww .j  a  v  a  2  s  . c om*/

    // Output as an object

    sb.append("{");

    // Otherwise, consider both the attributes and its children elements for
    // output

    if (this.attributes != null) {

        String attrIndent = StringUtils.repeat(DefaultIndentHolder, indent + 1);

        for (Map.Entry<String, Attribute> entry : this.attributes.entrySet()) {

            String attrName = entry.getKey();

            String attrValue = this.getAttributeValue(attrName);

            sb.append(String.format("\n%s\"%s\": \"%s\",", attrIndent, attrName, attrValue));

        }

    }

    if (this.children != null) {

        List<String> firstLevelPathes = new ArrayList<String>();

        for (Map.Entry<String, List<Element>> entry : this.children.entrySet()) {

            String originalPath = entry.getKey();

            int firstSignPos = StringUtils.indexOfAny(originalPath, '>', '<');

            String elementName = elementNameOf(originalPath);

            if (firstSignPos == -1) {

                firstLevelPathes.add(originalPath);

            }

        }

        for (String firstLevelPath : firstLevelPathes) {

            List<Element> elements = this.getElementsOf(firstLevelPath);

            // Check to see if elements could be converted to JSON array

            if (elements.size() > 1) {

                Boolean asArray = true;

                for (Element e : elements) {

                    if (!StringUtils.isBlank(e.getValue())) {

                        asArray = false;

                        break;

                    }

                }

                // If they could be treated as array

                if (asArray) {

                    String jsonKey = String.format("\"%s\":", elements.get(0).getName());

                    sb.append(String.format("\n%s%s[\n",

                            StringUtils.repeat(DefaultIndentHolder, indent + 1), jsonKey));

                    for (Element e : elements) {

                        sb.append(String.format("%s,\n", e.toJSON(indent + 2).replace(jsonKey, "")));

                    }

                    // Remove the last ','

                    sb.setLength(sb.length() - 2);

                    sb.append(String.format("\n%s],", StringUtils.repeat(DefaultIndentHolder, indent + 1)));

                    continue;

                }

            }

            // Otherwise, output the elements one by one

            for (Element e : elements) {

                sb.append(String.format("\n%s,", e.toJSON(indent + 1)));

            }

        }

        //

        // //Remove the last ',' and append '}'

        // sb.setLength(sb.length()-1);

        // sb.append("\n" + indentString + "}");

    }

    if (sb.toString().endsWith(",")) {

        sb.setLength(sb.toString().length() - 1);

        sb.append(String.format("\n%s}", indentString));

    }

    return sb.toString();

}

From source file:org.eclipse.recommenders.calls.rcp.ProposalMatcher.java

public ProposalMatcher(CompletionProposal proposal) {
    jSignature = getSignature(proposal);
    jName = valueOf(proposal.getName());
    jParams = getParameterTypes(jSignature);

    for (int i = 0; i < jParams.length; i++) {
        String param = getTypeErasure(jParams[i]);
        String paramBaseType = getElementType(param);
        param = param.replace('.', '/');
        param = StringUtils.removeEnd(param, ";");
        if (isWildcardCapture(paramBaseType) || isTypeParameter(paramBaseType)) {
            int dimensions = getArrayCount(param);
            param = StringUtils.repeat('[', dimensions) + "Ljava/lang/Object";
        }//  ww  w . j a v  a  2 s . co m
        jParams[i] = param;
    }
}

From source file:org.eclipse.recommenders.utils.Names.java

public static String vm2srcQualifiedType(final ITypeName type) {
    if (type.isPrimitiveType()) {
        return Names.vm2srcSimpleTypeName(type);
    }/*from   w  w  w .  j  a  va  2s. c  o m*/
    if (type.isArrayType()) {
        return vm2srcQualifiedType(type.getArrayBaseType())
                + StringUtils.repeat("[]", type.getArrayDimensions());
    }
    String s = type.getIdentifier();
    s = s.replace('/', '.');
    return s.substring(1);
}

From source file:org.eclipse.recommenders.utils.rcp.CompilerBindings.java

/**
 * TODO nested anonymous types are not resolved correctly. JDT uses line numbers for inner types instead of $1,..,$n
 *///  ww  w.  jav a 2 s. c  o  m
public static Optional<ITypeName> toTypeName(@Nullable TypeBinding binding) {
    // XXX generics fail
    if (binding == null) {
        return absent();
    }
    //
    final boolean boundParameterizedType = binding.isBoundParameterizedType();
    final boolean parameterizedType = binding.isParameterizedType();

    // if (binding.isBoundParameterizedType()) {
    // return null;
    // }

    if (binding.isArrayType()) {
        final int dimensions = binding.dimensions();
        final TypeBinding leafComponentType = binding.leafComponentType();
        final String arrayDimensions = StringUtils.repeat("[", dimensions);
        final Optional<ITypeName> typeName = toTypeName(leafComponentType);
        if (!typeName.isPresent()) {
            return absent();
        }
        final ITypeName res = VmTypeName.get(arrayDimensions + typeName.get().getIdentifier());
        return fromNullable(res);
    }
    // TODO: handling of generics is bogus!
    if (binding instanceof TypeVariableBinding) {
        final TypeVariableBinding generic = (TypeVariableBinding) binding;
        if (generic.declaringElement instanceof TypeBinding) {
            // XXX: for this?
            binding = (TypeBinding) generic.declaringElement;
        } else if (generic.superclass != null) {
            // example Tuple<T1 extends List, T2 extends Number) --> for
            // generic.superclass (T2)=Number
            // we replace the generic by its superclass
            binding = generic.superclass;
        }
    }

    String signature = String.valueOf(binding.genericTypeSignature());
    // if (binding instanceof BinaryTypeBinding) {
    // signature = StringUtils.substringBeforeLast(signature, ";");
    // }

    if (signature.length() == 1) {
        // no handling needed. primitives always look the same.
    } else if (signature.endsWith(";")) {
        signature = StringUtils.substringBeforeLast(signature, ";");
    } else {
        signature = "L" + SignatureUtil.stripSignatureToFQN(signature);
    }
    final ITypeName res = VmTypeName.get(signature);
    return fromNullable(res);
}

From source file:org.eclipse.recommenders.utils.rcp.JavaElementResolver.java

/**
 * Returns null if we fail to resolve all types used in the method signature, for instance generic return types
 * etc...//w  w  w  .  j  av  a2  s . c om
 * 
 */
// This method should return IMethodNames in all cases but yet it does not work completey as we want it to work
public Optional<IMethodName> toRecMethod(final IMethod jdtMethod) {
    if (jdtMethod == null) {
        return absent();
    }
    if (!jdtMethod.exists()) {
        // compiler generated methods (e.g., calls to constructors to inner non-static classes do not exist.
        return absent();
    }
    JdtUtils.resolveJavaElementProxy(jdtMethod);
    IMethodName recMethod = (IMethodName) cache.inverse().get(jdtMethod);
    if (recMethod == null) {
        try {
            final IType jdtDeclaringType = jdtMethod.getDeclaringType();
            //
            final String[] unresolvedParameterTypes = jdtMethod.getParameterTypes();
            final String[] resolvedParameterTypes = new String[unresolvedParameterTypes.length];
            for (int i = resolvedParameterTypes.length; i-- > 0;) {
                final String unresolved = unresolvedParameterTypes[i];
                final int arrayCount = Signature.getArrayCount(unresolved);
                String resolved = resolveUnqualifiedTypeNamesAndStripOffGenericsAndArrayDimension(unresolved,
                        jdtDeclaringType).or("V");
                resolved = resolved + StringUtils.repeat("[]", arrayCount);
                resolvedParameterTypes[i] = resolved;
            }
            String resolvedReturnType = null;

            // binary synthetic methods (compiler generated methods) do not exist and thus,
            // jdtMethod.getReturnType() throws an execption...

            final String unresolvedReturnType = jdtMethod.getReturnType();
            try {
                final int returnTypeArrayCount = Signature.getArrayCount(unresolvedReturnType);
                resolvedReturnType = JavaModelUtil.getResolvedTypeName(unresolvedReturnType, jdtDeclaringType)
                        + StringUtils.repeat("[]", returnTypeArrayCount);

            } catch (final JavaModelException e) {
                RecommendersUtilsPlugin.log(e);
            }
            if (resolvedReturnType == null) {
                RecommendersUtilsPlugin.logWarning("Failed to resolve return type '%s' of method %s.%s%s",
                        unresolvedReturnType, jdtDeclaringType.getFullyQualifiedName(),
                        jdtMethod.getElementName(), jdtMethod.getSignature());
                return absent();
            }
            final String methodSignature = Names.src2vmMethod(
                    jdtMethod.isConstructor() ? "<init>" : jdtMethod.getElementName(), resolvedParameterTypes,
                    resolvedReturnType);
            final ITypeName recDeclaringType = toRecType(jdtDeclaringType);
            recMethod = VmMethodName.get(recDeclaringType.getIdentifier(), methodSignature);
            registerRecJdtElementPair(recMethod, jdtMethod);
        } catch (final Exception e) {
            RecommendersUtilsPlugin.logError(e, "failed to resolve jdt method '%s'.", jdtMethod);
            return absent();
        }
    }
    return fromNullable(recMethod);
}

From source file:org.eclipse.recommenders.utils.rcp.JdtUtils.java

public static Optional<ITypeName> resolveUnqualifiedJDTType(String qName, final IJavaElement parent) {
    try {/*from   ww  w  . j a va  2 s  . c o  m*/
        qName = Signature.getTypeErasure(qName);
        qName = StringUtils.removeEnd(qName, ";");
        final int dimensions = Signature.getArrayCount(qName);
        if (dimensions > 0) {
            qName = Signature.getElementType(qName);
        }

        if (isPrimitiveTypeSignature(qName)) {
            final ITypeName t = VmTypeName.get(StringUtils.repeat('[', dimensions) + qName);
            return of(t);
        }

        final IType type = findClosestTypeOrThis(parent);
        if (type == null) {
            return absent();
        }

        if (qName.charAt(0) == Signature.C_TYPE_VARIABLE) {
            String literal = StringUtils.repeat('[', dimensions) + VmTypeName.OBJECT.getIdentifier();
            ITypeName name = VmTypeName.get(literal);
            return of(name);
        }
        if (qName.charAt(0) == Signature.C_UNRESOLVED) {

            final String[][] resolvedNames = type.resolveType(qName.substring(1));
            if (resolvedNames == null || resolvedNames.length == 0) {
                return of((ITypeName) VmTypeName.OBJECT);
            }
            final String pkg = new String(resolvedNames[0][0]);
            final String name = new String(resolvedNames[0][1]).replace('.', '$');
            qName = StringUtils.repeat('[', dimensions) + "L" + pkg + "." + name;
        }
        qName = qName.replace('.', '/');
        final ITypeName typeName = VmTypeName.get(qName);
        return of(typeName);
    } catch (final Exception e) {
        log(e);
        return absent();
    }
}

From source file:org.eclipse.smarthome.documentation.MarkdownProvider.java

/**
 * Returns a markdown table header for a list of column names.
 *
 * @param cols/*from   w w  w .  j  a v  a 2s .com*/
 * @return
 */
private static StringBuilder getTableHeader(List<String> cols) {
    StringBuilder builder = new StringBuilder(TABLE_DIVIDER);
    for (String col : cols) {
        builder.append(col).append(TABLE_DIVIDER);
    }
    builder.append("\n").append('|').append(StringUtils.repeat("---" + TABLE_DIVIDER, cols.size()))
            .append("\n");
    return builder;
}