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

The following examples show how to use com.google.common.base.Strings#padEnd() . 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: FormattingService.java    From xtext-core with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.14
 */
public List<TextEdit> format(XtextResource resource, Document document, int offset, int length,
		FormattingOptions options) {
	String indent = indentationInformation.getIndentString();
	if (options != null) {
		if (options.isInsertSpaces()) {
			indent = Strings.padEnd("", options.getTabSize(), ' ');
		}
	}
	List<TextEdit> result = new ArrayList<>();
	if (this.formatter2Provider != null) {
		MapBasedPreferenceValues preferences = new MapBasedPreferenceValues();
		preferences.put("indentation", indent);
		List<ITextReplacement> replacements = format2(resource, new TextRegion(offset, length), preferences);
		for (ITextReplacement r : replacements) {
			result.add(toTextEdit(document, r.getReplacementText(), r.getOffset(), r.getLength()));
		}
	}
	return result;
}
 
Example 2
Source File: BatchJobUploaderTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadIncrementalBatchJobOperations_logging() throws Exception {
  BatchJobUploadStatus status =
      new BatchJobUploadStatus(10, URI.create(mockHttpServer.getServerUrl()));
  String uploadRequestBody = "<mutate>testUpload</mutate>";
  when(uploadBodyProvider.getHttpContent(request, false, true))
      .thenReturn(new ByteArrayContent(null, uploadRequestBody.getBytes(UTF_8)));
  mockHttpServer.setMockResponse(new MockResponse("testUploadResponse"));

  String expectedBody = "testUpload</mutate>";
  expectedBody =
      Strings.padEnd(expectedBody, BatchJobUploader.REQUIRED_CONTENT_LENGTH_INCREMENT, ' ');

  // Invoke the incremental upload method.
  BatchJobUploadResponse response =
      uploader.uploadIncrementalBatchJobOperations(request, true, status);
  verify(batchJobLogger, times(1)).logUpload(
      expectedBody,
      status.getResumableUploadUri(),
      response,
      null
  );
 }
 
Example 3
Source File: CutEurostagNamingStrategy.java    From ipst with Mozilla Public License 2.0 6 votes vote down vote up
private String getEsgId(EurostagDictionary dictionary, NameType nameType, String iidmId, String regex, String repl) {
    String esgId = iidmId.length() > nameType.getLength() ? iidmId.substring(0, nameType.getLength())
            : Strings.padEnd(iidmId, nameType.getLength(), ' ');
    if (regex != null) {
        esgId = esgId.replaceAll(regex, repl);
    }
    int counter = 0;
    while (dictionary.esgIdExists(esgId) || forbiddenEsgIds.contains(esgId)) {
        String counterStr = Integer.toString(counter++);
        if (counterStr.length() > nameType.getLength()) {
            throw new RuntimeException("Renaming fatal error " + iidmId + " -> " + esgId);
        }
        esgId = esgId.substring(0, nameType.getLength() - counterStr.length()) + counterStr;
    }
    return esgId;
}
 
Example 4
Source File: CurrencyParameterSensitivityValueFormatter.java    From Strata with Apache License 2.0 6 votes vote down vote up
private String getSensitivityString(
    CurrencyParameterSensitivity sensitivity,
    DoubleFunction<String> formatFn,
    boolean pad) {

  StringBuilder sb = new StringBuilder();
  List<ParameterMetadata> parameterMetadata = sensitivity.getParameterMetadata();
  IntFunction<String> labelProvider =
      i -> Objects.toString(Strings.emptyToNull(parameterMetadata.get(i).getLabel()), String.valueOf(i + 1));

  for (int i = 0; i < sensitivity.getSensitivity().size(); i++) {
    String formattedSensitivity = formatFn.apply(sensitivity.getSensitivity().get(i));
    String field = labelProvider.apply(i) + " = " + formattedSensitivity;
    if (pad) {
      field = Strings.padEnd(field, PADDED_FIELD_WIDTH, ' ');
    }
    sb.append(field);
    if (i < sensitivity.getSensitivity().size() - 1) {
      sb.append(" | ");
    }
  }
  return sb.toString();
}
 
Example 5
Source File: StringsExample.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
/**
 * Right pad string
 */
@Test
public void right_pad_string () {

	String rightPaddedString = Strings.padEnd("levelup", 10, ' ');
	
	assertEquals("levelup   ", rightPaddedString);
	assertEquals(10, rightPaddedString.length());
	assertThat(rightPaddedString, endsWith(" "));
}
 
