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

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

Introduction

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

Prototype

public static String repeat(String str, int repeat) 

Source Link

Document

Repeat a String repeat times to form a new String.

Usage

From source file:org.apache.storm.messaging.netty.NettyTest.java

private void doTestLargeMessage(Map<String, Object> stormConf) throws Exception {
    LOG.info("3 Should send and receive a large message");
    String reqMessage = StringUtils.repeat("c", 2_048_000);
    IContext context = TransportFactory.makeContext(stormConf);
    try {//from  ww  w .j a  va  2 s.  co  m
        AtomicReference<TaskMessage> response = new AtomicReference<>();
        try (IConnection server = context.bind(null, 0);
                IConnection client = context.connect(null, "localhost", server.getPort(), remoteBpStatus)) {
            server.registerRecv(mkConnectionCallback(response::set));
            waitUntilReady(client, server);
            byte[] messageBytes = reqMessage.getBytes(StandardCharsets.UTF_8);

            send(client, taskId, messageBytes);

            waitForNotNull(response);
            TaskMessage responseMessage = response.get();
            assertThat(responseMessage.task(), is(taskId));
            assertThat(responseMessage.message(), is(messageBytes));
        }
    } finally {
        context.term();
    }
}

From source file:org.apache.storm.StormSubmitter.java

/**
 * Submits a topology to run on the cluster with a progress bar. A topology runs forever or until
 * explicitly killed.//from  w ww .  ja v  a  2  s  .  c om
 *
 *
 * @param name the name of the storm.
 * @param topoConf the topology-specific configuration. See {@link Config}.
 * @param topology the processing to execute.
 * @param opts to manipulate the starting of the topology
 * @throws AlreadyAliveException if a topology with this name is already running
 * @throws InvalidTopologyException if an invalid topology was submitted
 * @throws AuthorizationException if authorization is failed
 * @thorws SubmitterHookException if any Exception occurs during initialization or invocation of registered {@link ISubmitterHook}
 */
public static void submitTopologyWithProgressBar(String name, Map<String, Object> topoConf,
        StormTopology topology, SubmitOptions opts)
        throws AlreadyAliveException, InvalidTopologyException, AuthorizationException {
    // show a progress bar so we know we're not stuck (especially on slow connections)
    submitTopology(name, topoConf, topology, opts, new StormSubmitter.ProgressListener() {
        @Override
        public void onStart(String srcFile, String targetFile, long totalBytes) {
            System.out.printf("Start uploading file '%s' to '%s' (%d bytes)\n", srcFile, targetFile,
                    totalBytes);
        }

        @Override
        public void onProgress(String srcFile, String targetFile, long bytesUploaded, long totalBytes) {
            int length = 50;
            int p = (int) ((length * bytesUploaded) / totalBytes);
            String progress = StringUtils.repeat("=", p);
            String todo = StringUtils.repeat(" ", length - p);

            System.out.printf("\r[%s%s] %d / %d", progress, todo, bytesUploaded, totalBytes);
        }

        @Override
        public void onCompleted(String srcFile, String targetFile, long totalBytes) {
            System.out.printf("\nFile '%s' uploaded to '%s' (%d bytes)\n", srcFile, targetFile, totalBytes);
        }
    });
}

From source file:org.apache.taglibs.string.util.StringW.java

/**
 * Word-wrap a string./*from  www .  j  a  va 2  s. c  o  m*/
 * 
 * @param str
 *          String to word-wrap
 * @param width
 *          int to wrap at
 * @param delim
 *          String to use to separate lines
 * @param split
 *          String to use to split a word greater than width long
 * @param delimInside
 *          wheter or not delim should be included in chunk before length reaches width.
 * 
 * @return String that has been word wrapped
 */
