List of usage examples for org.apache.commons.lang3 StringUtils rightPad
public static String rightPad(final String str, final int size)
Right pad a String with spaces (' ').
The String is padded to the size of size .
StringUtils.rightPad(null, *) = null StringUtils.rightPad("", 3) = " " StringUtils.rightPad("bat", 3) = "bat" StringUtils.rightPad("bat", 5) = "bat " StringUtils.rightPad("bat", 1) = "bat" StringUtils.rightPad("bat", -1) = "bat"
From source file:com.ibasco.agql.protocols.valve.source.query.handlers.SourceRconPacketDecoder.java
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { final String separator = "================================================================================================="; //TODO: Move all code logic below to SourceRconPacketBuilder log.debug(separator);// w ww .ja va2 s. c om log.debug(" ({}) DECODING INCOMING DATA : Bytes Received = {} {}", index.incrementAndGet(), in.readableBytes(), index.get() > 1 ? "[Continuation]" : ""); log.debug(separator); String desc = StringUtils.rightPad("Minimum allowable size?", PAD_SIZE); //Verify we have the minimum allowable size if (in.readableBytes() < 14) { log.debug(" [ ] {} = NO (Actual Readable Bytes: {})", desc, in.readableBytes()); return; } log.debug(" [x] {} = YES (Actual Readable Bytes: {})", desc, in.readableBytes()); //Reset if this happens to be not a valid source rcon packet in.markReaderIndex(); //Read and Verify size desc = StringUtils.rightPad("Bytes received at least => than the \"declared\" size?", PAD_SIZE); int size = in.readIntLE(); int readableBytes = in.readableBytes(); if (readableBytes < size) { log.debug(" [ ] {} = NO (Declared Size: {}, Actual Bytes Read: {})", desc, readableBytes, size); in.resetReaderIndex(); return; } log.debug(" [x] {} = YES (Declared Size: {}, Actual Bytes Read: {})", desc, readableBytes, size); //Read and verify request id desc = StringUtils.rightPad("Request Id within the valid range?", PAD_SIZE); int id = in.readIntLE(); if (!(id == -1 || id == SourceRconUtil.RCON_TERMINATOR_RID || SourceRconUtil.isValidRequestId(id))) { log.debug(" [ ] {} = NO (Actual: {})", desc, id); in.resetReaderIndex(); return; } log.debug(" [x] {} = YES (Actual: {})", desc, id); //Read and verify request type desc = StringUtils.rightPad("Valid response type?", PAD_SIZE); int type = in.readIntLE(); if (get(type) == null) { log.debug(" [ ] {} = NO (Actual: {})", desc, type); in.resetReaderIndex(); return; } log.debug(" [x] {} = YES (Actual: {} = {})", desc, type, SourceRconResponseType.get(type)); //Read and verify body desc = StringUtils.rightPad("Contains Body?", PAD_SIZE); int bodyLength = in.bytesBefore((byte) 0); String body = StringUtils.EMPTY; if (bodyLength <= 0) log.debug(" [ ] {} = NO", desc); else { body = in.readCharSequence(bodyLength, StandardCharsets.UTF_8).toString(); log.debug(" [x] {} = YES (Length: {}, Body: {})", desc, bodyLength, StringUtils.replaceAll(StringUtils.truncate(body, 30), "\n", "\\\\n")); } //Peek at the last two bytes and verify that they are null-bytes byte bodyTerminator = in.getByte(in.readerIndex()); byte packetTerminator = in.getByte(in.readerIndex() + 1); desc = StringUtils.rightPad("Contains TWO null-terminating bytes at the end?", PAD_SIZE); //Make sure the last two bytes are NULL bytes (request id: 999 is reserved for split packet responses) if ((bodyTerminator != 0 || packetTerminator != 0) && (id == SourceRconUtil.RCON_TERMINATOR_RID)) { log.debug("Skipping {} bytes", in.readableBytes()); in.skipBytes(in.readableBytes()); return; } else if (bodyTerminator != 0 || packetTerminator != 0) { log.debug(" [ ] {} = NO (Actual: Body Terminator = {}, Packet Terminator = {})", desc, bodyTerminator, packetTerminator); in.resetReaderIndex(); return; } else { log.debug(" [x] {} = YES (Actual: Body Terminator = {}, Packet Terminator = {})", desc, bodyTerminator, packetTerminator); //All is good, skip the last two bytes if (in.readableBytes() >= 2) in.skipBytes(2); } //At this point, we can now construct a packet log.debug(" [x] Status: PASS (Size = {}, Id = {}, Type = {}, Remaining Bytes = {}, Body Size = {})", size, id, type, in.readableBytes(), bodyLength); log.debug(separator); //Reset the index index.set(0); //Construct the response packet and send to the next handlers SourceRconResponsePacket responsePacket; //Did we receive a terminator packet? if (this.terminatingPacketsEnabled && id == SourceRconUtil.RCON_TERMINATOR_RID && StringUtils.isBlank(body)) { responsePacket = new SourceRconTermResponsePacket(); } else { responsePacket = SourceRconPacketBuilder.getResponsePacket(type); } if (responsePacket != null) { responsePacket.setSize(size); responsePacket.setId(id); responsePacket.setType(type); responsePacket.setBody(body); log.debug( "Decode Complete. Passing response for request id : '{}' to the next handler. Remaining bytes ({})", id, in.readableBytes()); out.add(responsePacket); } }
From source file:com.stratio.crossdata.sh.utils.ConsoleUtils.java
/** * Convert QueryResult {@link com.stratio.crossdata.common.result.QueryResult} structure to String. * * @param queryResult {@link com.stratio.crossdata.common.result.QueryResult} from execution. * @return String representing the result. *//*from w w w . jav a 2s . c o m*/ private static String stringQueryResult(QueryResult queryResult) { if ((queryResult.getResultSet() == null) || queryResult.getResultSet().isEmpty()) { return System.lineSeparator() + "0 results returned"; } ResultSet resultSet = queryResult.getResultSet(); Map<String, Integer> colWidths = calculateColWidths(resultSet); String bar = StringUtils.repeat('-', getTotalWidth(colWidths) + (colWidths.values().size() * 3) + 1); StringBuilder sb = new StringBuilder(System.lineSeparator()); sb.append("Partial result: "); sb.append(!queryResult.isLastResultSet()); sb.append(System.lineSeparator()); sb.append(bar).append(System.lineSeparator()); sb.append("| "); List<String> columnNames = new ArrayList<>(); for (ColumnMetadata columnMetadata : resultSet.getColumnMetadata()) { sb.append(StringUtils.rightPad(columnMetadata.getName().getColumnNameToShow(), colWidths.get(columnMetadata.getName().getColumnNameToShow()) + 1)).append("| "); columnNames.add(columnMetadata.getName().getColumnNameToShow()); } sb.append(System.lineSeparator()); sb.append(bar); sb.append(System.lineSeparator()); for (Row row : resultSet) { sb.append("| "); for (String columnName : columnNames) { String str = String.valueOf(row.getCell(columnName.toLowerCase()).getValue()); sb.append(StringUtils.rightPad(str, colWidths.get(columnName.toLowerCase()))); sb.append(" | "); } sb.append(System.lineSeparator()); } sb.append(bar).append(System.lineSeparator()); return sb.toString(); }
From source file:de.openali.odysseus.chart.ext.base.layer.TooltipFormatter.java
private String alignText(final String[] texts, final int i) { final String value = texts[i]; final int alignment = m_alignments[i]; if (alignment == SWT.LEFT) return StringUtils.rightPad(value, m_columnWidths[i]); else/*from w w w. j a va2 s . co m*/ return StringUtils.leftPad(value, m_columnWidths[i]); }
From source file:mase.me.MEFinalRepertoireTextStat.java
protected String toString2D(MESubpopulation sub) { StringBuilder sb = new StringBuilder(); // find the bounds of the repertoire Collection<int[]> values = new ArrayList<>(sub.inverseHash.values()); int min0 = Integer.MAX_VALUE, min1 = Integer.MAX_VALUE, max0 = Integer.MIN_VALUE, max1 = Integer.MIN_VALUE; for (int[] v : values) { min0 = Math.min(min0, v[0]); max0 = Math.max(max0, v[0]); min1 = Math.min(min1, v[1]); max1 = Math.max(max1, v[1]); }/*from www .j a v a 2 s.c o m*/ // print repertoire int pad = Math.max(Integer.toString(min1).length(), Integer.toString(max1).length()); sb.append(StringUtils.repeat(' ', pad)).append("y\n"); for (int i1 = max1; i1 >= min1; i1--) { sb.append(StringUtils.leftPad(i1 + "", pad)).append("|"); for (int i0 = min0; i0 <= max0; i0++) { int h = sub.hash(new int[] { i0, i1 }); if (sub.map.containsKey(h)) { sb.append("[]"); } else { sb.append(" "); } } sb.append("\n"); } // x-axis lines sb.append(StringUtils.repeat(' ', pad)).append('-'); for (int i0 = min0; i0 <= max0; i0++) { sb.append("--"); } sb.append(" x\n"); // x-axis numbers sb.append(StringUtils.repeat(' ', pad + 1)); int longest = Math.max(Integer.toString(min0).length(), Integer.toString(max0).length()); int space = (longest + 2) / 2 * 2; int order = 0; for (int i0 = min0; i0 <= max0; i0++) { String s = Integer.toString(i0); if (order % (space / 2) == 0) { sb.append(StringUtils.rightPad(s, space)); } order++; } sb.append('\n'); return sb.toString(); }
From source file:com.sangupta.fileanalysis.db.DBResultViewer.java
private static void format(String value, int size, boolean rightAligned) { if (rightAligned) { value = StringUtils.leftPad(value, size); } else {/* w ww. jav a2 s . c o m*/ value = StringUtils.rightPad(value, size); } System.out.print("| " + value + " "); }
From source file:net.sf.dynamicreports.examples.complex.applicationform.ApplicationFormDesign.java
private HorizontalListBuilder textCell(String text, int size) { HorizontalListBuilder list = cmp.horizontalList(); String cellText = StringUtils.rightPad(text, size); cellText = StringUtils.left(cellText, size); for (char character : cellText.toCharArray()) { TextFieldBuilder<String> cell = cmp.text(String.valueOf(character)).setStyle(cellStyle) .setFixedDimension(cellWidth, cellHeight); list.add(cell);// w w w .j av a 2 s. c o m } return list; }
From source file:mase.MaseEvolve.java
public static File writeConfig(String[] args, Map<String, String> params, File outDir, boolean replaceDirWildcard) throws IOException { File configFile = File.createTempFile("maseconfig", ".params"); // Write the parameter map into a new file BufferedWriter bw = new BufferedWriter(new FileWriter(configFile)); // Write the command line arguments in a comment bw.write("#"); for (String arg : args) { bw.write(" " + arg); }/*from ww w. j a v a 2 s . c o m*/ bw.newLine(); // Write the parameters correctly padded int maxLen = -1; for (String str : params.keySet()) { maxLen = Math.max(maxLen, str.length()); } for (Entry<String, String> e : params.entrySet()) { String value = e.getValue(); if (value.contains("$") && replaceDirWildcard) { File f = new File(outDir, value.replace("$", "")); value = f.getAbsolutePath().replace("\\", "/"); } bw.write(StringUtils.rightPad(e.getKey(), maxLen) + " = " + value); bw.newLine(); } bw.close(); return configFile; }
From source file:net.morimekta.idltool.cmd.RemoteStatus.java
/** * Show standard status for a remote./* w w w. j a v a 2s.c o m*/ * * @param first If this is the first remote to print diffs. * @param sourceSha1sums The remote file to sha1sum map. * @param targetSha1sums The local file to sha1sum map. * @return If the next remote is the first to print diffs. */ private boolean showStatus(boolean first, @Nonnull String remoteName, @Nonnull File sourceDirectory, @Nonnull Map<String, String> sourceSha1sums, @Nonnull File targetDirectory, @Nonnull Map<String, String> targetSha1sums) throws IOException { Set<String> removedFiles = new TreeSet<>(targetSha1sums.keySet()); removedFiles.removeAll(sourceSha1sums.keySet()); Set<String> addedFiles = new TreeSet<>(sourceSha1sums.keySet()); addedFiles.removeAll(targetSha1sums.keySet()); Set<String> updatedFiles = new TreeSet<>(sourceSha1sums.keySet()); updatedFiles.removeAll(addedFiles); updatedFiles = updatedFiles.stream().filter(f -> !targetSha1sums.get(f).equals(sourceSha1sums.get(f))) .collect(Collectors.toSet()); Set<String> allFiles = new TreeSet<>(); allFiles.addAll(removedFiles); allFiles.addAll(addedFiles); allFiles.addAll(updatedFiles); if (allFiles.size() == 0) { return first; } int longestName = allFiles.stream().mapToInt(String::length).max().orElse(0); int diffSeparatorLength = Math.max(72, longestName + 6 + remoteName.length()); if (!first) { System.out.println(); } System.out.println(String.format("%sUpdates on %s%s", Color.BOLD, remoteName, Color.CLEAR)); for (String file : allFiles) { String paddedFile = StringUtils.rightPad(file, longestName); File sourceFile = new File(sourceDirectory, file); File targetFile = new File(targetDirectory, file); if (diff) { System.out.println(); System.out.println(Color.DIM + Strings.times("#", diffSeparatorLength) + Color.CLEAR); paddedFile = remoteName + "/" + paddedFile; } if (removedFiles.contains(file)) { System.out.println(String.format(" %s%s%s (%sD%s)%s", Color.YELLOW, paddedFile, Color.CLEAR, Color.RED, Color.CLEAR, getDiffStats(sourceFile, targetFile))); } else if (addedFiles.contains(file)) { System.out.println(String.format(" %s%s%s (%sA%s)%s", Color.YELLOW, paddedFile, Color.CLEAR, Color.GREEN, Color.CLEAR, getDiffStats(sourceFile, targetFile))); } else { System.out.println(String.format(" %s%s%s %s", Color.YELLOW, paddedFile, Color.CLEAR, getDiffStats(sourceFile, targetFile))); } if (diff) { System.out.println(Color.DIM + Strings.times("-", diffSeparatorLength) + Color.CLEAR); printDiffLines(sourceFile, targetFile); System.out.println(Color.DIM + Strings.times("#", diffSeparatorLength) + Color.CLEAR); } } return false; }
From source file:de.micromata.genome.logging.spi.ifiles.IndexedWriter.java
private String trimFixSize(String str, int size) { if (str.length() > size) { str = str.substring(0, size);//from w ww. j a va 2s .c o m } str = StringUtils.rightPad(str, size); return str; }
From source file:de.fau.cs.osr.hddiff.perfsuite.EditScriptAnalysis.java
private Object printNodeStatsByOp(GenericEditOp needle) { HashSet<String> tmp = new HashSet<>(editsByLabel.keySet()); tmp.remove(null);/*from w ww .j av a2 s.c o m*/ LinkedList<String> keys = new LinkedList<>(tmp); Collections.sort(keys); keys.add(null); StringBuilder b = new StringBuilder(); b.append(String.format(" %s by label:\n", needle)); boolean empty = true; for (String key : keys) { int count = 0; List<Edit> ops = editsByLabel.get(key); if (ops != null) for (Edit op : ops) { if (op.op == needle) ++count; } if (count > 0) { empty = false; if (key == null) key = "#text"; String paddedKey = StringUtils.rightPad(StringUtils.abbreviate(key, 16) + ":", 17); b.append(String.format(" %s %4d\n", paddedKey, count)); } } return empty ? "" : b.toString(); }