Example 6
Source File: BatchJobUploaderTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testUploadIncrementalBatchJobOperations_notFirst_notLast() throws Exception {
  BatchJobUploadStatus status =
      new BatchJobUploadStatus(10, URI.create(mockHttpServer.getServerUrl()));
  String uploadRequestBody = "<mutate>testUpload</mutate>";
  when(uploadBodyProvider.getHttpContent(request, false, false))
      .thenReturn(new ByteArrayContent(null, uploadRequestBody.getBytes(UTF_8)));
  mockHttpServer.setMockResponse(new MockResponse("testUploadResponse"));

  // Invoked the incremental upload method.
  BatchJobUploadResponse response =
      uploader.uploadIncrementalBatchJobOperations(request, false, status);
  assertEquals("Should have made one request", 1, mockHttpServer.getAllResponses().size());

  // Check the request.
  String firstRequest = mockHttpServer.getLastResponse().getRequestBody();
  String expectedBody = "testUpload";
  expectedBody =
      Strings.padEnd(expectedBody, BatchJobUploader.REQUIRED_CONTENT_LENGTH_INCREMENT, ' ');

  assertEquals("Request body is incorrect", expectedBody, firstRequest);
  assertEquals("Request should have succeeded", 200, response.getHttpStatus());

  // Check the BatchJobUploadStatus.
  BatchJobUploadStatus expectedStatus =
      new BatchJobUploadStatus(
          status.getTotalContentLength() + expectedBody.getBytes(UTF_8).length,
          URI.create(mockHttpServer.getServerUrl()));
  BatchJobUploadStatus actualStatus = response.getBatchJobUploadStatus();
  assertEquals(
      "Status total content length is incorrect",
      expectedStatus.getTotalContentLength(),
      actualStatus.getTotalContentLength());
  assertEquals(
      "Status resumable upload URI is incorrect",
      expectedStatus.getResumableUploadUri(),
      actualStatus.getResumableUploadUri());
}
 
Example 7
Source File: BlobStoreUtilImplTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testRejectLongPath() throws Exception {
  String shortPath = File.separator + "test" + File.separator + "testtestte";

  assertFalse(underTest.validateFilePath(shortPath, 9));

  String longMemberFolder = Strings.padEnd("", MAX_NAME_LENGTH + 1, 'x');
  shortPath = File.separator + longMemberFolder + shortPath;

  assertFalse(underTest.validateFilePath(shortPath, MAX_NAME_LENGTH));
}
 
Example 8
Source File: FileReader.java    From tablesaw with Apache License 2.0 5 votes vote down vote up
protected String getTypeString(Table structure) {
  StringBuilder buf = new StringBuilder();
  buf.append("ColumnType[] columnTypes = {");
  buf.append(System.lineSeparator());

  Column<?> typeCol = structure.column("Column Type");
  Column<?> indxCol = structure.column("Index");
  Column<?> nameCol = structure.column("Column Name");

  // add the column headers
  int typeColIndex = structure.columnIndex(typeCol);
  int indxColIndex = structure.columnIndex(indxCol);
  int nameColIndex = structure.columnIndex(nameCol);

  int typeColWidth = typeCol.columnWidth();
  int indxColWidth = indxCol.columnWidth();
  int nameColWidth = nameCol.columnWidth();

  final char padChar = ' ';
  for (int r = 0; r < structure.rowCount(); r++) {
    String cell = Strings.padEnd(structure.get(r, typeColIndex) + ",", typeColWidth, padChar);
    buf.append(cell);
    buf.append(" // ");

    cell = Strings.padEnd(structure.getUnformatted(r, indxColIndex), indxColWidth, padChar);
    buf.append(cell);
    buf.append(' ');

    cell = Strings.padEnd(structure.getUnformatted(r, nameColIndex), nameColWidth, padChar);
    buf.append(cell);
    buf.append(' ');

    buf.append(System.lineSeparator());
  }
  buf.append("}");
  buf.append(System.lineSeparator());
  return buf.toString();
}
 
