下面列出了com.google.common.base.Strings#lenientFormat ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Abort the direct runner job,removing it from the direct jobs registry.
*
* @param job to abort.
* @return The aborted Job
*/
@Override
public Job abortJob(Job job) {
DirectJob directJob = jobs.get(job.getExtId());
if (directJob != null) {
try {
directJob.abort();
} catch (IOException e) {
throw new RuntimeException(
Strings.lenientFormat("Unable to abort DirectRunner job %s", job.getExtId(), e));
}
jobs.remove(job.getExtId());
}
job.setStatus(JobStatus.ABORTING);
return job;
}
@BeforeMethod(alwaysRun = true)
public final void setTestName(Method method) {
final ConnectionPolicy connectionPolicy = this.clientBuilder.getConnectionPolicy();
final String connectionMode;
if (connectionPolicy == null) {
connectionMode = "None";
} else {
connectionMode = connectionPolicy.getConnectionMode() == ConnectionMode.Direct
? "Direct " + this.clientBuilder.getConfigs().getProtocol().name().toUpperCase()
: "Gateway";
}
this.testName = Strings.lenientFormat("%s::%s[%s with %s consistency]",
method.getDeclaringClass().getSimpleName(),
method.getName(),
connectionMode,
clientBuilder.getDesiredConsistencyLevel());
logger.info("Starting {}", this.testName);
}
@BeforeMethod(alwaysRun = true)
public final void setTestName(Method method) {
final ConnectionPolicy connectionPolicy = this.clientBuilder.getConnectionPolicy();
final String connectionMode;
if (connectionPolicy == null) {
connectionMode = "None";
} else {
connectionMode = connectionPolicy.getConnectionMode() == ConnectionMode.Direct
? "Direct " + this.clientBuilder.getConfigs().getProtocol().name().toUpperCase()
: "Gateway";
}
this.testName = Strings.lenientFormat("%s::%s[%s with %s consistency]",
method.getDeclaringClass().getSimpleName(),
method.getName(),
connectionMode,
clientBuilder.getDesiredConsistencyLevel());
logger.info("Starting {}", this.testName);
}
/**
* Decode a {@link UUID} as serialized by Microsoft APIs like {@code System.Guid.ToByteArray}
*
* @param in a {@link ByteBuf} containing the serialized {@link UUID} to be decoded
* @return a new {@link UUID}
*/
public static UUID decode(final ByteBuf in) {
checkNotNull(in, "in");
if (in.readableBytes() < 2 * Long.BYTES) {
final String reason = Strings.lenientFormat("invalid frame length: %s", in.readableBytes());
throw new CorruptedFrameException(reason);
}
long mostSignificantBits = in.readUnsignedIntLE() << 32;
mostSignificantBits |= (0x000000000000FFFFL & in.readShortLE()) << 16;
mostSignificantBits |= (0x000000000000FFFFL & in.readShortLE());
long leastSignificantBits = (0x000000000000FFFFL & in.readShortLE()) << (32 + 16);
for (int shift = 32 + 8; shift >= 0; shift -= 8) {
leastSignificantBits |= (0x00000000000000FFL & in.readByte()) << shift;
}
return new UUID(mostSignificantBits, leastSignificantBits);
}
public void encode(final ByteBuf out) {
final int expectedLength = RntbdRequestFrame.LENGTH + this.headers.computeLength();
final int start = out.writerIndex();
out.writeIntLE(expectedLength);
final RntbdRequestFrame header = new RntbdRequestFrame(this.getActivityId(), RntbdOperationType.Connection, RntbdResourceType.Connection);
header.encode(out);
this.headers.encode(out);
final int observedLength = out.writerIndex() - start;
if (observedLength != expectedLength) {
final String reason = Strings.lenientFormat("expectedLength=%s, observedLength=%s", expectedLength, observedLength);
throw new IllegalStateException(reason);
}
}
/**
* Add the given job to the registry.
*
* @param job containing the job id,
*/
public void add(DirectJob job) {
if (jobs.containsKey(job.getJobId())) {
throw new IllegalArgumentException(
Strings.lenientFormat("Job with id %s already exists and is running", job.getJobId()));
}
jobs.put(job.getJobId(), job);
}
/**
* Abort an existing Dataflow job. Streaming Dataflow jobs are always drained, not cancelled.
*
* @param job to abort.
* @return The aborted Job.
*/
@Override
public Job abortJob(Job job) {
String dataflowJobId = job.getExtId();
try {
com.google.api.services.dataflow.model.Job dataflowJob =
dataflow.projects().locations().jobs().get(projectId, location, dataflowJobId).execute();
com.google.api.services.dataflow.model.Job content =
new com.google.api.services.dataflow.model.Job();
if (dataflowJob.getType().equals(DataflowJobType.JOB_TYPE_BATCH.toString())) {
content.setRequestedState(DataflowJobState.JOB_STATE_CANCELLED.toString());
} else if (dataflowJob.getType().equals(DataflowJobType.JOB_TYPE_STREAMING.toString())) {
content.setRequestedState(DataflowJobState.JOB_STATE_DRAINING.toString());
}
dataflow
.projects()
.locations()
.jobs()
.update(projectId, location, dataflowJobId, content)
.execute();
} catch (Exception e) {
log.error("Unable to drain job with id: {}, cause: {}", dataflowJobId, e.getMessage());
throw new RuntimeException(
Strings.lenientFormat("Unable to drain job with id: %s", dataflowJobId), e);
}
job.setStatus(JobStatus.ABORTING);
return job;
}
static boolean canDecodePayload(final ByteBuf in, final int start) {
checkNotNull(in, "in");
final int readerIndex = in.readerIndex();
if (start < readerIndex) {
throw new IllegalArgumentException("start < in.readerIndex()");
}
final int offset = start - readerIndex;
if (in.readableBytes() - offset < Integer.BYTES) {
return false;
}
final long length = in.getUnsignedIntLE(start);
if (length > Integer.MAX_VALUE) {
final String reason = Strings.lenientFormat("Payload frame length exceeds Integer.MAX_VALUE, %s: %s",
Integer.MAX_VALUE, length
);
throw new CorruptedFrameException(reason);
}
return offset + Integer.BYTES + length <= in.readableBytes();
}
private static String formatMessage(String msg, Object... args) {
if (args.length == 0) {
return msg;
}
return Strings.lenientFormat(msg, args);
}
@Test(dataProvider = "collectionLinkTypeArgProvider", groups = "e2e")
public void readMyWrites(boolean useNameLink) throws Exception {
int concurrency = 5;
String cmdFormat = "-serviceEndpoint %s -masterKey %s" +
" -databaseId %s" +
" -collectionId %s" +
" -consistencyLevel %s" +
" -concurrency %s" +
" -numberOfOperations %s" +
" -maxRunningTimeDuration %s" +
" -operation ReadMyWrites" +
" -connectionMode Direct" +
" -numberOfPreCreatedDocuments 100" +
" -printingInterval 60" +
"%s";
String cmd = Strings.lenientFormat(cmdFormat,
TestConfigurations.HOST,
TestConfigurations.MASTER_KEY,
database.getId(),
collection.getId(),
desiredConsistency,
concurrency,
numberOfOperationsAsString,
maxRunningTime,
(useNameLink ? " -useNameLink" : ""));
Configuration cfg = new Configuration();
new JCommander(cfg, StringUtils.split(cmd));
AtomicInteger success = new AtomicInteger();
AtomicInteger error = new AtomicInteger();
ReadMyWriteWorkflow wf = new ReadMyWriteWorkflow(cfg) {
@Override
protected void onError(Throwable throwable) {
error.incrementAndGet();
}
@Override
protected void onSuccess() {
success.incrementAndGet();
}
};
// schedules a collection scale up after a delay
scheduleScaleUp(delayForInitiationCollectionScaleUpInSeconds, newCollectionThroughput);
wf.run();
wf.shutdown();
int numberOfOperations = Integer.parseInt(numberOfOperationsAsString);
assertThat(error).hasValue(0);
assertThat(collectionScaleUpFailed).isFalse();
if (numberOfOperations > 0) {
assertThat(success).hasValue(numberOfOperations);
}
}
public static RntbdResourceType fromId(final short id) throws IllegalArgumentException {
switch (id) {
case 0x0000:
return RntbdResourceType.Connection;
case 0x0001:
return RntbdResourceType.Database;
case 0x0002:
return RntbdResourceType.Collection;
case 0x0003:
return RntbdResourceType.Document;
case 0x0004:
return RntbdResourceType.Attachment;
case 0x0005:
return RntbdResourceType.User;
case 0x0006:
return RntbdResourceType.Permission;
case 0x0007:
return RntbdResourceType.StoredProcedure;
case 0x0008:
return RntbdResourceType.Conflict;
case 0x0009:
return RntbdResourceType.Trigger;
case 0x000A:
return RntbdResourceType.UserDefinedFunction;
case 0x000B:
return RntbdResourceType.Module;
case 0x000C:
return RntbdResourceType.Replica;
case 0x000D:
return RntbdResourceType.ModuleCommand;
case 0x000E:
return RntbdResourceType.Record;
case 0x000F:
return RntbdResourceType.Offer;
case 0x0010:
return RntbdResourceType.PartitionSetInformation;
case 0x0011:
return RntbdResourceType.XPReplicatorAddress;
case 0x0012:
return RntbdResourceType.MasterPartition;
case 0x0013:
return RntbdResourceType.ServerPartition;
case 0x0014:
return RntbdResourceType.DatabaseAccount;
case 0x0015:
return RntbdResourceType.Topology;
case 0x0016:
return RntbdResourceType.PartitionKeyRange;
// Obsolete and now undefined: case 0x0017: return RntbdResourceType.Timestamp;
case 0x0018:
return RntbdResourceType.Schema;
case 0x0019:
return RntbdResourceType.BatchApply;
case 0x001A:
return RntbdResourceType.RestoreMetadata;
case 0x001B:
return RntbdResourceType.ComputeGatewayCharges;
case 0x001C:
return RntbdResourceType.RidRange;
case 0x001D:
return RntbdResourceType.UserDefinedType;
}
throw new IllegalArgumentException(Strings.lenientFormat("id: %s", id));
}
private static RntbdResourceType map(final ResourceType resourceType) {
switch (resourceType) {
case Attachment:
return RntbdResourceType.Attachment;
case DocumentCollection:
return RntbdResourceType.Collection;
case Conflict:
return RntbdResourceType.Conflict;
case Database:
return RntbdResourceType.Database;
case Document:
return RntbdResourceType.Document;
case Module:
return RntbdResourceType.Module;
case ModuleCommand:
return RntbdResourceType.ModuleCommand;
case Record:
return RntbdResourceType.Record;
case Permission:
return RntbdResourceType.Permission;
case Replica:
return RntbdResourceType.Replica;
case StoredProcedure:
return RntbdResourceType.StoredProcedure;
case Trigger:
return RntbdResourceType.Trigger;
case User:
return RntbdResourceType.User;
case UserDefinedType:
return RntbdResourceType.UserDefinedType;
case UserDefinedFunction:
return RntbdResourceType.UserDefinedFunction;
case Offer:
return RntbdResourceType.Offer;
case PartitionSetInformation:
return RntbdResourceType.PartitionSetInformation;
case XPReplicatorAddress:
return RntbdResourceType.XPReplicatorAddress;
case MasterPartition:
return RntbdResourceType.MasterPartition;
case ServerPartition:
return RntbdResourceType.ServerPartition;
case DatabaseAccount:
return RntbdResourceType.DatabaseAccount;
case Topology:
return RntbdResourceType.Topology;
case PartitionKeyRange:
return RntbdResourceType.PartitionKeyRange;
case Schema:
return RntbdResourceType.Schema;
case BatchApply:
return RntbdResourceType.BatchApply;
case RestoreMetadata:
return RntbdResourceType.RestoreMetadata;
case ComputeGatewayCharges:
return RntbdResourceType.ComputeGatewayCharges;
case RidRange:
return RntbdResourceType.RidRange;
default:
final String reason = Strings.lenientFormat("Unrecognized resource type: %s", resourceType);
throw new UnsupportedOperationException(reason);
}
}
private static RntbdOperationType map(final OperationType operationType) {
switch (operationType) {
case Crash:
return RntbdOperationType.Crash;
case Create:
return RntbdOperationType.Create;
case Delete:
return RntbdOperationType.Delete;
case ExecuteJavaScript:
return RntbdOperationType.ExecuteJavaScript;
case Query:
return RntbdOperationType.Query;
case Pause:
return RntbdOperationType.Pause;
case Read:
return RntbdOperationType.Read;
case ReadFeed:
return RntbdOperationType.ReadFeed;
case Recreate:
return RntbdOperationType.Recreate;
case Recycle:
return RntbdOperationType.Recycle;
case Replace:
return RntbdOperationType.Replace;
case Resume:
return RntbdOperationType.Resume;
case Stop:
return RntbdOperationType.Stop;
case SqlQuery:
return RntbdOperationType.SQLQuery;
case Update:
return RntbdOperationType.Update;
case ForceConfigRefresh:
return RntbdOperationType.ForceConfigRefresh;
case Head:
return RntbdOperationType.Head;
case HeadFeed:
return RntbdOperationType.HeadFeed;
case Upsert:
return RntbdOperationType.Upsert;
case Throttle:
return RntbdOperationType.Throttle;
case PreCreateValidation:
return RntbdOperationType.PreCreateValidation;
case GetSplitPoint:
return RntbdOperationType.GetSplitPoint;
case AbortSplit:
return RntbdOperationType.AbortSplit;
case CompleteSplit:
return RntbdOperationType.CompleteSplit;
case BatchApply:
return RntbdOperationType.BatchApply;
case OfferUpdateOperation:
return RntbdOperationType.OfferUpdateOperation;
case OfferPreGrowValidation:
return RntbdOperationType.OfferPreGrowValidation;
case BatchReportThroughputUtilization:
return RntbdOperationType.BatchReportThroughputUtilization;
case AbortPartitionMigration:
return RntbdOperationType.AbortPartitionMigration;
case CompletePartitionMigration:
return RntbdOperationType.CompletePartitionMigration;
case PreReplaceValidation:
return RntbdOperationType.PreReplaceValidation;
case MigratePartition:
return RntbdOperationType.MigratePartition;
case AddComputeGatewayRequestCharges:
return RntbdOperationType.AddComputeGatewayRequestCharges;
default:
final String reason = Strings.lenientFormat("Unrecognized operation type: %s", operationType);
throw new UnsupportedOperationException(reason);
}
}
/**
* Shortcut for {@link #get(Class)} to immediately fail if value not set. Supposed to be used by shared state
* consumers (to validate situations when value must exists for sure).
*
* @param key shared object key
* @param message exception message (could use {@link String#format(String, Object...)} placeholders)
* @param args placeholder arguments for error message
* @param <V> shared object type
* @return stored object (never null)
* @throws IllegalStateException if value not set
*/
public <V> V getOrFail(final Class<?> key, final String message, final Object... args) {
final V res = get(key);
if (res == null) {
throw new IllegalStateException(Strings.lenientFormat(message, args));
}
return res;
}
/**
* Throws {@link CorruptedFrameException} if {@code b} is false.
* @param b the expression to check
* @param message the message to include in the thrown {@link CorruptedFrameException}, formatted
* like {@link com.google.common.base.Preconditions#checkArgument(boolean)} and
* friends
* @param arg1 the first argument to format the message with
*/
public static void checkFrame(boolean b, String message, Object arg1) {
if (!b) {
throw new CorruptedFrameException(Strings.lenientFormat(message, arg1));
}
}
/**
* Throws {@link CorruptedFrameException} if {@code b} is false.
* @param b the expression to check
* @param message the message to include in the thrown {@link CorruptedFrameException}, formatted
* like {@link com.google.common.base.Preconditions#checkArgument(boolean)} and
* friends
* @param arg1 the first argument to format the message with
* @param arg2 the second argument to format the message with
*/
public static void checkFrame(boolean b, String message, Object arg1, Object arg2) {
if (!b) {
throw new CorruptedFrameException(Strings.lenientFormat(message, arg1, arg2));
}
}
/**
* Throws {@link CorruptedFrameException} if {@code b} is false.
* @param b the expression to check
* @param message the message to include in the thrown {@link CorruptedFrameException}, formatted
* like {@link com.google.common.base.Preconditions#checkArgument(boolean)} and
* friends
* @param args the arguments to format the message with-
*/
public static void checkFrame(boolean b, String message, Object... args) {
if (!b) {
throw new CorruptedFrameException(Strings.lenientFormat(message, args));
}
}