static public String wordWrap(String str, int width, String delim, String split, boolean delimInside) {
    int sz = str.length();

    // System.err.println( ">>>> inside: " + delimInside + " sz : " + sz );

    // / shift width up one. mainly as it makes the logic easier
    width++;

    // our best guess as to an initial size
    StringBuffer buffer = new StringBuffer(sz / width * delim.length() + sz);

    // every line might include a delim on the end
    // System.err.println( "width before: "+ width );
    if (delimInside) {
        width = width - delim.length();
    } else {
        width--;
    }
    // System.err.println( "width after: "+ width );

    int idx = -1;
    String substr = null;

    // beware: i is rolled-back inside the loop
    for (int i = 0; i < sz; i += width) {

        // on the last line
        if (i > sz - width) {
            buffer.append(str.substring(i));
            // System.err.print("LAST-LINE: "+str.substring(i));
            break;
        }

        // System.err.println("loop[i] is: "+i);
        // the current line
        substr = str.substring(i, i + width);
        // System.err.println( "substr: " + substr );

        // is the delim already on the line
        idx = substr.indexOf(delim);
        // System.err.println( "i: " + i + " idx : " + idx );
        if (idx != -1) {
            buffer.append(substr.substring(0, idx));
            // System.err.println("Substr: '"substr.substring(0,idx)+"'");
            buffer.append(delim);
            i -= width - idx - delim.length();

            // System.err.println("loop[i] is now: "+i);
            // System.err.println("ounfd-whitespace: '"+substr.charAt(idx+1)+"'.");
            // Erase a space after a delim. Is this too obscure?
            if (substr.length() > idx + 1) {
                if (substr.charAt(idx + 1) != '\n') {
                    if (Character.isWhitespace(substr.charAt(idx + 1))) {
                        i++;
                    }
                }
            }
            // System.err.println("i -= "+width+"-"+idx);
            continue;
        }

        idx = -1;

        // figure out where the last space is
        char[] chrs = substr.toCharArray();
        for (int j = width; j > 0; j--) {
            if (Character.isWhitespace(chrs[j - 1])) {
                idx = j;
                // System.err.println("Found whitespace: "+idx);
                break;
            }
        }

        // idx is the last whitespace on the line.
        // System.err.println("idx is "+idx);
        if (idx == -1) {
            for (int j = width; j > 0; j--) {
                if (chrs[j - 1] == '-') {
                    idx = j;
                    // System.err.println("Found Dash: "+idx);
                    break;
                }
            }
            if (idx == -1) {
                buffer.append(substr);
                buffer.append(delim);
                // System.err.print(substr);
                // System.err.print(delim);
            } else {
                if (idx != width) {
                    idx++;
                }
                buffer.append(substr.substring(0, idx));
                buffer.append(delim);
                // System.err.print(substr.substring(0,idx));
                // System.err.print(delim);
                i -= width - idx;
            }
        } else {
            /*
             * if(force) { if(idx == width-1) { buffer.append(substr); buffer.append(delim); } else { //
             * stick a split in. int splitsz = split.length();
             * buffer.append(substr.substring(0,width-splitsz)); buffer.append(split);
             * buffer.append(delim); i -= splitsz; } } else {
             */
            // insert spaces
            buffer.append(substr.substring(0, idx));
            buffer.append(StringUtils.repeat(" ", width - idx));
            // System.err.print(substr.substring(0,idx));
            // System.err.print(StringUtils.repeat(" ",width-idx));
            buffer.append(delim);
            // System.err.print(delim);
            // System.err.println("i -= "+width+"-"+idx);
            i -= width - idx;
            // }
        }
    }
    // System.err.println("\n*************");
    return buffer.toString();
}

From source file:org.apache.tajo.cli.tools.TajoAdmin.java

private void processList(Writer writer) throws ParseException, IOException, ServiceException, SQLException {

    List<BriefQueryInfo> queryList = tajoClient.getRunningQueryList();
    SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
    StringBuilder builder = new StringBuilder();

    /* print title */
    builder.append(StringUtils.rightPad("QueryId", 21));
    builder.append(StringUtils.rightPad("State", 20));
    builder.append(StringUtils.rightPad("StartTime", 20));
    builder.append(StringUtils.rightPad("Query", 30)).append("\n");

    builder.append(StringUtils.rightPad(StringUtils.repeat("-", 20), 21));
    builder.append(StringUtils.rightPad(StringUtils.repeat("-", 19), 20));
    builder.append(StringUtils.rightPad(StringUtils.repeat("-", 19), 20));
    builder.append(StringUtils.rightPad(StringUtils.repeat("-", 29), 30)).append("\n");
    writer.write(builder.toString());/*from   ww  w .j a va  2s  . co m*/

    builder = new StringBuilder();
    for (BriefQueryInfo queryInfo : queryList) {
        builder.append(StringUtils.rightPad(new QueryId(queryInfo.getQueryId()).toString(), 21));
        builder.append(StringUtils.rightPad(queryInfo.getState().name(), 20));
        builder.append(StringUtils.rightPad(df.format(queryInfo.getStartTime()), 20));
        builder.append(StringUtils.abbreviate(queryInfo.getQuery(), 30)).append("\n");
    }
    writer.write(builder.toString());
}