Example 9
Source File: BatchJobUploaderTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testUploadIncrementalBatchJobOperations_notFirst() throws Exception {
  BatchJobUploadStatus status =
      new BatchJobUploadStatus(10, URI.create(mockHttpServer.getServerUrl()));
  String uploadRequestBody = "<mutate>testUpload</mutate>";
  when(uploadBodyProvider.getHttpContent(request, false, true))
      .thenReturn(new ByteArrayContent(null, uploadRequestBody.getBytes(UTF_8)));
  mockHttpServer.setMockResponse(new MockResponse("testUploadResponse"));

  // Invoked the incremental upload method.
  BatchJobUploadResponse response =
      uploader.uploadIncrementalBatchJobOperations(request, true, status);
  assertEquals("Should have made one request", 1, mockHttpServer.getAllResponses().size());

  // Check the request.
  String firstRequest = mockHttpServer.getLastResponse().getRequestBody();
  String expectedBody = "testUpload</mutate>";
  expectedBody =
      Strings.padEnd(expectedBody, BatchJobUploader.REQUIRED_CONTENT_LENGTH_INCREMENT, ' ');

  assertEquals("Request body is incorrect", expectedBody, firstRequest);
  assertEquals("Request should have succeeded", 200, response.getHttpStatus());

  // Check the BatchJobUploadStatus.
  BatchJobUploadStatus expectedStatus =
      new BatchJobUploadStatus(
          status.getTotalContentLength() + expectedBody.getBytes(UTF_8).length,
          URI.create(mockHttpServer.getServerUrl()));
  BatchJobUploadStatus actualStatus = response.getBatchJobUploadStatus();
  assertEquals(
      "Status total content length is incorrect",
      expectedStatus.getTotalContentLength(),
      actualStatus.getTotalContentLength());
  assertEquals(
      "Status resumable upload URI is incorrect",
      expectedStatus.getResumableUploadUri(),
      actualStatus.getResumableUploadUri());
}
 
Example 10
Source File: FileReader.java    From tablesaw with Apache License 2.0 5 votes vote down vote up
protected String getTypeString(Table structure) {
  StringBuilder buf = new StringBuilder();
  buf.append("ColumnType[] columnTypes = {");
  buf.append(System.lineSeparator());

  Column<?> typeCol = structure.column("Column Type");
  Column<?> indxCol = structure.column("Index");
  Column<?> nameCol = structure.column("Column Name");

  // add the column headers
  int typeColIndex = structure.columnIndex(typeCol);
  int indxColIndex = structure.columnIndex(indxCol);
  int nameColIndex = structure.columnIndex(nameCol);

  int typeColWidth = typeCol.columnWidth();
  int indxColWidth = indxCol.columnWidth();
  int nameColWidth = nameCol.columnWidth();

  final char padChar = ' ';
  for (int r = 0; r < structure.rowCount(); r++) {
    String cell = Strings.padEnd(structure.get(r, typeColIndex) + ",", typeColWidth, padChar);
    buf.append(cell);
    buf.append(" // ");

    cell = Strings.padEnd(structure.getUnformatted(r, indxColIndex), indxColWidth, padChar);
    buf.append(cell);
    buf.append(' ');

    cell = Strings.padEnd(structure.getUnformatted(r, nameColIndex), nameColWidth, padChar);
    buf.append(cell);
    buf.append(' ');

    buf.append(System.lineSeparator());
  }
  buf.append("}");
  buf.append(System.lineSeparator());
  return buf.toString();
}
 
Example 11
Source File: EsgName.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
public EsgName(String name, int maxLength) {
    if (name.length() > maxLength) {
        throw new RuntimeException("Invalid id '" + name + "', expected to be less or equal to "
                + maxLength + " characters");
    }
    this.name = Strings.padEnd(name, maxLength, ' ');
}
 
Example 12
Source File: DebugPathSanitizer.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * @return the given path as a string, expanded using {@code separator} to fulfill the required
 *     {@code pathSize}.
 */
public static String getPaddedDir(String path, int size, char pad) {
  Preconditions.checkArgument(
      path.length() <= size,
      String.format(
          "Path is too long to sanitize:\n'%s' is %d characters long, limit is %d.",
          path, path.length(), size));
  return Strings.padEnd(path, size, pad);
}
 
Example 13
Source File: ShardHashAdjuster.java    From aliyun-log-java-producer with Apache License 2.0 5 votes vote down vote up
public String adjust(String shardHash) {
  HashCode hashCode = Hashing.md5().hashBytes(shardHash.getBytes());
  String binary =
      Strings.padStart(new BigInteger(1, hashCode.asBytes()).toString(2), BINARY_LENGTH, '0');
  String adjustedBinary = Strings.padEnd(binary.substring(0, reservedBits), BINARY_LENGTH, '0');
  return Strings.padStart(new BigInteger(adjustedBinary, 2).toString(16), HEX_LENGTH, '0');
}
 
Example 14
Source File: ValidatorLogger.java    From teku with Apache License 2.0 5 votes vote down vote up
public void dutyCompleted(
    final String producedType,
    final UnsignedLong slot,
    final int successCount,
    final Set<Bytes32> blockRoots) {
  final String paddedType = Strings.padEnd(producedType, LONGEST_TYPE_LENGTH, ' ');
  logDuty(paddedType, slot, successCount, blockRoots);
}
 
