下面列出了org.apache.commons.lang3.StringUtils#repeat ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public String apply(final Integer referenceBuild) {
if (referenceBuild >= currentBuild) {
return "1"; // fallback
}
else {
String cleanUrl = StringUtils.stripEnd(resultUrl, "/");
int subDetailsCount = StringUtils.countMatches(cleanUrl, "/");
String backward = StringUtils.repeat("../", subDetailsCount + 2);
String detailsUrl = StringUtils.substringBefore(cleanUrl, "/");
String url = String.format("%s%d/%s", backward, referenceBuild, detailsUrl);
return a(computeAge(referenceBuild))
.withHref(StringUtils.stripEnd(url, "/")).render();
}
}
private static void printNode(Element node, int indent) {
String prefix = (indent > 0) ? StringUtils.repeat(">", indent) + " " : "";
LOGGER.debug(prefix + "<" + node.getTagName() + "> / " + node.getNamespaceURI() + " / " + node.getPrefix());
prefix = StringUtils.repeat(">", indent + 1) + " ";
NamedNodeMap attribs = node.getAttributes();
for (int i = 0; i < attribs.getLength(); i++) {
Attr attrib = (Attr) attribs.item(i);
LOGGER.debug(prefix + "@" + attrib.getName() + " / " + attrib.getNamespaceURI() + " / " + attrib.getPrefix());
}
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child instanceof Element) {
XmlUtils.printNode((Element) child, indent + 1);
}
}
}
@Test
public void validate_descriptionSizeExceeded_ValidationException() {
//Arrange
ProcessTextFieldInput request = mockAbbyyRequest();
String description = StringUtils.repeat("*", Limits.MAX_SIZE_OF_DESCR + 1);
when(request.getDescription()).thenReturn(description);
//Act
ValidationException ex = this.sut.validate(request);
//Assert
assertNotNull(ex);
}
/**
* <p>Returns a string containing closing parenthesis. The number of
* parenthesis is based on the number of missing closing parenthesis
* in the argument string.
*
* <p>Example:
*
* {@code}
* input: "((( ))" -> output: ")"
* {@code}
*
* @param str a string.
*
* @return a String containing 0 or more "closing" parenthesis
*/
public static String getClosingParentheses( String str )
{
if ( StringUtils.isEmpty( str ) )
{
return StringUtils.EMPTY;
}
int open = 0;
for ( int i = 0; i < str.length(); i++ )
{
if ( str.charAt( i ) == '(' )
{
open++;
}
else if ( str.charAt( i ) == ')' )
{
if ( open >= 1 )
{
open--;
}
}
}
return StringUtils.repeat( ")", open );
}
public void debugService(BluetoothGattService service, int indentCount) {
String indentString = StringUtils.repeat(' ', indentCount);
final UUID uuidService = service.getUuid();
if (gattDebugEnabled) {
final String uuidServiceString = uuidService.toString();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(indentString);
stringBuilder.append(GattAttributes.lookup(uuidServiceString, "Unknown service"));
stringBuilder.append(" (" + uuidServiceString + ")");
for (BluetoothGattCharacteristic character : service.getCharacteristics()) {
final String uuidCharacteristicString = character.getUuid().toString();
stringBuilder.append("\n ");
stringBuilder.append(indentString);
stringBuilder.append(" - " + GattAttributes.lookup(uuidCharacteristicString, "Unknown Characteristic"));
stringBuilder.append(" (" + uuidCharacteristicString + ")");
}
stringBuilder.append("\n\n");
LOG.warn(stringBuilder.toString());
List<BluetoothGattService> includedServices = service.getIncludedServices();
for (BluetoothGattService serviceI : includedServices) {
debugService(serviceI, indentCount + 4);
}
}
}
private void updateIndent(boolean up)
{
if (up)
{
this.cachedIndent = StringUtils.repeat(' ', (++ this.indent) * 2);
}
else
{
this.cachedIndent = StringUtils.repeat(' ', (-- this.indent) * 2);
}
}
@Test
public void testSmallMessagePutAll() {
String key = "test";
String smallMessage = StringUtils.repeat("a", maxMessageSize - 1);
List<Entry<String, String>> entries = new ArrayList<>();
entries.add(new Entry<>(key, smallMessage));
store.putAll(entries);
Assert.assertEquals(store.get(key), smallMessage);
}
@Test
public void keywordShouldCreateNewOneWhenFlagNameLengthEqualsMaxLength() {
String maxLengthFlagName = StringUtils.repeat("a", FLAG_NAME_MAX_LENTH);
Keyword keyword = Keyword.of(maxLengthFlagName);
assertThat(keyword.getFlagName()).isEqualTo(maxLengthFlagName);
}
@Test
public void testLongValueInComponentConfigExtLatin() throws Exception {
ComponentRepresentation rep = createComponentRepresentation("mycomponent");
String value = StringUtils.repeat("ěščřžýíŮÍÁ", 400); // 4000 Unicode extended-Latin characters
rep.getConfig().addFirst("required", "foo");
rep.getConfig().addFirst("val1", value);
String id = createComponent(rep);
ComponentRepresentation returned = components.component(id).toRepresentation();
assertEquals(value, returned.getConfig().getFirst("val1"));
}
@Test
void shouldEncryptAndDecryptChunkUsingAES() throws Exception {
String chunk = StringUtils.repeat("Encryption is awesome!", 150);
SecretKey secretKey = EncryptionHelper.generateAESKey();
String encryptedData = EncryptionHelper.encryptUsingAES(secretKey, chunk);
String decryptedData = EncryptionHelper.decryptUsingAES(secretKey, encryptedData);
assertThat(chunk, is(decryptedData));
}
@Test(expected = IllegalArgumentException.class)
public void constructorShouldThrowExceptionOnInputTooBig() throws Exception {
new IssuedCommand(StringUtils.repeat('A', 65536));
}
private String fixHR(char symbol, int charsOnLine) {
return StringUtils.repeat(symbol, charsOnLine) + "\n";
}
private static String backward(int length) {
return StringUtils.repeat('\b', length);
}
private String dashLine(String character) {
return StringUtils.repeat(character, maxLength - 2);
}
protected String processFlowFile(final ComponentLog logger, final DebugLevels logLevel, final FlowFile flowFile, final ProcessSession session, final ProcessContext context) {
final Set<String> attributeKeys = getAttributesToLog(flowFile.getAttributes().keySet(), context);
final ComponentLog LOG = getLogger();
final String dashedLine;
String logPrefix = context.getProperty(LOG_PREFIX).evaluateAttributeExpressions(flowFile).getValue();
Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());
if (StringUtil.isBlank(logPrefix)) {
dashedLine = StringUtils.repeat('-', 50);
} else {
// abbreviate long lines
logPrefix = StringUtils.abbreviate(logPrefix, 40);
// center the logPrefix and pad with dashes
logPrefix = StringUtils.center(logPrefix, 40, '-');
// five dashes on the left and right side, plus the dashed logPrefix
dashedLine = StringUtils.repeat('-', 5) + logPrefix + StringUtils.repeat('-', 5);
}
// Pretty print metadata
final StringBuilder message = new StringBuilder();
message.append("logging for flow file ").append(flowFile);
message.append("\n");
message.append(dashedLine);
message.append("\nStandard FlowFile Attributes");
message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "entryDate", new Date(flowFile.getEntryDate())));
message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "lineageStartDate", new Date(flowFile.getLineageStartDate())));
message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "fileSize", flowFile.getSize()));
message.append("\nFlowFile Attribute Map Content");
for (final String key : attributeKeys) {
message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", key, flowFile.getAttribute(key)));
}
message.append("\n");
message.append(dashedLine);
// The user can request to log the payload
final boolean logPayload = context.getProperty(LOG_PAYLOAD).asBoolean();
if (logPayload) {
message.append("\n");
if (flowFile.getSize() < ONE_MB) {
final FlowFilePayloadCallback callback = new FlowFilePayloadCallback(charset);
session.read(flowFile, callback);
message.append(callback.getContents());
} else {
message.append("\n Not including payload since it is larger than one mb.");
}
}
final String outputMessage = message.toString().trim();
// Uses optional property to specify logging level
switch (logLevel) {
case info:
LOG.info(outputMessage);
break;
case debug:
LOG.debug(outputMessage);
break;
case warn:
LOG.warn(outputMessage);
break;
case trace:
LOG.trace(outputMessage);
break;
case error:
LOG.error(outputMessage);
break;
default:
LOG.debug(outputMessage);
}
return outputMessage;
}
protected String processFlowFile(final ComponentLog logger, final DebugLevels logLevel, final FlowFile flowFile, final ProcessSession session, final ProcessContext context) {
final Set<String> attributeKeys = getAttributesToLog(flowFile.getAttributes().keySet(), context);
final ComponentLog LOG = getLogger();
final String dashedLine;
String logPrefix = context.getProperty(LOG_PREFIX).evaluateAttributeExpressions(flowFile).getValue();
if (StringUtil.isBlank(logPrefix)) {
dashedLine = StringUtils.repeat('-', 50);
} else {
// abbreviate long lines
logPrefix = StringUtils.abbreviate(logPrefix, 40);
// center the logPrefix and pad with dashes
logPrefix = StringUtils.center(logPrefix, 40, '-');
// five dashes on the left and right side, plus the dashed logPrefix
dashedLine = StringUtils.repeat('-', 5) + logPrefix + StringUtils.repeat('-', 5);
}
// Pretty print metadata
final StringBuilder message = new StringBuilder();
message.append("logging for flow file ").append(flowFile);
message.append("\n");
message.append(dashedLine);
message.append("\nStandard FlowFile Attributes");
message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "entryDate", new Date(flowFile.getEntryDate())));
message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "lineageStartDate", new Date(flowFile.getLineageStartDate())));
message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "fileSize", flowFile.getSize()));
message.append("\nFlowFile Attribute Map Content");
for (final String key : attributeKeys) {
message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", key, flowFile.getAttribute(key)));
}
message.append("\n");
message.append(dashedLine);
// The user can request to log the payload
final boolean logPayload = context.getProperty(LOG_PAYLOAD).asBoolean();
if (logPayload) {
message.append("\n");
if (flowFile.getSize() < ONE_MB) {
final FlowFilePayloadCallback callback = new FlowFilePayloadCallback();
session.read(flowFile, callback);
message.append(callback.getContents());
} else {
message.append("\n Not including payload since it is larger than one mb.");
}
}
final String outputMessage = message.toString().trim();
// Uses optional property to specify logging level
switch (logLevel) {
case info:
LOG.info(outputMessage);
break;
case debug:
LOG.debug(outputMessage);
break;
case warn:
LOG.warn(outputMessage);
break;
case trace:
LOG.trace(outputMessage);
break;
case error:
LOG.error(outputMessage);
break;
default:
LOG.debug(outputMessage);
}
return outputMessage;
}
@Test( expected = IllegalArgumentException.class )
public void testConstructor2() throws Exception
{
new MessageListenerImpl( StringUtils.repeat( "s", MessageListener.MAX_RECIPIENT_ID_LEN + 1 ) );
}
private MailboxPath tooLongMailboxPath(MailboxPath fromMailboxPath) {
return new MailboxPath(fromMailboxPath, StringUtils.repeat("b", 65537));
}
@Test
public void testMultithreadedSharedConnMessagingNetworkServiceRate() throws Exception {
Assume.assumeFalse("Use log level INFO to run benchmarking", LOG.isLoggable(Level.FINEST));
LOG.log(Level.FINEST, name.getMethodName());
final IdentifierFactory factory = new StringIdentifierFactory();
final Injector injector = Tang.Factory.getTang().newInjector();
injector.bindVolatileParameter(NameServerParameters.NameServerIdentifierFactory.class, factory);
injector.bindVolatileInstance(LocalAddressProvider.class, this.localAddressProvider);
try (NameServer server = injector.getInstance(NameServer.class)) {
final int nameServerPort = server.getPort();
final int[] messageSizes = {2000}; // {1,16,32,64,512,64*1024,1024*1024};
for (final int size : messageSizes) {
final int numMessages = 300000 / (Math.max(1, size / 512));
final int numThreads = 2;
final int totalNumMessages = numMessages * numThreads;
final Monitor monitor = new Monitor();
// network service
final String name2 = "task2";
final String name1 = "task1";
final Configuration nameResolverConf =
Tang.Factory.getTang().newConfigurationBuilder(NameResolverConfiguration.CONF
.set(NameResolverConfiguration.NAME_SERVER_HOSTNAME, this.localAddress)
.set(NameResolverConfiguration.NAME_SERVICE_PORT, nameServerPort)
.build())
.build();
final Injector injector2 = Tang.Factory.getTang().newInjector(nameResolverConf);
LOG.log(Level.FINEST, "=== Test network service receiver start");
LOG.log(Level.FINEST, "=== Test network service sender start");
try (NameResolver nameResolver = injector2.getInstance(NameResolver.class)) {
injector2.bindVolatileParameter(NetworkServiceParameters.NetworkServiceIdentifierFactory.class, factory);
injector2.bindVolatileInstance(NameResolver.class, nameResolver);
injector2.bindVolatileParameter(NetworkServiceParameters.NetworkServiceCodec.class, new StringCodec());
injector2.bindVolatileParameter(NetworkServiceParameters.NetworkServiceTransportFactory.class,
injector.getInstance(MessagingTransportFactory.class));
injector2.bindVolatileParameter(NetworkServiceParameters.NetworkServiceExceptionHandler.class,
new ExceptionHandler());
final Injector injectorNs2 = injector2.forkInjector();
injectorNs2.bindVolatileParameter(NetworkServiceParameters.NetworkServiceHandler.class,
new MessageHandler<String>(name2, monitor, totalNumMessages));
final NetworkService<String> ns2 = injectorNs2.getInstance(NetworkService.class);
final Injector injectorNs1 = injector2.forkInjector();
injectorNs1.bindVolatileParameter(NetworkServiceParameters.NetworkServiceHandler.class,
new MessageHandler<String>(name1, null, 0));
final NetworkService<String> ns1 = injectorNs1.getInstance(NetworkService.class);
ns2.registerId(factory.getNewInstance(name2));
final int port2 = ns2.getTransport().getListeningPort();
server.register(factory.getNewInstance("task2"), new InetSocketAddress(this.localAddress, port2));
ns1.registerId(factory.getNewInstance(name1));
final int port1 = ns1.getTransport().getListeningPort();
server.register(factory.getNewInstance("task1"), new InetSocketAddress(this.localAddress, port1));
final Identifier destId = factory.getNewInstance(name2);
try (Connection<String> conn = ns1.newConnection(destId)) {
conn.open();
final String message = StringUtils.repeat('1', size);
final ExecutorService e = Executors.newCachedThreadPool();
final long start = System.currentTimeMillis();
for (int i = 0; i < numThreads; i++) {
e.submit(new Runnable() {
@Override
public void run() {
for (int i = 0; i < numMessages; i++) {
conn.write(message);
}
}
});
}
e.shutdown();
e.awaitTermination(30, TimeUnit.SECONDS);
monitor.mwait();
final long end = System.currentTimeMillis();
final double runtime = ((double) end - start) / 1000;
LOG.log(Level.FINEST, "size: " + size + "; messages/s: " + totalNumMessages / runtime +
" bandwidth(bytes/s): " + ((double) totalNumMessages * 2 * size) / runtime); // x2 for unicode chars
}
}
}
}
}
public String createDivider(char symbol, int charsOnLine) {
return StringUtils.repeat(symbol, charsOnLine) + "\n";
}