From source file:org.apache.tajo.client.TajoAdmin.java

private void processList(Writer writer) throws ParseException, IOException, ServiceException, SQLException {
    tajoClient = TajoHAClientUtil.getTajoClient(tajoConf, tajoClient);
    List<BriefQueryInfo> queryList = tajoClient.getRunningQueryList();
    SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT);
    StringBuilder builder = new StringBuilder();

    /* print title */
    builder.append(StringUtils.rightPad("QueryId", 21));
    builder.append(StringUtils.rightPad("State", 20));
    builder.append(StringUtils.rightPad("StartTime", 20));
    builder.append(StringUtils.rightPad("Query", 30)).append("\n");

    builder.append(StringUtils.rightPad(StringUtils.repeat("-", 20), 21));
    builder.append(StringUtils.rightPad(StringUtils.repeat("-", 19), 20));
    builder.append(StringUtils.rightPad(StringUtils.repeat("-", 19), 20));
    builder.append(StringUtils.rightPad(StringUtils.repeat("-", 29), 30)).append("\n");
    writer.write(builder.toString());// w  ww.ja v  a2  s . c  om

    builder = new StringBuilder();
    for (BriefQueryInfo queryInfo : queryList) {
        builder.append(StringUtils.rightPad(new QueryId(queryInfo.getQueryId()).toString(), 21));
        builder.append(StringUtils.rightPad(queryInfo.getState().name(), 20));
        builder.append(StringUtils.rightPad(df.format(queryInfo.getStartTime()), 20));
        builder.append(StringUtils.abbreviate(queryInfo.getQuery(), 30)).append("\n");
    }
    writer.write(builder.toString());
}

From source file:org.apache.tajo.engine.query.exception.SQLParseError.java

private String getDetailedMessageWithLocation() {
    StringBuilder sb = new StringBuilder();
    int displayLimit = 80;
    String queryPrefix = "LINE " + line + ":" + charPositionInLine + " ";
    String prefixPadding = StringUtils.repeat(" ", queryPrefix.length());
    String locationString;// w w  w . java  2s  .  c  o  m

    int tokenLength = offendingToken.getStopIndex() - offendingToken.getStartIndex() + 1;
    if (tokenLength > 0) {
        locationString = StringUtils.repeat(" ", charPositionInLine) + StringUtils.repeat("^", tokenLength);
    } else {
        locationString = StringUtils.repeat(" ", charPositionInLine) + "^";
    }

    sb.append("ERROR: ").append(header).append("\n");
    sb.append(queryPrefix);

    if (errorLine.length() > displayLimit) {
        int padding = (displayLimit / 2);

        String ellipsis = " ... ";
        int startPos = locationString.length() - padding - 1;
        if (startPos <= 0) {
            startPos = 0;
            sb.append(errorLine.substring(startPos, displayLimit)).append(ellipsis).append("\n");
            sb.append(prefixPadding).append(locationString);
        } else if (errorLine.length() - (locationString.length() + padding) <= 0) {
            startPos = errorLine.length() - displayLimit - 1;
            sb.append(ellipsis).append(errorLine.substring(startPos)).append("\n");
            sb.append(prefixPadding).append(locationString.substring(startPos - ellipsis.length()));
        } else {
            sb.append(ellipsis).append(errorLine.substring(startPos, startPos + displayLimit)).append(ellipsis)
                    .append("\n");
            sb.append(prefixPadding).append(locationString.substring(startPos - ellipsis.length()));
        }
    } else {
        sb.append(errorLine).append("\n");
        sb.append(prefixPadding).append(locationString);
    }
    return sb.toString();
}

From source file:org.apache.tajo.parser.sql.SQLParseError.java

