Java Code Examples for com.google.common.base.Strings#repeat()

The following examples show how to use com.google.common.base.Strings#repeat() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LegacyFormatUtils.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String dashedChatMessage(
    String message, String dash, String dashPrefix, String messagePrefix) {
  message = " " + message + " ";
  int dashCount =
      (GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH - ChatColor.stripColor(message).length() - 2)
          / (dash.length() * 2);
  String dashes = dashCount >= 0 ? Strings.repeat(dash, dashCount) : "";

  StringBuffer builder = new StringBuffer();
  if (dashCount > 0) {
    builder.append(dashPrefix).append(dashes).append(ChatColor.RESET);
  }

  if (messagePrefix != null) {
    builder.append(messagePrefix);
  }

  builder.append(message);

  if (dashCount > 0) {
    builder.append(ChatColor.RESET).append(dashPrefix).append(dashes);
  }

  return builder.toString();
}
 
Example 2
Source File: ShortExceptionFormatter.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void printException(TestDescriptor descriptor, Throwable exception, boolean cause, int indentLevel, StringBuilder builder) {
    String indent = Strings.repeat(INDENT, indentLevel);
    builder.append(indent);
    if (cause) {
        builder.append("Caused by: ");
    }
    String className = exception instanceof PlaceholderException
            ? ((PlaceholderException) exception).getExceptionClassName() : exception.getClass().getName();
    builder.append(className);

    StackTraceFilter filter = new StackTraceFilter(new ClassMethodNameStackTraceSpec(descriptor.getClassName(), null));
    List<StackTraceElement> stackTrace = filter.filter(exception);
    if (stackTrace.size() > 0) {
        StackTraceElement element = stackTrace.get(0);
        builder.append(" at ");
        builder.append(element.getFileName());
        builder.append(':');
        builder.append(element.getLineNumber());
    }
    builder.append('\n');

    if (testLogging.getShowCauses() && exception.getCause() != null) {
        printException(descriptor, exception.getCause(), true, indentLevel + 1, builder);
    }
}
 
Example 3
Source File: PlainTextScenarioWriter.java    From JGiven with Apache License 2.0 6 votes vote down vote up
private String getIntroString( List<Word> words, int depth ) {
    String intro;
    if( depth > 0 ) {
        intro = INDENT + String.format( "%" + maxFillWordLength + "s ", " " ) +
                Strings.repeat( NESTED_INDENT, depth - 1 ) + NESTED_HEADING;

        if( words.get( 0 ).isIntroWord() ) {
            intro = intro + WordUtil.capitalize( words.get( 0 ).getValue() ) + " ";
        }
    } else {
        if( words.get( 0 ).isIntroWord() ) {
            intro = INDENT + String.format( "%" + maxFillWordLength + "s ", WordUtil.capitalize( words.get( 0 ).getValue() ) );
        } else {
            intro = INDENT + String.format( "%" + maxFillWordLength + "s ", " " );
        }
    }
    return intro;
}
 
Example 4
Source File: SyntaxErrorListener.java    From SkaETL with Apache License 2.0 6 votes vote down vote up
private SyntaxException buildSyntaxException() {
    String message = "\n";

    for (Error error : errors) {
        message += formula + "\n";
        message += Strings.repeat(" ", error.charPositionInLine);
        int start = error.token.getStartIndex();
        int stop = error.token.getStopIndex();

        if (start >= 0 && stop >= 0) {
            message += Strings.repeat("^", stop - start + 1) + "\n";
        }

        message += error.msg + "\r\n";
    }
    return new SyntaxException(message);
}
 
Example 5
Source File: PairHMMLikelihoodCalculationEngineUnitTest.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider = "PcrErrorModelTestProvider", enabled = true)
public void createPcrErrorModelTest(final String repeat, final int repeatLength) {

    final PairHMMLikelihoodCalculationEngine engine = new PairHMMLikelihoodCalculationEngine((byte)0, new PairHMMNativeArguments(),
            PairHMM.Implementation.ORIGINAL, 0.0,
            PairHMMLikelihoodCalculationEngine.PCRErrorModel.CONSERVATIVE);

    final String readString = Strings.repeat(repeat, repeatLength);
    final byte[] insQuals = new byte[readString.length()];
    final byte[] delQuals = new byte[readString.length()];
    Arrays.fill(insQuals, (byte) PairHMMLikelihoodCalculationEngine.INITIAL_QSCORE);
    Arrays.fill(delQuals, (byte) PairHMMLikelihoodCalculationEngine.INITIAL_QSCORE);

    engine.applyPCRErrorModel(readString.getBytes(), insQuals, delQuals);

    for ( int i = 1; i < insQuals.length; i++ ) {

        final int repeatLengthFromCovariate = PairHMMLikelihoodCalculationEngine.findTandemRepeatUnits(readString.getBytes(), i-1).getRight();
        final byte adjustedScore = PairHMMLikelihoodCalculationEngine.getErrorModelAdjustedQual(repeatLengthFromCovariate, 3.0);

        Assert.assertEquals(insQuals[i - 1], adjustedScore);
        Assert.assertEquals(delQuals[i - 1], adjustedScore);
    }
}
 
