List of usage examples for com.google.common.base Strings repeat
public static String repeat(String string, int count)
From source file:io.github.aritzhack.aritzh.logging.LogFormatter.java
public static String formatLogMessage(@NotNull LogLevel level, @NotNull String format, @Nullable String message, @Nullable Throwable t, @Nullable String loggerName) { boolean inCondition = false; boolean conditionMet = false; StringBuilder out = new StringBuilder(); char[] chars = format.toCharArray(); for (int i = 0; i < chars.length; i++) { boolean notLast = i < chars.length - 1; char c = chars[i]; // Check for ending the condition environment if (inCondition && c == DELIMITER_RIGHT) { inCondition = false;/*from ww w.j a va2 s .c om*/ conditionMet = false; continue; } // Skip if the condition is unmet if (inCondition && !conditionMet) continue; if (c == BEGIN_TOKEN && notLast) { // Check if we are in a replace-token i++; c = chars[i]; switch (c) { case BEGIN_TOKEN: out.append(BEGIN_TOKEN); break; case TOKEN_MESSAGE: out.append(message); break; case TOKEN_DATE: if (notLast && chars[i + 1] == DELIMITER_LEFT) { i++; String dFormat = ""; while (i < chars.length - 1) { i++; c = chars[i]; if (c == DELIMITER_RIGHT) break; dFormat += c; } if (!dateFormats.containsKey(dFormat)) { dateFormats.put(dFormat, new SimpleDateFormat(dFormat)); } out.append(dateFormats.get(dFormat).format(new Date())); } else { out.append(DF.format(new Date())); } break; case TOKEN_LEVEL: out.append(level.name()); break; case TOKEN_FULL_LEVEL: out.append("[").append(level.name()).append("]"); out.append(Strings.repeat(" ", LogLevel.maxNameLength - level.name().length())); break; case TOKEN_THROWABLE: if (t != null) { out.append(Throwables.getStackTraceAsString(t)); } break; case TOKEN_THREAD: out.append(Thread.currentThread().getName()); break; case TOKEN_NAME: out.append(loggerName); break; } } else if (c == BEGIN_CONDITION) { // Check if we are starting a condition environment inCondition = true; // Read the condition String condition = ""; while (i < chars.length - 1) { // Safe-check not to get an ArrayIndexOutOfBoundsException i++; c = chars[i]; if (c == DELIMITER_LEFT) break; // If we reach the beginning if the environment, stop condition += c; } // Parse the condition if (condition.equalsIgnoreCase(toS(TOKEN_THROWABLE))) { conditionMet = t != null; } else if (condition.startsWith(toS(TOKEN_LEVEL)) || condition.startsWith(toS(TOKEN_FULL_LEVEL))) { String cLevel = condition.substring(1); conditionMet = LogLevel.getLevel(cLevel) == level; } else if (condition.equalsIgnoreCase(toS(TOKEN_MESSAGE))) { conditionMet = !Strings.isNullOrEmpty(message); } else if (condition.equalsIgnoreCase(toS(TOKEN_NAME))) { conditionMet = !Strings.isNullOrEmpty(loggerName); } } else { out.append(c); } } return out.toString(); }
From source file:de.cau.cs.kieler.klay.layered.JsonDebugUtil.java
/** * Writes a debug graph for the given linear segments and their * dependencies./*from w w w .j a v a2 s . c om*/ * * @param layeredGraph * the layered graph. * @param segmentList * the list of linear segments. * @param outgoingList * the list of successors for each linear segment. */ public static void writeDebugGraph(final LGraph layeredGraph, final List<LinearSegment> segmentList, final List<List<LinearSegment>> outgoingList) { try { final ConsoleWriter ConsoleWriter = createConsoleWriter(layeredGraph); beginGraph(ConsoleWriter, layeredGraph); final String indent1 = Strings.repeat(INDENT, 2); final String indent2 = Strings.repeat(INDENT, 3); // SUPPRESS // CHECKSTYLE // MagicNumber int edgeId = 0; final Iterator<LinearSegment> segmentIterator = segmentList.iterator(); final Iterator<List<LinearSegment>> successorsIterator = outgoingList.iterator(); final StringBuffer edges = new StringBuffer(); while (segmentIterator.hasNext()) { final LinearSegment segment = segmentIterator.next(); ConsoleWriter.write("\n" + indent1 + "{\n" + indent2 + "\"id\": \"n" + segment.hashCode() + "\",\n" + indent2 + "\"labels\": [ { \"text\": \"" + segment + "\" } ],\n" + indent2 + "\"width\": 50,\n" + indent2 + "\"height\": 25\n" + indent1 + "}"); if (segmentIterator.hasNext()) { ConsoleWriter.write(","); } final Iterator<LinearSegment> succIterator = successorsIterator.next().iterator(); while (succIterator.hasNext()) { final LinearSegment successor = succIterator.next(); edges.append("\n" + indent1 + "{\n" + indent2 + "\"id\": \"e" + edgeId++ + "\",\n" + indent2 + "\"source\": \"n" + segment.hashCode() + "\",\n" + indent2 + "\"target\": \"n" + successor.hashCode() + "\",\n" + indent1 + "},"); } } endChildNodeList(ConsoleWriter); if (edges.length() > 0) { edges.deleteCharAt(edges.length() - 1); } ConsoleWriter.write(INDENT + "\"edges\": [" + edges + "\n" + indent1 + "]"); endGraph(ConsoleWriter); } catch (final Exception exception) { exception.printStackTrace(); } }
From source file:com.spotify.helios.cli.Utils.java
public static <K extends Comparable<K>, V> void printMap(final PrintStream out, final String name, final Function<V, String> transform, final Map<K, V> values) { out.print(name);/*from w w w . j a v a2 s . c o m*/ boolean first = true; for (final K key : Ordering.natural().sortedCopy(values.keySet())) { if (!first) { out.print(Strings.repeat(" ", name.length())); } final V value = values.get(key); out.printf("%s=%s%n", key, transform.apply(value)); first = false; } if (first) { out.println(); } }
From source file:suneido.database.immudb.BtreeNode.java
void print(Writer w, Storage stor) throws IOException { String indent = Strings.repeat(" ", level); w.append(indent).append(printName() + " level " + level + "\n"); for (int i = 0; i < size(); ++i) { BtreeKey slot = get(i);//from w w w . j a v a2 s . co m w.append(indent).append(slot.toString()).append("\n"); if (level > 0) childNode(stor, i).print(w, stor); } }
From source file:org.nla.tarotdroid.biz.helpers.UrlHelper.java
/** * Generate url of image on google charts. * Check https://developers.google.com/chart/image/docs/chart_params to learn about the parameters * Check http://imagecharteditor.appspot.com/ to generate charts * @param gameSet/* ww w . ja v a 2s . co m*/ * @return */ public static String buildPictureLink(final GameSet gameSet) { StringBuffer buf = new StringBuffer(); Map<Integer, String> colorsForPlayerCount = newHashMap(); colorsForPlayerCount.put(3, "3072F3,FF0000,FF9900"); colorsForPlayerCount.put(4, "3072F3,FF0000,FF9900,15F34B"); colorsForPlayerCount.put(5, "3072F3,FF0000,FF9900,15F34B,50AA66"); colorsForPlayerCount.put(6, "3072F3,FF0000,FF9900,15F34B,50AA66,AA00FF"); int minScore = -1 * gameSet.getGameSetScores().getMaxAbsoluteScore() - 100; int maxScore = gameSet.getGameSetScores().getMaxAbsoluteScore() + 100; int gameStyleType; switch (gameSet.getGameStyleType()) { case Tarot3: gameStyleType = 3; break; case Tarot4: gameStyleType = 4; break; case Tarot5: gameStyleType = 5; break; case None: default: gameStyleType = 0; } // this bit generates a List<String> containing each player data set (ex: -1|50,75,100,75,75) IGameSetStatisticsComputer gameSetStatisticsComputer = GameSetStatisticsComputerFactory .GetGameSetStatisticsComputer(gameSet, "guava"); List<String> playerDataSets = newArrayList(); String[] playerNames = gameSetStatisticsComputer.getPlayerNames(); List<double[]> playerScores = gameSetStatisticsComputer.getScores(); for (int playerIndex = 0; playerIndex < playerNames.length; ++playerIndex) { double[] nonProjectedPlayerScores = playerScores.get(playerIndex); List<Integer> projectedPlayerScores = newArrayList(); for (Double nonProjectedScore : nonProjectedPlayerScores) { projectedPlayerScores.add(projectScoresOnChart(nonProjectedScore, minScore, maxScore)); } StringBuffer playerDataSet = new StringBuffer(); playerDataSet.append("-1|"); playerDataSet.append(Joiner.on(",").join(projectedPlayerScores)); playerDataSets.add(playerDataSet.toString()); } // each parameter value generation String chxr = MessageFormat.format("chxr=0,0,{0}|1,{1},{2}", gameSet.getGameCount(), minScore + "", maxScore + ""); String chco = MessageFormat.format("&chco={0}", colorsForPlayerCount.get(gameSet.getPlayers().size())); String chdl = MessageFormat.format("&chdl={0}", Joiner.on("|").join(playerNames)); String chls = MessageFormat.format("&chls={0}", Strings.repeat("3", gameSet.getPlayers().size()).replace("", " ").trim().replace(" ", "|")); String chd = MessageFormat.format("&chd=t:{0}", Joiner.on("|").join(playerDataSets)); String chtt = MessageFormat.format("&chtt=Tarot+a+{0}%2C+{1}+parties", gameStyleType, gameSet.getGameCount()); // final url generation buf.append("http://chart.googleapis.com/chart?"); buf.append(chxr); //chxr => x axis goes from 0 to {0} games, y axis goes from {1} to {2} points buf.append("&chxs=0,676767,13,0,_,676767|1,676767,13,0,_,676767"); //chxs => x and y axis propoerties and styles buf.append("&chxt=x,y"); //chs => x and y axis displayed buf.append("&chs=600x400"); //chs => image resolution buf.append("&cht=lxy"); // cht => chart type line xy buf.append(chco); // chco => colors of player lines //buf.append("&chds=-10,100,0,100,-20,100,0,100"); // chds => ? but apparently useless for lxy buf.append(chd); // chd => series of payer scores buf.append(chdl); // chdl => legends buf.append("&chdlp=r"); // chdlp => legend at the right of the chart buf.append("&chg=0,10,5,2"); // chg => grid properties => only horizontal dashed lines buf.append(chls); // chls => line styles => no dash, 3 in thickness buf.append("&chma=5,5,5,25"); // chma => margins buf.append(chtt); // chtt => title, {0} is gameStyleType, {1} is game count return buf.toString(); }
From source file:google.registry.tools.VerifyOteCommand.java
@Override public void run() throws IOException { if (RegistryEnvironment.get() != RegistryEnvironment.SANDBOX) { System.err.printf(/*from www . j a va2 s . c om*/ "WARNING: Running against %s environment. Are " + "you sure you didn\'t mean to run this against sandbox (e.g. \"-e SANDBOX\")?%n", RegistryEnvironment.get()); } checkArgument(mainParameters.isEmpty() == checkAll, "Must provide at least one registrar name, or supply --check-all with no names."); for (String clientId : mainParameters) { // OT&E registrars are created with clientIDs of registrarName-[1-4], but this command is // passed registrarName. So check the existence of the first persisted registrar to see if // the input is valid. verifyNotNull(loadByClientId(clientId + "-1"), "Registrar %s does not exist.", clientId); } Collection<String> registrars = mainParameters.isEmpty() ? getAllRegistrarNames() : mainParameters; Map<String, Object> response = connection.sendJson(VerifyOteAction.PATH, ImmutableMap.of("summarize", Boolean.toString(summarize), "registrars", new ArrayList<>(registrars))); System.out.println(Strings.repeat("-", 80)); for (Entry<String, Object> registrar : response.entrySet()) { System.out.printf(summarize ? "%-20s - %s\n" : "\n=========== %s OT&E status ============\n%s\n", registrar.getKey(), registrar.getValue()); } System.out.println(Strings.repeat("-", 80)); }
From source file:com.google.api.codegen.util.ruby.RubyCommentReformatter.java
@Override public String reformat(String comment) { StringBuffer sb = new StringBuffer(); int listIndent = 0; boolean followsListItem = false; boolean followsBlankLine = false; for (String line : Splitter.on("\n").split(comment)) { Matcher listMatcher = CommentPatterns.UNORDERED_LIST_PATTERN.matcher(line); boolean matchesList = listMatcher.lookingAt(); Matcher indentMatcher = CommentPatterns.INDENT_PATTERN.matcher(line); indentMatcher.lookingAt();// ww w.j a v a 2 s .c o m int indent = indentMatcher.group().length(); if (matchesList) { line = listMatcher.replaceFirst(BULLET); } if (indent < listIndent && (matchesList || followsBlankLine)) { listIndent -= BULLET.length(); } else if (followsListItem && (!matchesList || indent > listIndent)) { listIndent += BULLET.length(); } if (listIndent > 0) { line = line.trim(); sb.append(Strings.repeat(" ", listIndent)); } sb.append(transformer.transform(line)).append("\n"); followsListItem = matchesList; followsBlankLine = line.isEmpty(); } return sb.toString().trim(); }
From source file:com.github.rinde.logistics.pdptw.solver.optaplanner.ScoreCalculator.java
static String asString(Object entity, String variableName) { final StringBuilder sb = new StringBuilder().append(entity).append(" \tvariable: ").append(variableName) .append(Strings.repeat(" ", ParcelVisit.PREV_VISIT.length() - variableName.length())) .append(" \tvalue: "); if (variableName.equals(NEXT_VISIT)) { sb.append(((Visit) entity).getNextVisit()); } else if (variableName.equals(ParcelVisit.PREV_VISIT)) { sb.append(((ParcelVisit) entity).getPreviousVisit()); } else if (variableName.equals(VEHICLE)) { sb.append(((ParcelVisit) entity).getVehicle()); }//from www. j a v a 2 s. co m return sb.toString(); }
From source file:com.zimbra.cs.index.query.ItemQuery.java
@Override public void sanitizedDump(StringBuilder out) { out.append("ITEMID"); if (isAllQuery) { out.append(",all"); } else if (isNoneQuery) { out.append(",none"); } else {// ww w. j a va2s . c o m out.append(Strings.repeat(",$TEXT", itemIds.size())); } }
From source file:fr.ens.biologie.genomique.eoulsan.ui.BasicUI.java
@Override public void notifyStepState(final Step step, final int terminatedTasks, final int submittedTasks, final double progress) { // Check if the UI has been initialized checkState(this.workflow != null, "The UI has not been initialized"); if (!isInteractiveMode() || step == null || step.getWorkflow() != this.workflow || step.getState() != StepState.WORKING || !this.steps.containsKey(step)) { return;// w w w . j a v a 2s . co m } final double globalProgress = computeGlobalProgress(step, progress); if (globalProgress == 0 && this.lastMessageLength == 0) { System.out.println(Globals.WELCOME_MSG); } final String msg = String.format("%.0f%% workflow done (currently process step %s #%d, %.0f%% done)", globalProgress * 100.0, step.getId(), step.getNumber(), progress * 100.0); // Clear previous message System.out.print(Strings.repeat("\r", this.lastMessageLength)); System.out.print(Strings.repeat(" ", this.lastMessageLength)); System.out.print(Strings.repeat("\r", this.lastMessageLength)); this.lastMessageLength = msg.length(); System.out.print(msg); // At the end of the workflow print \n if (globalProgress == 1.0) { System.out.println(); } System.out.flush(); }