Example 15
Source File: MilestoneDatabase.java    From compass with GNU Affero General Public License v3.0 5 votes vote down vote up
private String getTagForIndex(int index) {
  String tag;
  int[] trits = new int[15];
  for (int i = 0; i < index; i++) {
    Converter.increment(trits, trits.length);
  }
  tag = Converter.trytes(trits);
  return Strings.padEnd(tag, 27, '9');
}
 
Example 16
Source File: Table.java    From gauge-java with Apache License 2.0 4 votes vote down vote up
private Function<String, String> format(final int maxStringLength) {
    return input -> Strings.padEnd(input, maxStringLength, SPACE_AS_CHAR);
}
 
Example 17
Source File: AbstractTestOrcReader.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
private String toCharValue(Object value)
{
    return Strings.padEnd(value.toString(), CHAR_LENGTH, ' ');
}
 
Example 18
Source File: ObjectFileScrubbers.java    From buck with Apache License 2.0 4 votes vote down vote up
private static void putSpaceRightPaddedString(ByteBuffer buffer, int len, String value) {
  Preconditions.checkState(value.length() <= len);
  value = Strings.padEnd(value, len, ' ');
  buffer.put(value.getBytes(Charsets.US_ASCII));
}
 
Example 19
Source File: DateTime.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
private static Rfc3339ParseResult parseRfc3339WithNanoSeconds(String str)
    throws NumberFormatException {
  Matcher matcher = RFC3339_PATTERN.matcher(str);
  if (!matcher.matches()) {
    throw new NumberFormatException("Invalid date/time format: " + str);
  }

  int year = Integer.parseInt(matcher.group(1)); // yyyy
  int month = Integer.parseInt(matcher.group(2)) - 1; // MM
  int day = Integer.parseInt(matcher.group(3)); // dd
  boolean isTimeGiven = matcher.group(4) != null; // 'T'HH:mm:ss.milliseconds
  String tzShiftRegexGroup = matcher.group(9); // 'Z', or time zone shift HH:mm following '+'/'-'
  boolean isTzShiftGiven = tzShiftRegexGroup != null;
  int hourOfDay = 0;
  int minute = 0;
  int second = 0;
  int nanoseconds = 0;
  Integer tzShiftInteger = null;

  if (isTzShiftGiven && !isTimeGiven) {
    throw new NumberFormatException(
        "Invalid date/time format, cannot specify time zone shift"
            + " without specifying time: "
            + str);
  }

  if (isTimeGiven) {
    hourOfDay = Integer.parseInt(matcher.group(5)); // HH
    minute = Integer.parseInt(matcher.group(6)); // mm
    second = Integer.parseInt(matcher.group(7)); // ss
    if (matcher.group(8) != null) { // contains .nanoseconds?
      String fraction = Strings.padEnd(matcher.group(8).substring(1), 9, '0');
      nanoseconds = Integer.parseInt(fraction);
    }
  }
  Calendar dateTime = new GregorianCalendar(GMT);
  dateTime.clear();
  dateTime.set(year, month, day, hourOfDay, minute, second);
  long value = dateTime.getTimeInMillis();

  if (isTimeGiven && isTzShiftGiven) {
    if (Character.toUpperCase(tzShiftRegexGroup.charAt(0)) != 'Z') {
      int tzShift =
          Integer.parseInt(matcher.group(11)) * 60 // time zone shift HH
              + Integer.parseInt(matcher.group(12)); // time zone shift mm
      if (matcher.group(10).charAt(0) == '-') { // time zone shift + or -
        tzShift = -tzShift;
      }
      value -= tzShift * 60000L; // e.g. if 1 hour ahead of UTC, subtract an hour to get UTC time
      tzShiftInteger = tzShift;
    } else {
      tzShiftInteger = 0;
    }
  }
  // convert to seconds and nanoseconds
  long secondsSinceEpoch = value / 1000L;
  return new Rfc3339ParseResult(secondsSinceEpoch, nanoseconds, isTimeGiven, tzShiftInteger);
}
 
