Search in sources :

Example 51 with Duration

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;
}
Also used : Schedule(io.spine.core.CommandContext.Schedule) Duration(com.google.protobuf.Duration)

Example 52 with Duration

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());
    }
}
Also used : StorageConfig(com.google.privacy.dlp.v2.StorageConfig) DlpServiceClient(com.google.cloud.dlp.v2.DlpServiceClient) Schedule(com.google.privacy.dlp.v2.Schedule) CloudStorageOptions(com.google.privacy.dlp.v2.CloudStorageOptions) Duration(com.google.protobuf.Duration) InspectConfig(com.google.privacy.dlp.v2.InspectConfig) JobTrigger(com.google.privacy.dlp.v2.JobTrigger) ParseException(org.apache.commons.cli.ParseException) InspectJobConfig(com.google.privacy.dlp.v2.InspectJobConfig) CreateJobTriggerRequest(com.google.privacy.dlp.v2.CreateJobTriggerRequest)

Example 53 with Duration

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));
}
Also used : Channel(io.grpc.Channel) Metadata(io.grpc.Metadata) Duration(com.google.protobuf.Duration) CallOptions(io.grpc.CallOptions) ByteString(com.google.protobuf.ByteString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Logger(io.grpc.binarylog.v1.GrpcLogEntry.Logger) MethodDescriptor(io.grpc.MethodDescriptor) ClientCall(io.grpc.ClientCall) NoopClientCall(io.grpc.internal.NoopClientCall) SocketAddress(java.net.SocketAddress) DomainSocketAddress(io.netty.channel.unix.DomainSocketAddress) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.Test)

Example 54 with Duration

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));
}
Also used : ServerCallHandler(io.grpc.ServerCallHandler) Metadata(io.grpc.Metadata) Duration(com.google.protobuf.Duration) SinkWriter(io.grpc.protobuf.services.BinlogHelper.SinkWriter) NoopServerCall(io.grpc.internal.NoopServerCall) NoopServerCall(io.grpc.internal.NoopServerCall) ServerCall(io.grpc.ServerCall) Test(org.junit.Test)

Example 55 with Duration

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
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) GrpcLogEntry(io.grpc.binarylog.v1.GrpcLogEntry) Duration(com.google.protobuf.Duration) ByteString(com.google.protobuf.ByteString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) InetAddress(java.net.InetAddress) Test(org.junit.Test)

Aggregations

Duration (com.google.protobuf.Duration)58 Test (org.junit.Test)37 Timestamp (com.google.protobuf.Timestamp)25 AbstractZonedTimeTest (io.spine.time.AbstractZonedTimeTest)8 LocalTime (io.spine.time.LocalTime)8 ByteString (com.google.protobuf.ByteString)7 Metadata (io.grpc.Metadata)7 InetSocketAddress (java.net.InetSocketAddress)7 SocketAddress (java.net.SocketAddress)6 Command (io.spine.core.Command)5 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)5 CallOptions (io.grpc.CallOptions)4 Channel (io.grpc.Channel)4 ClientCall (io.grpc.ClientCall)4 MethodDescriptor (io.grpc.MethodDescriptor)4 Status (io.grpc.Status)4 Message (com.google.protobuf.Message)3 ServerCall (io.grpc.ServerCall)3 DomainSocketAddress (io.netty.channel.unix.DomainSocketAddress)3 Schedule (io.spine.core.CommandContext.Schedule)3