use of com.google.protobuf.Duration in project core-java by SpineEventEngine.
the class Commands method isScheduled.
/**
* Checks if the command is scheduled to be delivered later.
*
* @param command a command to check
* @return {@code true} if the command context has a scheduling option set,
* {@code false} otherwise
*/
public static boolean isScheduled(Command command) {
checkNotNull(command);
final Schedule schedule = command.getContext().getSchedule();
final Duration delay = schedule.getDelay();
if (isNotDefault(delay)) {
checkArgument(delay.getSeconds() > 0, "Command delay seconds must be a positive value.");
return true;
}
return false;
}
use of com.google.protobuf.Duration in project java-docs-samples by GoogleCloudPlatform.
the class Triggers method createTrigger.
// [START dlp_create_trigger]
/**
* Schedule a DLP inspection trigger for a GCS location.
*
* @param triggerId (Optional) name of the trigger to be created
* @param displayName (Optional) display name for the trigger to be created
* @param description (Optional) description for the trigger to be created
* @param scanPeriod How often to wait between scans, in days (minimum = 1 day)
* @param infoTypes infoTypes of information to match eg. InfoType.PHONE_NUMBER,
* InfoType.EMAIL_ADDRESS
* @param minLikelihood minimum likelihood required before returning a match
* @param maxFindings maximum number of findings to report per request (0 = server maximum)
* @param projectId The project ID to run the API call under
*/
private static void createTrigger(String triggerId, String displayName, String description, String bucketName, String fileName, int scanPeriod, List<InfoType> infoTypes, Likelihood minLikelihood, int maxFindings, String projectId) throws Exception {
// instantiate a client
DlpServiceClient dlpServiceClient = DlpServiceClient.create();
try {
CloudStorageOptions cloudStorageOptions = CloudStorageOptions.newBuilder().setFileSet(CloudStorageOptions.FileSet.newBuilder().setUrl("gs://" + bucketName + "/" + fileName)).build();
StorageConfig storageConfig = StorageConfig.newBuilder().setCloudStorageOptions(cloudStorageOptions).build();
InspectConfig.FindingLimits findingLimits = InspectConfig.FindingLimits.newBuilder().setMaxFindingsPerRequest(maxFindings).build();
InspectConfig inspectConfig = InspectConfig.newBuilder().addAllInfoTypes(infoTypes).setMinLikelihood(minLikelihood).setLimits(findingLimits).build();
InspectJobConfig inspectJobConfig = InspectJobConfig.newBuilder().setInspectConfig(inspectConfig).setStorageConfig(storageConfig).build();
// Schedule scan of GCS bucket every scanPeriod number of days (minimum = 1 day)
Duration duration = Duration.newBuilder().setSeconds(scanPeriod * 24 * 3600).build();
Schedule schedule = Schedule.newBuilder().setRecurrencePeriodDuration(duration).build();
JobTrigger.Trigger trigger = JobTrigger.Trigger.newBuilder().setSchedule(schedule).build();
JobTrigger jobTrigger = JobTrigger.newBuilder().setInspectJob(inspectJobConfig).setName(triggerId).setDisplayName(displayName).setDescription(description).setStatus(JobTrigger.Status.HEALTHY).addTriggers(trigger).build();
// Create scan request
CreateJobTriggerRequest createJobTriggerRequest = CreateJobTriggerRequest.newBuilder().setParent(ProjectName.of(projectId).toString()).setJobTrigger(jobTrigger).build();
JobTrigger createdJobTrigger = dlpServiceClient.createJobTrigger(createJobTriggerRequest);
System.out.println("Created Trigger: " + createdJobTrigger.getName());
} catch (Exception e) {
System.out.println("Error creating trigger: " + e.getMessage());
}
}
use of com.google.protobuf.Duration in project grpc-java by grpc.
the class BinlogHelperTest method clientDeadlineLogged_deadlineSetViaContext.
@Test
public void clientDeadlineLogged_deadlineSetViaContext() throws Exception {
// important: deadline is read from the ctx where call was created
final SettableFuture<ClientCall<byte[], byte[]>> callFuture = SettableFuture.create();
Context.current().withDeadline(Deadline.after(1, TimeUnit.SECONDS), Executors.newSingleThreadScheduledExecutor()).run(new Runnable() {
@Override
public void run() {
MethodDescriptor<byte[], byte[]> method = MethodDescriptor.<byte[], byte[]>newBuilder().setType(MethodType.UNKNOWN).setFullMethodName("service/method").setRequestMarshaller(BYTEARRAY_MARSHALLER).setResponseMarshaller(BYTEARRAY_MARSHALLER).build();
callFuture.set(new BinlogHelper(mockSinkWriter).getClientInterceptor(CALL_ID).interceptCall(method, CallOptions.DEFAULT.withDeadlineAfter(1, TimeUnit.SECONDS), new Channel() {
@Override
public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> newCall(MethodDescriptor<RequestT, ResponseT> methodDescriptor, CallOptions callOptions) {
return new NoopClientCall<>();
}
@Override
public String authority() {
return null;
}
}));
}
});
@SuppressWarnings("unchecked") ClientCall.Listener<byte[]> mockListener = mock(ClientCall.Listener.class);
callFuture.get().start(mockListener, new Metadata());
ArgumentCaptor<Duration> callOptTimeoutCaptor = ArgumentCaptor.forClass(Duration.class);
verify(mockSinkWriter).logClientHeader(anyLong(), anyString(), ArgumentMatchers.<String>any(), callOptTimeoutCaptor.capture(), any(Metadata.class), any(GrpcLogEntry.Logger.class), anyLong(), AdditionalMatchers.or(ArgumentMatchers.<SocketAddress>isNull(), ArgumentMatchers.<SocketAddress>any()));
Duration timeout = callOptTimeoutCaptor.getValue();
assertThat(TimeUnit.SECONDS.toNanos(1) - Durations.toNanos(timeout)).isAtMost(TimeUnit.MILLISECONDS.toNanos(250));
}
use of com.google.protobuf.Duration in project grpc-java by grpc.
the class BinlogHelperTest method serverDeadlineLogged.
@Test
public void serverDeadlineLogged() {
final MethodDescriptor<byte[], byte[]> method = MethodDescriptor.<byte[], byte[]>newBuilder().setType(MethodType.UNKNOWN).setFullMethodName("service/method").setRequestMarshaller(BYTEARRAY_MARSHALLER).setResponseMarshaller(BYTEARRAY_MARSHALLER).build();
final ServerCall<byte[], byte[]> noopServerCall = new NoopServerCall<byte[], byte[]>() {
@Override
public MethodDescriptor<byte[], byte[]> getMethodDescriptor() {
return method;
}
};
final ServerCallHandler<byte[], byte[]> noopHandler = new ServerCallHandler<byte[], byte[]>() {
@Override
public ServerCall.Listener<byte[]> startCall(ServerCall<byte[], byte[]> call, Metadata headers) {
return new ServerCall.Listener<byte[]>() {
};
}
};
// Warm-up JVM
new BinlogHelper(mock(SinkWriter.class)).getServerInterceptor(1234).interceptCall(noopServerCall, new Metadata(), noopHandler);
// We expect the contents of the "grpc-timeout" header to be installed the context
Context.current().withDeadlineAfter(1, TimeUnit.SECONDS, Executors.newSingleThreadScheduledExecutor()).run(new Runnable() {
@Override
public void run() {
ServerCall.Listener<byte[]> unused = new BinlogHelper(mockSinkWriter).getServerInterceptor(CALL_ID).interceptCall(noopServerCall, new Metadata(), noopHandler);
}
});
ArgumentCaptor<Duration> timeoutCaptor = ArgumentCaptor.forClass(Duration.class);
verify(mockSinkWriter).logClientHeader(/*seq=*/
eq(1L), eq("service/method"), ArgumentMatchers.<String>isNull(), timeoutCaptor.capture(), any(Metadata.class), eq(Logger.LOGGER_SERVER), eq(CALL_ID), ArgumentMatchers.<SocketAddress>isNull());
verifyNoMoreInteractions(mockSinkWriter);
Duration timeout = timeoutCaptor.getValue();
assertThat(TimeUnit.SECONDS.toNanos(1) - Durations.toNanos(timeout)).isAtMost(TimeUnit.MILLISECONDS.toNanos(250));
}
use of com.google.protobuf.Duration in project grpc-java by grpc.
the class BinlogHelperTest method logClientHeader.
@Test
public void logClientHeader() throws Exception {
long seq = 1;
String authority = "authority";
String methodName = "service/method";
Duration timeout = Durations.fromMillis(1234);
InetAddress address = InetAddress.getByName("127.0.0.1");
int port = 12345;
InetSocketAddress peerAddress = new InetSocketAddress(address, port);
long callId = 1000;
GrpcLogEntry.Builder builder = metadataToProtoTestHelper(EventType.EVENT_TYPE_CLIENT_HEADER, nonEmptyMetadata, 10).toBuilder().setTimestamp(timestamp).setSequenceIdWithinCall(seq).setLogger(Logger.LOGGER_CLIENT).setCallId(callId);
builder.getClientHeaderBuilder().setMethodName("/" + methodName).setAuthority(authority).setTimeout(timeout);
GrpcLogEntry base = builder.build();
{
sinkWriterImpl.logClientHeader(seq, methodName, authority, timeout, nonEmptyMetadata, Logger.LOGGER_CLIENT, callId, /*peerAddress=*/
null);
verify(sink).write(base);
}
// logger is server
{
sinkWriterImpl.logClientHeader(seq, methodName, authority, timeout, nonEmptyMetadata, Logger.LOGGER_SERVER, callId, peerAddress);
verify(sink).write(base.toBuilder().setPeer(BinlogHelper.socketToProto(peerAddress)).setLogger(Logger.LOGGER_SERVER).build());
}
// authority is null
{
sinkWriterImpl.logClientHeader(seq, methodName, /*authority=*/
null, timeout, nonEmptyMetadata, Logger.LOGGER_CLIENT, callId, /*peerAddress=*/
null);
verify(sink).write(base.toBuilder().setClientHeader(builder.getClientHeader().toBuilder().clearAuthority().build()).build());
}
// timeout is null
{
sinkWriterImpl.logClientHeader(seq, methodName, authority, /*timeout=*/
null, nonEmptyMetadata, Logger.LOGGER_CLIENT, callId, /*peerAddress=*/
null);
verify(sink).write(base.toBuilder().setClientHeader(builder.getClientHeader().toBuilder().clearTimeout().build()).build());
}
// peerAddress is non null (error for client side)
try {
sinkWriterImpl.logClientHeader(seq, methodName, authority, timeout, nonEmptyMetadata, Logger.LOGGER_CLIENT, callId, peerAddress);
fail();
} catch (IllegalArgumentException expected) {
// noop
}
}
Aggregations