private String getDetailedMessageWithLocation() {
    StringBuilder sb = new StringBuilder();
    int displayLimit = 80;
    String queryPrefix = "LINE " + line + ":" + " ";
    String prefixPadding = StringUtils.repeat(" ", queryPrefix.length());
    String locationString;/*  w w  w  .  j  a  v a 2 s. c  o  m*/

    int tokenLength = offendingToken.getStopIndex() - offendingToken.getStartIndex() + 1;
    if (tokenLength > 0) {
        locationString = StringUtils.repeat(" ", charPositionInLine) + StringUtils.repeat("^", tokenLength);
    } else {
        locationString = StringUtils.repeat(" ", charPositionInLine) + "^";
    }

    sb.append("ERROR: ").append(header).append("\n");
    sb.append(queryPrefix);

    if (errorLine.length() > displayLimit) {
        int padding = (displayLimit / 2);

        String ellipsis = " ... ";
        int startPos = locationString.length() - padding - 1;
        if (startPos <= 0) {
            startPos = 0;
            sb.append(errorLine.substring(startPos, displayLimit)).append(ellipsis).append("\n");
            sb.append(prefixPadding).append(locationString);
        } else if (errorLine.length() - (locationString.length() + padding) <= 0) {
            startPos = errorLine.length() - displayLimit - 1;
            sb.append(ellipsis).append(errorLine.substring(startPos)).append("\n");
            sb.append(prefixPadding).append(StringUtils.repeat(" ", ellipsis.length()))
                    .append(locationString.substring(startPos));
        } else {
            sb.append(ellipsis).append(errorLine.substring(startPos, startPos + displayLimit)).append(ellipsis)
                    .append("\n");
            sb.append(prefixPadding).append(StringUtils.repeat(" ", ellipsis.length()))
                    .append(locationString.substring(startPos));
        }
    } else {
        sb.append(errorLine).append("\n");
        sb.append(prefixPadding).append(locationString);
    }
    return sb.toString();
}

From source file:org.apache.tez.runtime.library.common.sort.impl.dflt.TestDefaultSorter.java

@Test
@Ignore//w  w  w .  j  a v a 2s . c  o  m
/**
 * Disabling this, as this would need 2047 MB io.sort.mb for testing.
 * Provide > 2GB to JVM when running this test to avoid OOM in string generation.
 *
 * Set DefaultSorter.MAX_IO_SORT_MB = 2047 for running this.
 */
public void testSortLimitsWithLargeRecords() throws IOException {
    OutputContext context = createTezOutputContext();

    doReturn(2800 * 1024 * 1024l).when(context).getTotalMemoryAvailableToTask();

    //Setting IO_SORT_MB to 2047 MB
    conf.setInt(TezRuntimeConfiguration.TEZ_RUNTIME_IO_SORT_MB, 2047);
    context.requestInitialMemory(
            ExternalSorter.getInitialMemoryRequirement(conf, context.getTotalMemoryAvailableToTask()),
            new MemoryUpdateCallbackHandler());

    DefaultSorter sorter = new DefaultSorter(context, conf, 2, 2047 << 20);

    int i = 0;
    /**
     * If io.sort.mb is not capped to 1800, this would end up throwing
     * "java.lang.ArrayIndexOutOfBoundsException" after many spills.
     * Intentionally made it as infinite loop.
     */
    while (true) {
        Text key = new Text(i + "");
        //Generate random size between 1 MB to 100 MB.
        int valSize = ThreadLocalRandom.current().nextInt(1 * 1024 * 1024, 100 * 1024 * 1024);
        String val = StringInterner.weakIntern(StringUtils.repeat("v", valSize));
        sorter.write(key, new Text(val));
        i = (i + 1) % 10;
    }
}

From source file:org.apereo.portal.xml.stream.IndentingXMLEventWriter.java

/** Note that a document was ended. */
protected void afterEndDocument() {
    depth = 0;/*from  w  ww.j av  a 2  s .  c om*/
    final Set<StackState> state = scopeState.getFirst();
    if (state.contains(StackState.WROTE_MARKUP) && !state.contains(StackState.WROTE_DATA)) { // but not data
        try {
            final String indent = getLineSeparator() + StringUtils.repeat("  ", 0);
            final Characters indentEvent = xmlEventFactory.createCharacters(indent);
            wrappedWriter.add(indentEvent);
        } catch (Exception ignored) {
        }
    }
    scopeState.clear();
    scopeState.push(EnumSet.noneOf(StackState.class)); // start fresh
}

From source file:org.apereo.portal.xml.stream.IndentingXMLEventWriter.java

/**
 * Generate an indentation string for the specified depth and indent size
 *//*from  w ww . jav a2s . c o m*/
protected String getIndent(int depth, int size) {
    final int length = depth * size;
    String indent = indentCache.get(length);
    if (indent == null) {
        indent = getLineSeparator() + StringUtils.repeat(" ", length);
        indentCache.put(length, indent);
    }
    return indent;
}