Example 6
Source File: MetadataUtils.java    From parquet-mr with Apache License 2.0 5 votes vote down vote up
private static void showDetails(PrettyPrintWriter out, PrimitiveType type, int depth, MessageType container, List<String> cpath, boolean showOriginalTypes) {
  String name = Strings.repeat(".", depth) + type.getName();
  Repetition rep = type.getRepetition();
  PrimitiveTypeName ptype = type.getPrimitiveTypeName();

  out.format("%s: %s %s", name, rep, ptype);
  if (showOriginalTypes) {
    OriginalType otype;
    try {
      otype = type.getOriginalType();
    } catch (Exception e) {
      otype = null;
    }
    if (otype != null) out.format(" O:%s", otype);
  } else {
    LogicalTypeAnnotation ltype = type.getLogicalTypeAnnotation();
    if (ltype != null) out.format(" L:%s", ltype);
  }

  if (container != null) {
    cpath.add(type.getName());
    String[] paths = cpath.toArray(new String[0]);
    cpath.remove(cpath.size() - 1);

    ColumnDescriptor desc = container.getColumnDescription(paths);

    int defl = desc.getMaxDefinitionLevel();
    int repl = desc.getMaxRepetitionLevel();
    out.format(" R:%d D:%d", repl, defl);
  }
  out.println();
}
 
Example 7
Source File: HealthModule.java    From spark with GNU General Public License v3.0 5 votes vote down vote up
private static TextComponent generateDiskUsageDiagram(double used, double max, int length) {
    int usedChars = (int) ((used * length) / max);
    String line = Strings.repeat("/", usedChars) + Strings.repeat(" ", length - usedChars);
    return TextComponent.builder("")
            .append(TextComponent.of("[", TextColor.DARK_GRAY))
            .append(TextComponent.of(line, TextColor.GRAY))
            .append(TextComponent.of("]", TextColor.DARK_GRAY))
            .build();
}
 
Example 8
Source File: ShellToolAbstractTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(groups = {"Integration"})
public void testExecScriptBigCommand() throws Exception {
    String bigstring = Strings.repeat("a", 10000);
    String out = execScript("echo "+bigstring);
    
    assertTrue(out.contains(bigstring), "out="+out);
}
 
Example 9
Source File: MailboxManagerTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
void renamingMailboxShouldNotFailWhenLimitNameLength() throws Exception {
    MailboxSession session = mailboxManager.createSystemSession(USER_1);

    String mailboxName = Strings.repeat("a", MailboxManager.MAX_MAILBOX_NAME_LENGTH);

    MailboxPath originPath = MailboxPath.forUser(USER_1, "origin");
    mailboxManager.createMailbox(originPath, session);

    assertThatCode(() -> mailboxManager.renameMailbox(originPath, MailboxPath.forUser(USER_1, mailboxName), session))
        .doesNotThrowAnyException();
}
 
Example 10
Source File: MessageTest.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTruncateMessage() {
    final String suffix = " [truncated to 100000 characters]";
    String longString = Strings.repeat("a", 100000);
    ReadableMessage message = (ReadableMessage) Message.create("{}", longString + "a");
    assertThat(message.getText()).isEqualTo(longString + suffix);
}
 
Example 11
Source File: MessageTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void publishMessageApplicationHeaders() throws Exception
{
    final String stringPropValue = "mystring";
    final String longStringPropValue = Strings.repeat("*", 256);
    final Map<String, Object> headers = new HashMap<>();
    headers.put("stringprop", stringPropValue);
    headers.put("longstringprop", longStringPropValue);
    headers.put("intprop", Integer.MIN_VALUE);
    headers.put("longprop", Long.MAX_VALUE);
    headers.put("boolprop", Boolean.TRUE);

    final Map<String, Object> messageBody = new HashMap<>();
    messageBody.put("address", QUEUE_NAME);
    messageBody.put("headers", headers);

    getHelper().submitRequest("virtualhost/publishMessage",
                              "POST",
                              Collections.singletonMap("message", messageBody),
                              SC_OK);

    Connection connection = getConnection();
    try
    {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = session.createQueue(QUEUE_NAME);
        MessageConsumer consumer = session.createConsumer(queue);
        Message message = consumer.receive(getReceiveTimeout());
        assertThat(message, is(notNullValue()));
        assertThat(message.getStringProperty("stringprop"), is(equalTo(stringPropValue)));
        assertThat(message.getIntProperty("intprop"), is(equalTo(Integer.MIN_VALUE)));
        assertThat(message.getLongProperty("longprop"), is(equalTo(Long.MAX_VALUE)));
        assertThat(message.getBooleanProperty("boolprop"), is(equalTo(Boolean.TRUE)));
    }
    finally
    {
        connection.close();
    }
}
 
Example 12
Source File: TestRestVertxTransportConfig.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
/**
 * Max initial line length is set to 5000
 */