Example 20
Source File: MilestoneDatabase.java    From compass with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List<Transaction> createMilestone(String trunk, String branch, int index, int mwm) {

  IotaPoW pow = getPoWProvider();

  // Get the siblings in the current merkle tree
  List<String> leafSiblings = siblings(index, layers);
  String siblingsTrytes = String.join("", leafSiblings);
  String paddedSiblingsTrytes = Strings.padEnd(siblingsTrytes, ISS.FRAGMENT_LENGTH / ISS.TRYTE_WIDTH, '9');

  final String tag = getTagForIndex(index);

  // A milestone consists of two transactions.
  // The last transaction (currentIndex == lastIndex) contains the siblings for the merkle tree.
  Transaction txSiblings = new Transaction();
  txSiblings.setSignatureFragments(paddedSiblingsTrytes);
  txSiblings.setAddress(root);
  txSiblings.setCurrentIndex(signatureSource.getSecurity());
  txSiblings.setLastIndex(signatureSource.getSecurity());
  txSiblings.setTimestamp(System.currentTimeMillis() / 1000);
  txSiblings.setObsoleteTag(tag);
  txSiblings.setValue(0);
  txSiblings.setBundle(EMPTY_HASH);
  txSiblings.setTrunkTransaction(trunk);
  txSiblings.setBranchTransaction(branch);
  txSiblings.setTag(tag);
  txSiblings.setNonce(EMPTY_TAG);

  // The other transactions contain a signature that signs the siblings and thereby ensures the integrity.
  List<Transaction> txs =
      IntStream.range(0, signatureSource.getSecurity()).mapToObj(i -> {
        Transaction tx = new Transaction();
        tx.setSignatureFragments(Strings.repeat("9", 27 * 81));
        tx.setAddress(root);
        tx.setCurrentIndex(i);
        tx.setLastIndex(signatureSource.getSecurity());
        tx.setTimestamp(System.currentTimeMillis() / 1000);
        tx.setObsoleteTag(tag);
        tx.setValue(0);
        tx.setBundle(EMPTY_HASH);
        tx.setTrunkTransaction(EMPTY_HASH);
        tx.setBranchTransaction(trunk);
        tx.setTag(tag);
        tx.setNonce(EMPTY_TAG);
        return tx;
      }).collect(Collectors.toList());

  txs.add(txSiblings);

  Transaction tPoW;
  String hashToSign;

  //calculate the bundle hash (same for Curl & Kerl)
  String bundleHash = calculateBundleHash(txs);
  txs.forEach(tx -> tx.setBundle(bundleHash));

  txSiblings.setAttachmentTimestamp(System.currentTimeMillis());
  tPoW = new Transaction(pow.performPoW(txSiblings.toTrytes(), mwm));
  txSiblings.setAttachmentTimestamp(tPoW.getAttachmentTimestamp());
  txSiblings.setAttachmentTimestampLowerBound(tPoW.getAttachmentTimestampLowerBound());
  txSiblings.setAttachmentTimestampUpperBound(tPoW.getAttachmentTimestampUpperBound());
  txSiblings.setNonce(tPoW.getNonce());

  // We need to avoid the M bug we we are signing with KERL
  if (signatureSource.getSignatureMode() == SpongeFactory.Mode.KERL) {
    /*
    In the case that the signature is created using KERL, we need to ensure that there exists no 'M'(=13) in the
    normalized fragment that we're signing.
     */
    boolean hashContainsM;
    int attempts = 0;
    do {
      int[] hashTrits = Hasher.hashTrytesToTrits(powMode, txSiblings.toTrytes());
      int[] normHash = ISS.normalizedBundle(hashTrits);

      hashContainsM = Arrays.stream(normHash).limit(ISS.NUMBER_OF_FRAGMENT_CHUNKS * signatureSource.getSecurity()).anyMatch(elem -> elem == 13);
      if (hashContainsM) {
        txSiblings.setAttachmentTimestamp(System.currentTimeMillis());
        tPoW = new Transaction(pow.performPoW(txSiblings.toTrytes(), mwm));
        txSiblings.setAttachmentTimestamp(tPoW.getAttachmentTimestamp());
        txSiblings.setAttachmentTimestampLowerBound(tPoW.getAttachmentTimestampLowerBound());
        txSiblings.setAttachmentTimestampUpperBound(tPoW.getAttachmentTimestampUpperBound());
        txSiblings.setNonce(tPoW.getNonce());
      }
      attempts++;
    } while (hashContainsM);

    log.info("KERL milestone generation took {} attempts.", attempts);

  }

  hashToSign = Hasher.hashTrytes(powMode, txSiblings.toTrytes());
  String signature = signatureSource.getSignature(index, hashToSign);
  txSiblings.setHash(hashToSign);

  validateSignature(root, index, hashToSign, signature, siblingsTrytes);

  chainTransactionsFillSignatures(mwm, txs, signature);

  return txs;
}