@Test
public void testMaxInitialLineLength5000() {
  String q = Strings.repeat("q", 5000 - INITIAL_LINE_PREFIX.length() - INITIAL_LINE_SUFFIX.length());
  String result = consumers.getIntf().testMaxInitialLineLength(q);
  Assert.assertEquals("OK", result);
}
 
Example 13
Source File: Assertions.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private String ensureArrayName(String name) {
    String suffix = "";
    Matcher matcher = ARRAY_PATTERN.matcher(name);
    if (matcher.matches()) {
        name = Type.getType(matcher.group(2)).getClassName();
        suffix = Strings.repeat("[]", matcher.group(1).length());
    }
    return name + suffix;
}
 
Example 14
Source File: JavaCommentsHelper.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
private String indentLineComments(List<String> lines, int column0) {
    lines = wrapLineComments(lines, column0, options);
    StringBuilder builder = new StringBuilder();
    builder.append(lines.get(0).trim());
    String indentString = Strings.repeat(" ", column0);
    for (int i = 1; i < lines.size(); ++i) {
        builder.append(lineSeparator).append(indentString).append(lines.get(i).trim());
    }
    return builder.toString();
}
 
Example 15
Source File: AbstractOutputGenerator.java    From servicecomb-samples with Apache License 2.0 4 votes vote down vote up
protected static String generateFmt(int leftPad, int keyLen) {
  return Strings.repeat(" ", leftPad) + "%-" + keyLen + "s: %s\n";
}
 
Example 16
Source File: SqlFormatter.java    From rainbow with Apache License 2.0 4 votes vote down vote up
private static String indentString(int indent)
{
    return Strings.repeat(INDENT, indent);
}
 
Example 17
Source File: TranslateGroupManuallyPanel.java    From BigStitcher with GNU General Public License v2.0 4 votes vote down vote up
public static String padLeft(String in, int minLength)
{
	return Strings.repeat( " ", (int) Math.max( minLength - in.length(), 0 ) ) + in;
}
 
Example 18
Source File: NestableCallAspect.java    From glowroot with Apache License 2.0 4 votes vote down vote up
@OnBefore
public static TraceEntry onBefore(OptionalThreadContext context) {
    int count = counter.getAndIncrement();
    String transactionName;
    String headline;
    if (random.nextBoolean()) {
        transactionName = "Nestable with a very long trace headline";
        headline = "Nestable with a very long trace headline to test wrapping"
                + " abcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz";
    } else {
        transactionName =
                Strings.repeat(String.valueOf((char) ('a' + random.nextInt(26))), 40);
        headline = transactionName;
    }
    if (random.nextInt(10) == 0) {
        // create a long-tail of transaction names to simulate long-tail of urls
        transactionName += random.nextInt(1000);
    }
    TraceEntry traceEntry;
    if (count % 10 == 0) {
        traceEntry = context.startTransaction("Background", transactionName,
                getRootMessageSupplier(headline), timerName);
    } else {
        traceEntry = context.startTransaction("Sandbox", transactionName,
                getRootMessageSupplier(headline), timerName);
    }
    int index = count % (USERS.size() + 1);
    if (index < USERS.size()) {
        context.setTransactionUser(USERS.get(index), Priority.USER_PLUGIN);
    } else {
        context.setTransactionUser(null, Priority.USER_PLUGIN);
    }
    if (random.nextBoolean()) {
        context.addTransactionAttribute("My First Attribute", "hello world");
        context.addTransactionAttribute("My First Attribute", "hello world");
        context.addTransactionAttribute("My First Attribute",
                "hello world " + random.nextInt(10));
    }
    if (random.nextBoolean()) {
        context.addTransactionAttribute("Second", "val " + random.nextInt(10));
    }
    if (random.nextBoolean()) {
        context.addTransactionAttribute("A Very Long Attribute Value",
                Strings.repeat("abcdefghijklmnopqrstuvwxyz", 3));
    }
    if (random.nextBoolean()) {
        context.addTransactionAttribute("Another",
                "a b c d e f g h i j k l m n o p q r s t u v w x y z"
                        + " a b c d e f g h i j k l m n o p q r s t u v w x y z");
    }
    return traceEntry;
}
 
Example 19
Source File: SignaturePrinter.java    From Mixin with MIT License 4 votes vote down vote up
private static String arraySuffix(Type type) {
    return Strings.repeat("[]", type.getDimensions());
}
 
Example 20
Source File: StringHelper.java    From cuba with Apache License 2.0 3 votes vote down vote up
/**
 * Wraps the given string into two lines containing "=" symbols. The length of the lines is calculated to be equal
 * to maximum length of the enclosed lines.
 * <p>For example:
 * <pre>
 *     ===============
 *     Some line
 *     Some other line
 *     ===============
 * </pre>
 */
public static String wrapLogMessage(String message) {
    int length = Splitter.on("\n").splitToList(message).stream()
            .mapToInt(String::length)
            .max().orElse(0);
    return "\n" + Strings.repeat("=", length) + '\n'
            + message + '\n'
            + Strings.repeat("=", length);
}