index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DefaultChildWorkflowIdHandler.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; import java.util.function.Supplier; public class DefaultChildWorkflowIdHandler implements ChildWorkflowIdHandler { @Override public String generateWorkflowId(WorkflowExecution currentWorkflow, Supplier<String> nextId) { return String.format("%s:%s", currentWorkflow.getRunId(), nextId.get()); } @Override public String extractRequestedWorkflowId(String childWorkflowId) { return childWorkflowId; } }
3,500
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowClientFactoryBase.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow; import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClient; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; public abstract class WorkflowClientFactoryBase<T> implements WorkflowClientFactory<T> { private GenericWorkflowClient genericClient; private DataConverter dataConverter; private StartWorkflowOptions startWorkflowOptions = new StartWorkflowOptions(); private final DecisionContextProvider decisionContextProvider = new DecisionContextProviderImpl(); public WorkflowClientFactoryBase() { this(null, null, null); } public WorkflowClientFactoryBase(StartWorkflowOptions startWorkflowOptions) { this(startWorkflowOptions, null, null); } public WorkflowClientFactoryBase(StartWorkflowOptions startWorkflowOptions, DataConverter dataConverter) { this(startWorkflowOptions, dataConverter, null); } public WorkflowClientFactoryBase(StartWorkflowOptions startWorkflowOptions, DataConverter dataConverter, GenericWorkflowClient genericClient) { this.startWorkflowOptions = startWorkflowOptions; if (dataConverter == null) { this.dataConverter = new JsonDataConverter(); } else { this.dataConverter = dataConverter; } this.genericClient = genericClient; } @Override public GenericWorkflowClient getGenericClient() { return genericClient; } @Override public void setGenericClient(GenericWorkflowClient genericClient) { this.genericClient = genericClient; } @Override public DataConverter getDataConverter() { return dataConverter; } @Override public void setDataConverter(DataConverter dataConverter) { this.dataConverter = dataConverter; } @Override public StartWorkflowOptions getStartWorkflowOptions() { return startWorkflowOptions; } @Override public void setStartWorkflowOptions(StartWorkflowOptions startWorkflowOptions) { this.startWorkflowOptions = startWorkflowOptions; } @Override public T getClient() { GenericWorkflowClient client = getGenericClientToUse(); String workflowId = client.generateUniqueId(); WorkflowExecution execution = new WorkflowExecution().withWorkflowId(workflowId); return getClient(execution, startWorkflowOptions, dataConverter); } @Override public T getClient(String workflowId) { if (workflowId == null || workflowId.isEmpty()) { throw new IllegalArgumentException("workflowId"); } WorkflowExecution execution = new WorkflowExecution().withWorkflowId(workflowId); return getClient(execution, startWorkflowOptions, dataConverter); } @Override public T getClient(WorkflowExecution execution) { return getClient(execution, startWorkflowOptions, dataConverter); } @Override public T getClient(WorkflowExecution execution, StartWorkflowOptions options) { return getClient(execution, options, dataConverter); } @Override public T getClient(WorkflowExecution execution, StartWorkflowOptions options, DataConverter dataConverter) { GenericWorkflowClient client = getGenericClientToUse(); return createClientInstance(execution, options, dataConverter, client); } private GenericWorkflowClient getGenericClientToUse() { GenericWorkflowClient result; if (genericClient == null) { result = decisionContextProvider.getDecisionContext().getWorkflowClient(); } else { result = genericClient; } return result; } protected abstract T createClientInstance(WorkflowExecution execution, StartWorkflowOptions options, DataConverter dataConverter, GenericWorkflowClient genericClient); }
3,501
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ActivityTaskTimedOutException.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow; import com.amazonaws.services.simpleworkflow.model.ActivityTaskTimeoutType; import com.amazonaws.services.simpleworkflow.model.ActivityType; /** * Exception that indicates Activity time out. */ @SuppressWarnings("serial") public class ActivityTaskTimedOutException extends ActivityTaskException { private ActivityTaskTimeoutType timeoutType; private String details; public ActivityTaskTimedOutException(String message, Throwable cause) { super(message, cause); } public ActivityTaskTimedOutException(String message) { super(message); } public ActivityTaskTimedOutException(long eventId, ActivityType activityType, String activityId, String timeoutType, String details) { super(timeoutType, eventId, activityType, activityId); this.timeoutType = ActivityTaskTimeoutType.fromValue(timeoutType); this.details = details; } public ActivityTaskTimeoutType getTimeoutType() { return timeoutType; } public void setTimeoutType(ActivityTaskTimeoutType timeoutType) { this.timeoutType = timeoutType; } /** * @return The value from the last activity heartbeat details field. */ public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } }
3,502
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ActivitiesClientBase.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.generic.GenericActivityClient; import com.amazonaws.services.simpleworkflow.model.ActivityType; public abstract class ActivitiesClientBase implements ActivitiesClient { protected DynamicActivitiesClientImpl dynamicActivitiesClient; protected ActivitiesClientBase(GenericActivityClient genericClient, DataConverter dataConverter, ActivitySchedulingOptions schedulingOptions) { this.dynamicActivitiesClient = new DynamicActivitiesClientImpl(schedulingOptions, dataConverter, genericClient); } protected <T> Promise<T> scheduleActivity(ActivityType activityType, Promise<?>[] arguments, ActivitySchedulingOptions optionsOverride, Class<T> returnType, Promise<?>... waitFor) { return dynamicActivitiesClient.scheduleActivity(activityType, arguments, optionsOverride, returnType, waitFor); } protected <T> Promise<T> scheduleActivity(ActivityType activityType, Object[] arguments, ActivitySchedulingOptions optionsOverride, Class<T> returnType, Promise<?>... waitFor) { return dynamicActivitiesClient.scheduleActivity(activityType, arguments, optionsOverride, returnType, waitFor); } @Override public DataConverter getDataConverter() { return dynamicActivitiesClient.getDataConverter(); } public void setDataConverter(DataConverter converter) { dynamicActivitiesClient.setDataConverter(converter); } @Override public ActivitySchedulingOptions getSchedulingOptions() { return dynamicActivitiesClient.getSchedulingOptions(); } public void setSchedulingOptions(ActivitySchedulingOptions schedulingOptions) { dynamicActivitiesClient.setSchedulingOptions(schedulingOptions); } @Override public GenericActivityClient getGenericClient() { return dynamicActivitiesClient.getGenericClient(); } public void setGenericClient(GenericActivityClient genericClient) { dynamicActivitiesClient.setGenericClient(genericClient); } }
3,503
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ChildWorkflowFailedException.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; import com.amazonaws.services.simpleworkflow.model.WorkflowType; @SuppressWarnings("serial") public class ChildWorkflowFailedException extends ChildWorkflowException { private String details; public ChildWorkflowFailedException(String message) { super(message); } public ChildWorkflowFailedException(String message, Throwable cause) { super(message, cause); } public ChildWorkflowFailedException(long eventId, WorkflowExecution workflowExecution, WorkflowType workflowType, String reason, String details) { super(createMessage(workflowExecution, workflowType, reason), eventId, workflowExecution, workflowType); this.details = details; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } private static String createMessage(WorkflowExecution workflowExecution, WorkflowType workflowType, String reason) { return "name=" + workflowType.getName() + ", version=" + workflowType.getVersion() + ", workflowId=" + workflowExecution.getWorkflowId() + ", runId=" + workflowExecution.getRunId() + ": " + reason; } }
3,504
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ActivityExecutionContext.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow; import java.util.concurrent.CancellationException; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.annotations.ManualActivityCompletion; import com.amazonaws.services.simpleworkflow.flow.generic.ActivityImplementation; import com.amazonaws.services.simpleworkflow.model.ActivityTask; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; /** * Context object passed to an activity implementation. * * @see ActivityImplementation * * @author fateev */ public abstract class ActivityExecutionContext { /** * @return task token that is required to report task completion when * {@link ManualActivityCompletion} is used. */ public abstract String getTaskToken(); /** * @return workfow execution that requested the activity execution */ public abstract WorkflowExecution getWorkflowExecution(); /** * @return task that caused activity execution */ public abstract ActivityTask getTask(); /** * Use to notify Simple Workflow that activity execution is alive. * * @param details * In case of activity timeout details are returned as a field of * the exception thrown. * @throws AmazonClientException * If any internal errors are encountered inside the client * while attempting to make the request or handle the response. * For example if a network connection is not available. * @throws AmazonServiceException * If an error response is returned by AmazonSimpleWorkflow * indicating either a problem with the data in the request. * Internal service errors are swallowed and not propagated to * the caller. * @throws CancellationException * Indicates that activity cancellation was requested by the * workflow.Should be rethrown from activity implementation to * indicate successful cancellation. */ public abstract void recordActivityHeartbeat(String details) throws AmazonServiceException, AmazonClientException, CancellationException; /** * @return an instance of the Simple Workflow Java client that is the same * used by the invoked activity worker. */ public abstract AmazonSimpleWorkflow getService(); public String getDomain() { // Throwing implementation is provided to not break existing subclasses throw new UnsupportedOperationException(); } }
3,505
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/AsyncRunnable.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; /** * Serves the same purpose as {@link Runnable}, but avoids special handling of checked exceptions. * * @see AsyncExecutor */ public interface AsyncRunnable { public void run() throws Throwable; }
3,506
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/AsyncCancelAndRetryExecutor.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import java.util.concurrent.CancellationException; import com.amazonaws.services.simpleworkflow.flow.core.Cancelable; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.core.Task; import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally; /** * Cancels and reexecutes a command when {@link #cancelCurrentAndReexecute()} is * called. In case of command failures or successful completions it is not * reexecuted. * * @author fateev */ public class AsyncCancelAndRetryExecutor implements AsyncExecutor { private Cancelable currentCommandTryCatchFinally; private Settable<Void> commandDone; /** * Used to inhibit retry in case of failures or successful completions */ private boolean cancelledDueToRetryRequest; protected AsyncRunnable command; @Override public void execute(final AsyncRunnable cmd) { if (currentCommandTryCatchFinally != null) { throw new IllegalStateException("Already executing a command"); } command = cmd; currentCommandTryCatchFinally = new TryCatchFinally() { @Override protected void doTry() throws Throwable { cmd.run(); } @Override protected void doCatch(Throwable e) throws Throwable { if (e instanceof CancellationException && commandDone != null) { cancelledDueToRetryRequest = true; } else { throw e; } } @Override protected void doFinally() throws Throwable { if (!cancelledDueToRetryRequest) { command = null; } if (commandDone != null) { commandDone.set(null); } commandDone = null; currentCommandTryCatchFinally = null; } }; } public void cancelCurrentAndReexecute() { if (currentCommandTryCatchFinally != null) { // Skip duplicated calls to cancelCurrentAndReexecute if (commandDone == null) { commandDone = new Settable<Void>(); currentCommandTryCatchFinally.cancel(null); new Task(commandDone) { @Override protected void doExecute() throws Throwable { if (cancelledDueToRetryRequest) { execute(command); } } }; } } } }
3,507
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/FixedIntervalInvocationSchedule.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import java.util.Date; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; /** * Schedule that represents invocations with a fixed delay up to a specified expiration interval or count. * * @author fateev */ public class FixedIntervalInvocationSchedule implements InvocationSchedule { protected static final int SECOND = 1000; private final long intervalMilliseconds; private final long expirationMilliseconds; private final int maxInvocationCount; public FixedIntervalInvocationSchedule(int intervalSeconds, int expirationSeconds, int maxInvocationCount) { this.intervalMilliseconds = intervalSeconds * SECOND; this.expirationMilliseconds = expirationSeconds * SECOND; this.maxInvocationCount = maxInvocationCount; } public FixedIntervalInvocationSchedule(int intervalSeconds, int expirationSeconds) { this.intervalMilliseconds = intervalSeconds * SECOND; this.expirationMilliseconds = expirationSeconds * SECOND; this.maxInvocationCount = Integer.MAX_VALUE; } @Override public long nextInvocationDelaySeconds(Date currentTime, Date startTime, Date lastInvocationTime, int pastInvocatonsCount) { if (pastInvocatonsCount >= maxInvocationCount) { return FlowConstants.NONE; } long resultMilliseconds; if (lastInvocationTime == null) { resultMilliseconds = startTime.getTime() + intervalMilliseconds - currentTime.getTime(); } else { resultMilliseconds = lastInvocationTime.getTime() + intervalMilliseconds - currentTime.getTime(); } if (resultMilliseconds < 0) { resultMilliseconds = 0; } if (currentTime.getTime() + resultMilliseconds - startTime.getTime() >= expirationMilliseconds) { return FlowConstants.NONE; } return resultMilliseconds / SECOND; } }
3,508
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/RetryCallable.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import com.amazonaws.services.simpleworkflow.flow.core.Promise; public interface RetryCallable<T> { Promise<T> call() throws Throwable; }
3,509
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/InvocationSchedule.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import java.util.Date; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; /** * Encapsulates an invocation schedule. * * @see AsyncScheduledExecutor * @see ScheduleDecorator * @author fateev */ public interface InvocationSchedule { /** * Return interval until the next invocation. * * @param currentTime * - current workflow time * @param startTime * - time when workflow started * @param lastInvocationTime * - time when last invocation happened * @param pastInvocatonsCount * - how many invocations were done * @return time in seconds until the next invocation. * {@link FlowConstants#NONE} if no more invocations should be * scheduled. */ long nextInvocationDelaySeconds(Date currentTime, Date startTime, Date lastInvocationTime, int pastInvocatonsCount); }
3,510
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/RetryDecorator.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProviderImpl; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Settable; /** * In case of failures repeats every call to a wrapped object method according * the provided {@link RetryPolicy}. * * @author fateev */ public class RetryDecorator implements Decorator { private final AsyncRetryingExecutor executor; public RetryDecorator(RetryPolicy retryPolicy, WorkflowClock clock) { executor = new AsyncRetryingExecutor(retryPolicy, clock); } public RetryDecorator(RetryPolicy retryPolicy) { this(retryPolicy, new DecisionContextProviderImpl().getDecisionContext().getWorkflowClock()); } @SuppressWarnings("unchecked") @Override public final <V> V decorate(Class<V> interfaces, V object) { Class<?>[] interfazes = { interfaces }; return (V) Proxy.newProxyInstance(object.getClass().getClassLoader(), interfazes, new DecoratorInvocationHandler(object)); } @SuppressWarnings("unchecked") @Override public final <V> V decorate(Class<?>[] interfaces, V object) { return (V) Proxy.newProxyInstance(object.getClass().getClassLoader(), interfaces, new DecoratorInvocationHandler(object)); } private final class DecoratorInvocationHandler implements InvocationHandler { @SuppressWarnings({ "unchecked", "rawtypes" }) private final class RetriedRunnable implements AsyncRunnable { private final Object[] args; private final Method method; private Settable result; private RetriedRunnable(Object[] args, Method method) { this.args = args; Class<?> returnType = method.getReturnType(); boolean voidReturnType = Void.TYPE.equals(returnType); if (!voidReturnType) { if (!Promise.class.isAssignableFrom(returnType)) { throw new IllegalArgumentException("Cannot decorate " + method.getName() + " as its return type is not void or Promise"); } result = new Settable(); } this.method = method; } @Override public void run() throws Throwable { if (result == null) { // void return type method.invoke(object, args); } else { // Need to unchain as it could be chained to the result of the previous run invocation result.unchain(); result.chain((Promise) method.invoke(object, args)); } } public Promise getResult() { return result; } } private final Object object; public DecoratorInvocationHandler(Object object) { this.object = object; } @Override public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { try { if (!isDecorated(method, args)) { return method.invoke(object, args); } } catch (InvocationTargetException ite) { throw ite.getTargetException(); } RetriedRunnable command = new RetriedRunnable(args, method); executor.execute(command); return command.getResult(); } } protected boolean isDecorated(Method method, Object[] args) { return !method.getDeclaringClass().equals(Object.class); } }
3,511
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/RetryPolicy.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import java.util.Date; import com.amazonaws.services.simpleworkflow.flow.annotations.ExponentialRetry; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; /** * Defines retry policy in case of failures. Valid implementation should be * stateless and thread safe. * * @see RetryDecorator * @see ExponentialRetry */ public interface RetryPolicy { boolean isRetryable(Throwable failure); /** * @return Time to the next retry. {@link FlowConstants#NONE} means stop * retrying. */ long nextRetryDelaySeconds(Date firstAttempt, Date recordedFailure, int numberOfTries); }
3,512
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/Decorator.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; public interface Decorator { public <V> V decorate(Class<V> interfaces, V object); public <V> V decorate(Class<?>[] interfaces, V object); }
3,513
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/RetryPolicyBase.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.amazonaws.services.simpleworkflow.flow.DecisionException; public abstract class RetryPolicyBase implements RetryPolicy { private List<Class<? extends Throwable>> exceptionsToRetry; private List<Class<? extends Throwable>> exceptionsToExclude; public List<Class<? extends Throwable>> getExceptionsToRetry() { if (exceptionsToRetry == null) { exceptionsToRetry = new ArrayList<Class<? extends Throwable>>(); exceptionsToRetry.add(Throwable.class); } return exceptionsToRetry; } public void setExceptionsToRetry(List<Class<? extends Throwable>> exceptionsToRetry) { List<Class<? extends Throwable>> exceptionsToRetryCopy = new ArrayList<Class<? extends Throwable>>(); if (exceptionsToRetry != null) { exceptionsToRetryCopy.addAll(exceptionsToRetry); } this.exceptionsToRetry = exceptionsToRetryCopy; } public RetryPolicyBase withExceptionsToRetry(Collection<Class<? extends Throwable>> exceptionsToRetry) { List<Class<? extends Throwable>> exceptionsToRetryCopy = new ArrayList<Class<? extends Throwable>>(); if (exceptionsToRetry != null) { exceptionsToRetryCopy.addAll(exceptionsToRetry); } this.exceptionsToRetry = exceptionsToRetryCopy; return this; } public List<Class<? extends Throwable>> getExceptionsToExclude() { if (exceptionsToExclude == null) { exceptionsToExclude = new ArrayList<Class<? extends Throwable>>(); } return exceptionsToExclude; } public void setExceptionsToExclude(List<Class<? extends Throwable>> exceptionsToExclude) { List<Class<? extends Throwable>> exceptionsToExcludeCopy = new ArrayList<Class<? extends Throwable>>(); if (exceptionsToExclude != null) { exceptionsToExcludeCopy.addAll(exceptionsToExclude); } this.exceptionsToExclude = exceptionsToExcludeCopy; } public RetryPolicyBase withExceptionsToExclude(Collection<Class<? extends Throwable>> exceptionsToExclude) { List<Class<? extends Throwable>> exceptionsToExcludeCopy = new ArrayList<Class<? extends Throwable>>(); if (exceptionsToExclude != null) { exceptionsToExcludeCopy.addAll(exceptionsToExclude); } this.exceptionsToExclude = exceptionsToExcludeCopy; return this; } @Override public boolean isRetryable(Throwable failure) { boolean isRetryable = false; if (failure instanceof DecisionException && failure.getCause() != null) { failure = failure.getCause(); } for (Class<? extends Throwable> exceptionToRetry: getExceptionsToRetry()) { if (exceptionToRetry.isAssignableFrom(failure.getClass())) { isRetryable = true; break; } } if (isRetryable) { for (Class<? extends Throwable> exceptionNotToRetry: getExceptionsToExclude()) { if (exceptionNotToRetry.isAssignableFrom(failure.getClass())) { isRetryable = false; break; } } } return isRetryable; } }
3,514
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/AsyncRetryingExecutor.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import java.util.Date; import java.util.concurrent.CancellationException; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.core.Task; import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally; /** * Retries failed command according to the specified retryPolicy. * * @author fateev */ public class AsyncRetryingExecutor implements AsyncExecutor { private final RetryPolicy retryPolicy; private WorkflowClock clock; public AsyncRetryingExecutor(RetryPolicy retryPolicy, WorkflowClock clock) { this.retryPolicy = retryPolicy; this.clock = clock; } @Override public void execute(final AsyncRunnable command) { // Task is used only to avoid wrapping Throwable thrown from scheduleWithRetry new Task() { @Override protected void doExecute() throws Throwable { scheduleWithRetry(command, null, 1, clock.currentTimeMillis(), 0); } }; } private void scheduleWithRetry(final AsyncRunnable command, final Throwable failure, final int attempt, final long firstAttemptTime, final long timeOfRecordedFailure) throws Throwable { long delay = -1; if (attempt > 1) { if (!retryPolicy.isRetryable(failure)) { throw failure; } delay = retryPolicy.nextRetryDelaySeconds(new Date(firstAttemptTime), new Date(timeOfRecordedFailure), attempt); if (delay < 0) { throw failure; } } if (delay > 0) { Promise<Void> timer = clock.createTimer(delay); new Task(timer) { @Override protected void doExecute() throws Throwable { invoke(command, attempt, firstAttemptTime); } }; } else { invoke(command, attempt, firstAttemptTime); } } private void invoke(final AsyncRunnable command, final int attempt, final long firstAttemptTime) { final Settable<Throwable> shouldRetry = new Settable<Throwable>(); new TryCatchFinally() { Throwable failureToRetry = null; @Override protected void doTry() throws Throwable { command.run(); } @Override protected void doCatch(Throwable failure) throws Throwable { if (failure instanceof CancellationException) { throw failure; } failureToRetry = failure; } @Override protected void doFinally() throws Throwable { shouldRetry.set(failureToRetry); } }; new Task(shouldRetry) { @Override protected void doExecute() throws Throwable { Throwable failure = shouldRetry.get(); if (failure != null) { scheduleWithRetry(command, failure, attempt + 1, firstAttemptTime, clock.currentTimeMillis()); } } }; } }
3,515
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/AsyncExecutor.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import java.util.concurrent.Executor; /** * Serves the same purpose as {@link Executor}, but in asynchronous world. The * difference from {@link Executor} is that checked exceptions are not treated * differently then runtime ones as {@link AsyncRunnable#run()} throws * Throwable. */ public interface AsyncExecutor { public void execute(AsyncRunnable command); }
3,516
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/AsyncScheduledExecutor.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import java.util.Date; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.core.Task; import com.amazonaws.services.simpleworkflow.flow.core.TryFinally; /** * AsyncExecutor implementation that executes commands according to a provided * schedule. Commands are expected to contain only non blocking asynchronous * code. * * @author fateev */ public class AsyncScheduledExecutor implements AsyncExecutor { private final InvocationSchedule schedule; private final WorkflowClock clock; public AsyncScheduledExecutor(InvocationSchedule schedule, WorkflowClock clock) { this.schedule = schedule; this.clock = clock; } public void execute(AsyncRunnable command) { scheduleNext(command, new Date(clock.currentTimeMillis()), 0, Promise.asPromise((Date) null)); } private void scheduleNext(final AsyncRunnable command, Date startTime, int pastInvocationsCount, final Promise<Date> invoked) { Date currentTime = new Date(clock.currentTimeMillis()); long nextInvocationDelay = schedule.nextInvocationDelaySeconds(currentTime, startTime, invoked.get(), pastInvocationsCount); if (nextInvocationDelay >= 0) { Promise<Void> nextInvocationTimer = clock.createTimer(nextInvocationDelay); // Recursing from task (or @Asynchronous) is always OK executeAccordingToSchedule(command, startTime, pastInvocationsCount, nextInvocationTimer); } } private void executeAccordingToSchedule(final AsyncRunnable command, final Date startTime, final int pastInvocationsCount, Promise<Void> nextInvocationTimer) { final Settable<Date> invoked = new Settable<Date>(); new TryFinally(nextInvocationTimer) { private Date lastInvocationTime; @Override protected void doTry() throws Throwable { lastInvocationTime = new Date(clock.currentTimeMillis()); command.run(); } @Override protected void doFinally() throws Throwable { // It is common mistake to recurse from doFinally or doCatch. // As code in doFinally and in doCatch is non cancelable it // makes the whole branch non cancelable which is usually // not intended. invoked.set(lastInvocationTime); } }; new Task(invoked) { @Override protected void doExecute() throws Throwable { scheduleNext(command, startTime, pastInvocationsCount + 1, invoked); } }; } }
3,517
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/ScheduleDecorator.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProviderImpl; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.core.TryFinally; /** * Repeats every call to a wrapped object method according to provided schedule. * If {@link RetryPolicy} is provided calls that fail are retried according to * it. Retry count is reset at each scheduled invocation. * * @author fateev */ public class ScheduleDecorator implements Decorator { private final class DecoratorInvocationHandler implements InvocationHandler { private final Object object; public DecoratorInvocationHandler(Object object) { this.object = object; } @Override public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { try { if (!isDecorated(method, args)) { return method.invoke(object, args); } } catch (InvocationTargetException ite) { throw ite.getTargetException(); } Class<?> returnType = method.getReturnType(); boolean isVoidReturnType = Void.TYPE.equals(returnType); final Settable<Object> result = isVoidReturnType ? null : new Settable<Object>(); new TryFinally() { Object r; @Override protected void doTry() throws Throwable { scheduledExecutor.execute(new AsyncRunnable() { @Override public void run() throws Throwable { try { r = method.invoke(object, args); } catch (InvocationTargetException ite) { throw ite.getTargetException(); } } }); } @Override protected void doFinally() throws Throwable { if (result != null) { result.set(r); } } }; return result; } } private final AsyncScheduledExecutor scheduledExecutor; public ScheduleDecorator(InvocationSchedule schedule, WorkflowClock clock) { scheduledExecutor = new AsyncScheduledExecutor(schedule, clock); } public ScheduleDecorator(InvocationSchedule schedule) { this(schedule, new DecisionContextProviderImpl().getDecisionContext().getWorkflowClock()); } @SuppressWarnings("unchecked") @Override public final <V> V decorate(Class<V> interfaces, V object) { Class<?>[] interfazes = { interfaces }; return (V) Proxy.newProxyInstance(object.getClass().getClassLoader(), interfazes, new DecoratorInvocationHandler(object)); } @SuppressWarnings("unchecked") @Override public final <V> V decorate(Class<?>[] interfaces, V object) { return (V) Proxy.newProxyInstance(object.getClass().getClassLoader(), interfaces, new DecoratorInvocationHandler(object)); } private boolean isDecorated(Method method, Object[] args) { return !method.getDeclaringClass().equals(Object.class); } }
3,518
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/ExponentialRetryPolicy.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import java.util.Collection; import java.util.Date; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.flow.common.FlowDefaults; public class ExponentialRetryPolicy extends RetryPolicyBase { private final long initialRetryIntervalSeconds; private long maximumRetryIntervalSeconds = FlowDefaults.EXPONENTIAL_RETRY_MAXIMUM_RETRY_INTERVAL_SECONDS; private long retryExpirationIntervalSeconds = FlowDefaults.EXPONENTIAL_RETRY_RETRY_EXPIRATION_SECONDS; private double backoffCoefficient = FlowDefaults.EXPONENTIAL_RETRY_BACKOFF_COEFFICIENT; private int maximumAttempts = FlowDefaults.EXPONENTIAL_RETRY_MAXIMUM_ATTEMPTS; public ExponentialRetryPolicy(long initialRetryIntervalSeconds) { this.initialRetryIntervalSeconds = initialRetryIntervalSeconds; } public long getInitialRetryIntervalSeconds() { return initialRetryIntervalSeconds; } public long getMaximumRetryIntervalSeconds() { return maximumRetryIntervalSeconds; } /** * Set the upper limit of retry interval. No limit by default. */ public void setMaximumRetryIntervalSeconds(long maximumRetryIntervalSeconds) { this.maximumRetryIntervalSeconds = maximumRetryIntervalSeconds; } public ExponentialRetryPolicy withMaximumRetryIntervalSeconds(long maximumRetryIntervalSeconds) { this.maximumRetryIntervalSeconds = maximumRetryIntervalSeconds; return this; } public long getRetryExpirationIntervalSeconds() { return retryExpirationIntervalSeconds; } /** * Stop retrying after the specified interval. */ public void setRetryExpirationIntervalSeconds(long retryExpirationIntervalSeconds) { this.retryExpirationIntervalSeconds = retryExpirationIntervalSeconds; } public ExponentialRetryPolicy withRetryExpirationIntervalSeconds(long retryExpirationIntervalSeconds) { this.retryExpirationIntervalSeconds = retryExpirationIntervalSeconds; return this; } public double getBackoffCoefficient() { return backoffCoefficient; } /** * Coefficient used to calculate the next retry interval. The following * formula is used: * <code>initialRetryIntervalSeconds * Math.pow(backoffCoefficient, numberOfTries - 2)</code> */ public void setBackoffCoefficient(double backoffCoefficient) { this.backoffCoefficient = backoffCoefficient; } public ExponentialRetryPolicy withBackoffCoefficient(double backoffCoefficient) { this.backoffCoefficient = backoffCoefficient; return this; } public int getMaximumAttempts() { return maximumAttempts; } /** * Maximum number of attempts. The first retry is second attempt. */ public void setMaximumAttempts(int maximumAttempts) { this.maximumAttempts = maximumAttempts; } public ExponentialRetryPolicy withMaximumAttempts(int maximumAttempts) { this.maximumAttempts = maximumAttempts; return this; } /** * The exception types that cause operation being retried. Subclasses of the * specified types are also included. Default is Throwable.class which means * retry any exceptions. */ @Override public ExponentialRetryPolicy withExceptionsToRetry(Collection<Class<? extends Throwable>> exceptionsToRetry) { super.withExceptionsToRetry(exceptionsToRetry); return this; } /** * The exception types that should not be retried. Subclasses of the * specified types are also not retried. Default is empty list. */ @Override public ExponentialRetryPolicy withExceptionsToExclude(Collection<Class<? extends Throwable>> exceptionsToRetry) { super.withExceptionsToExclude(exceptionsToRetry); return this; } @Override public long nextRetryDelaySeconds(Date firstAttempt, Date recordedFailure, int numberOfTries) { if (numberOfTries < 2) { throw new IllegalArgumentException("attempt is less then 2: " + numberOfTries); } if (maximumAttempts > FlowConstants.NONE && numberOfTries > maximumAttempts) { return FlowConstants.NONE; } long result = (long) (initialRetryIntervalSeconds * Math.pow(backoffCoefficient, numberOfTries - 2)); result = maximumRetryIntervalSeconds > FlowConstants.NONE ? Math.min(result, maximumRetryIntervalSeconds) : result; int secondsSinceFirstAttempt = (int) ((recordedFailure.getTime() - firstAttempt.getTime()) / 1000); if (retryExpirationIntervalSeconds > FlowConstants.NONE && secondsSinceFirstAttempt + result >= retryExpirationIntervalSeconds) { return FlowConstants.NONE; } return result; } /** * Performs the following three validation checks for ExponentialRetry * Policy: 1) initialRetryIntervalSeconds is not greater than * maximumRetryIntervalSeconds 2) initialRetryIntervalSeconds is not greater * than retryExpirationIntervalSeconds */ public void validate() throws IllegalStateException { if (maximumRetryIntervalSeconds > FlowConstants.NONE && initialRetryIntervalSeconds > maximumRetryIntervalSeconds) { throw new IllegalStateException( "ExponentialRetryPolicy requires maximumRetryIntervalSeconds to have a value larger than initialRetryIntervalSeconds."); } if (retryExpirationIntervalSeconds > FlowConstants.NONE && initialRetryIntervalSeconds > retryExpirationIntervalSeconds) { throw new IllegalStateException( "ExponentialRetryPolicy requires retryExpirationIntervalSeconds to have a value larger than initialRetryIntervalSeconds."); } } }
3,519
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/interceptors/ExponentialRetryWithJitterPolicy.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.interceptors; import java.util.Random; import java.util.Date; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; /** * Retry policy that adds to the functionality of the ExponentialRetryPolicy by allowing a jitter value * to the nextRetryDelaySeconds output. The jitter is the value of baseDelay multiplied with a random * coefficient between 0 and maxJitterCoefficient. And the jitter could randomly be positive or negative: * <p> * -(baseDelay * maxJitterCoefficient) &lt;= jitter &lt; (baseDelay * maxJitterCoefficient) * </p> * Since maxJitterCoefficient is exclusively between 0 and 1, the absolute value of jitter is always * smaller than the baseDelay. * * @author congwan * */ public class ExponentialRetryWithJitterPolicy extends ExponentialRetryPolicy { private final Random jitterCoefficientGenerator; private final double maxJitterCoefficient; /** * Makes a new ExponentialRetryWithJitterPolicy object with the specified jitter conditions. * @param initialRetryIntervalSeconds the initial interval for retry delays in seconds. * @param jitterCoefficientGenerator a random number generator that generates the value for the jitter coefficient. * @param maxJitterCoefficient the maximum allowed jitter to be added to the output of the nextRetryDelaySeconds. */ public ExponentialRetryWithJitterPolicy(final long initialRetryIntervalSeconds, final Random jitterCoefficientGenerator, final double maxJitterCoefficient) { super(initialRetryIntervalSeconds); this.jitterCoefficientGenerator = jitterCoefficientGenerator; this.maxJitterCoefficient = maxJitterCoefficient; } @Override public long nextRetryDelaySeconds(final Date firstAttempt, final Date recordedFailure, final int numberOfTries) { final long baseDelay = super.nextRetryDelaySeconds(firstAttempt, recordedFailure, numberOfTries); long totalDelay; if (baseDelay == FlowConstants.NONE) { totalDelay = baseDelay; } else { long jitter = Math.round(baseDelay * maxJitterCoefficient * (2 * jitterCoefficientGenerator.nextDouble() - 1)); totalDelay = baseDelay + jitter; } return totalDelay; } @Override public void validate() throws IllegalStateException { super.validate(); if (jitterCoefficientGenerator == null) { throw new IllegalStateException("ExponentialRetryWithJitterPolicy requires jitterCoefficientGenerator not to be null."); } if (maxJitterCoefficient <= 0 || maxJitterCoefficient >= 1) { throw new IllegalStateException("ExponentialRetryWithJitterPolicy requires maxJitterCoefficient to be exclusively between 0 and 1."); } } }
3,520
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/AsyncContextAware.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; abstract class AsyncContextAware { abstract AsyncParentContext getContext(); }
3,521
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/Cancelable.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; public interface Cancelable { public void cancel(Throwable cause); public boolean isCancelRequested(); }
3,522
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/TaskContext.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.concurrent.Executor; class TaskContext extends AsyncContextBase implements AsyncParentContext { private final Task task; private boolean executionStartedOrCompleted; private final String parentTaskMethodName; private final boolean hideStartFromMethod; public TaskContext(Task task, Boolean daemon, Promise<?>[] waitFor) { super(daemon, waitFor, 7); this.task = task; this.parentTaskMethodName = null; this.hideStartFromMethod = false; } public TaskContext(AsyncParentContext parent, Task task, Boolean daemon, Promise<?>[] waitFor) { super(parent, daemon, waitFor, 5); this.task = task; this.parentTaskMethodName = null; this.hideStartFromMethod = false; } public TaskContext(AsyncParentContext parent, Task task, Boolean daemon, String parentTaskMethodName, boolean hideParentTaskMethodName, int skipStackLines, Promise<?>[] waitFor) { super(parent, daemon, waitFor, skipStackLines); this.task = task; this.parentTaskMethodName = parentTaskMethodName; this.hideStartFromMethod = hideParentTaskMethodName; } public TaskContext(Task task, Boolean daemon, String parentTaskMethodName, boolean hideParentTaskMethodName, int skipStackLines, Promise<?>[] waitFor) { super(daemon, waitFor, skipStackLines); this.task = task; this.parentTaskMethodName = parentTaskMethodName; this.hideStartFromMethod = hideParentTaskMethodName; } public void cancel(Throwable cause) { if (cancelRequested) { return; } cancelRequested = true; if (!executionStartedOrCompleted) { parent.remove(this); } } @Override public void run() { if (cancelRequested) { return; } setCurrent(this); Error error = null; try { executionStartedOrCompleted = true; task.doExecute(); parent.remove(this); } catch (Throwable e) { if (e instanceof Error) { error = (Error) e; } else { if (stackTrace != null && !parent.isRethrown(e)) { AsyncStackTrace merged = new AsyncStackTrace(stackTrace, e.getStackTrace(), 0); merged.setStartFrom(getParentTaskMethodName()); merged.setHideStartFromMethod(hideStartFromMethod); e.setStackTrace(merged.getStackTrace()); } parent.fail(this, e); } } finally { if (error != null) { throw error; } setCurrent(null); } } @Override public void add(AsyncContextBase async, Promise<?> waitFor) { parent.add(async, waitFor); } @Override public void remove(AsyncContextBase async) { parent.remove(async); } @Override public void fail(AsyncContextBase async, Throwable e) { parent.fail(async, e); } @Override public Executor getExecutor() { return parent.getExecutor(); } @Override public boolean isRethrown(Throwable e) { return parent.isRethrown(e); } @Override public AsyncParentContext getCurrentTryCatchFinallyContext() { return parent; } @Override public boolean getDaemonFlagForHeir() { return isDaemon(); } @Override public String getParentTaskMethodName() { return parentTaskMethodName == null ? "doExecute" : parentTaskMethodName; } @Override public boolean getHideStartFromMethod() { return hideStartFromMethod; } public String toString() { if (stackTrace != null) { return stackTrace.toString(); } return super.toString(); } }
3,523
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/AndPromise.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.Collection; /** * Promise that becomes ready when all its values are ready. <code>null</code> * value is considered ready. */ public class AndPromise extends Promise<Void> { private final class AndPromiseCallback implements Runnable { private int count; AndPromiseCallback(int count) { this.count = count; } @Override public void run() { if (--count == 0) { impl.set(null); } } } private static final Promise<?>[] EMPTY_VALUE_ARRAY = new Promise[0]; private final Settable<Void> impl = new Settable<Void>(); @SuppressWarnings("rawtypes") private final Promise[] values; public AndPromise(Promise<?>... values) { this.values = values; if (values == null || values.length == 0) { impl.set(null); } Runnable callback = new AndPromiseCallback(values.length); for (Promise<?> value : values) { if (value != null) { value.addCallback(callback); } else { callback.run(); } } } @SuppressWarnings({ "rawtypes" }) public AndPromise(Collection<Promise> collection) { this(collection.toArray(EMPTY_VALUE_ARRAY)); } @SuppressWarnings("rawtypes") public Promise[] getValues() { return values; } @Override protected void addCallback(Runnable callback) { impl.addCallback(callback); } @Override public Void get() { return impl.get(); } @Override public boolean isReady() { return impl.isReady(); } @Override protected void removeCallback(Runnable callback) { impl.removeCallback(callback); } }
3,524
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/ExternalTaskCancellationHandler.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; public interface ExternalTaskCancellationHandler { /** * Called when cancellation of the external task is requested. Use * {@link ExternalTaskCompletionHandle#complete()} to report task successful * completion or cancellation. Use * {@link ExternalTaskCompletionHandle#fail(Throwable)} to report task * completion or cancellation failure. * @param cause the reason for the cancellation. May be <code>null</code>. */ public void handleCancellation(Throwable cause); }
3,525
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/Promise.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; /** * Promise is a future like object that is used as a placeholder for a result of * an asynchronous API. Java Future is a synchronization construct that is used * to block a thread that called get() method if result is not available yet. * Promise differs from it as it cannot be used for blocking. A call to its * get() method throws IllegalStateException if result is not available yet. The * correct way to ensure that Promise is ready is to access it from a method * that is annotated as @Asynchronous and have the given Promise as one its * arguments or from {@link Task#doExecute()} method assuming that promise was * passed to the Task as a constructor parameter. * * <p> * Promise is not linked to error handling like Future is. In case of exceptions * they are propagated to the {@link TryCatchFinally#doCatch(Throwable)} method * of the {@link TryCatchFinally} that owns the asynchronous task that failed. * See {@link TryCatchFinally} for more info on the error handling. * * <p> * For promises that don't need a value and just used to ensure correct ordering * of asynchronous operations the common pattern to use {@link Void} as a * generic type. * <p> * * @param <V> * The result type returned by this Promise's get method. Use * {@link Void} to represent Promise that indicates completion of * operation that doesn't return a value. */ public abstract class Promise<V> { /** * @return result of your asynchronous computation * @throws IllegalStateException * if result of your asynchronous computation is not available * yet */ public abstract V get(); /** * @return <code>true</code> if the result of your asynchronous computation * is available */ public abstract boolean isReady(); /** * @return human friendly description on what this promise represents. * Emitted for example as part of * {@link AsyncScope#getAsynchronousThreadDumpAsString()} */ public String getDescription() { return null; } /** * Compliant implementation should notify callbacks after promise is set to * ready state. * * @param callback * callback to notify */ protected abstract void addCallback(Runnable callback); protected abstract void removeCallback(Runnable callback); /** * Convenience method for creating a Promise object which is in ready state * and returns the passed in value when get() is called. * <p> * The same as <code>new {@link Settable}&lt;T&gt;(value)</code> * * @param <T> * Type of value * @param value * Object to return when get() is called * @return An instance of Promise wrapper object */ public static <T> Promise<T> asPromise(T value) { return new Settable<T>(value); } /** * This is a factory method to create a Promise&lt;Void&gt; object in ready state. * * @return An instance of Promise object with no value. */ public static Promise<Void> Void() { return new Settable<Void>(null); } }
3,526
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/Promises.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Promises { private Promises() {} public static <T> Promise<List<T>> listOfPromisesToPromise(final List<Promise<T>> list) { final Settable<List<T>> result = new Settable<List<T>>(); @SuppressWarnings({ "rawtypes", "unchecked" }) AndPromise andPromise = new AndPromise((Collection)list); new Task(andPromise) { @Override protected void doExecute() throws Throwable { List<T> extracted = new ArrayList<T>(list.size()); for (Promise<T> promise : list) { extracted.add(promise.get()); } result.set(extracted); } }; return result; } public static <K, V> Promise<Map<K, V>> mapOfPromisesToPromise(final Map<K, Promise<V>> map) { final Settable<Map<K, V>> result = new Settable<Map<K, V>>(); @SuppressWarnings({ "rawtypes", "unchecked" }) AndPromise andPromise = new AndPromise((Collection) map.values()); new Task(andPromise) { @Override protected void doExecute() throws Throwable { Map<K, V> extracted = new HashMap<K, V>(map.size()); for (Entry<K, Promise<V>> pair : map.entrySet()) { extracted.put(pair.getKey(), pair.getValue().get()); } result.set(extracted); } }; return result; } public static <T> Promise<Set<T>> setOfPromisesToPromise(final Set<Promise<T>> set) { final Settable<Set<T>> result = new Settable<Set<T>>(); @SuppressWarnings({ "rawtypes", "unchecked" }) AndPromise andPromise = new AndPromise((Collection) set); new Task(andPromise) { @Override protected void doExecute() throws Throwable { Set<T> extracted = new HashSet<T>(set.size()); for (Promise<T> promise : set) { extracted.add(promise.get()); } result.set(extracted); } }; return result; } }
3,527
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/TryFinally.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; public abstract class TryFinally extends TryCatchFinally { public TryFinally(Promise<?>... waitFor) { // The reason this() is not called here is to pass correct value of the skipStackLines. // While this() passes the same value it also adds its own line into the stack trace. super(null, null, 7, waitFor); } public TryFinally(boolean daemon, Promise<?>... waitFor) { super(daemon, null, 7, waitFor); } public TryFinally(AsyncContextAware parent, boolean daemon, Promise<?>... waitFor) { super(parent, daemon, null, 7, waitFor); } public TryFinally(AsyncContextAware parent, Promise<?>... waitFor) { super(parent, null, null, 7, waitFor); } @Override protected void doCatch(Throwable e) throws Throwable { throw e; } }
3,528
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/OrPromise.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.Collection; /** * Promise that becomes ready when any of its values becomes ready. * <code>null</code> value is considered ready. */ public class OrPromise extends Promise<Void> { private final class OrPromiseCallback implements Runnable { @Override public void run() { if (!impl.isReady()) { impl.set(null); } } } private static final Promise<?>[] EMPTY_VALUE_ARRAY = new Promise[0]; private final Settable<Void> impl = new Settable<Void>(); private final Promise<?>[] values; public OrPromise(Promise<?>... values) { this.values = values; if (values == null || values.length == 0) { impl.set(null); } Runnable callback = new OrPromiseCallback(); for (Promise<?> value : values) { if (value != null) { value.addCallback(callback); } else { callback.run(); } } } @SuppressWarnings({ "rawtypes" }) public OrPromise(Collection<Promise> collection) { this(collection.toArray(EMPTY_VALUE_ARRAY)); } public Promise<?>[] getValues() { return values; } @Override protected void addCallback(Runnable callback) { impl.addCallback(callback); } @Override public Void get() { return impl.get(); } @Override public boolean isReady() { return impl.isReady(); } @Override protected void removeCallback(Runnable callback) { impl.removeCallback(callback); } }
3,529
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/ExternalTaskCompletionHandle.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; /** * Used to complete or fail an external task initiated through * {@link ExternalTask#doExecute(ExternalTaskCompletionHandle)}. * <p> * Flow framework is not thread safe and expects that all asynchronous code is * executed in a single thread. Currently ExternalTaskCompletionHandle is the * only exception as it allows {@link #complete()} and {@link #fail(Throwable)} * be called from other threads. * * @author fateev */ public interface ExternalTaskCompletionHandle { public void complete(); public void fail(Throwable e); }
3,530
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/ExternalTaskContext.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.concurrent.Executor; class ExternalTaskContext extends AsyncContextBase { private final class ExternalTaskCompletionHandleImpl implements ExternalTaskCompletionHandle { private String methodName; private boolean completed; private Throwable failure; private void setDoExecuteFailed(String methodName, Throwable e) { this.failure = e; this.methodName = methodName; } @Override public void complete() { if (failure != null) { throw new IllegalStateException("Invalid ExternalTaskCompletionHandle as " + methodName + " failed with an exception.", failure); } if (completed) { throw new IllegalStateException("Already completed"); } completed = true; if (!inCancellationHandler) { removeFromParent(); } } @Override public void fail(final Throwable e) { if (e instanceof Error) { throw (Error) e; } if (failure != null) { throw new IllegalStateException("Invalid ExternalTaskCompletionHandle as " + methodName + " failed with exception.", failure); } if (completed) { throw new IllegalStateException("Already completed"); } if (stackTrace != null && !parent.isRethrown(e)) { AsyncStackTrace merged = new AsyncStackTrace(stackTrace, e.getStackTrace(), 0); merged.setStartFrom(getParentTaskMethodName()); e.setStackTrace(merged.getStackTrace()); } failure = e; if (!inCancellationHandler) { failToParent(e); } } public boolean isCompleted() { return completed; } public Throwable getFailure() { return failure; } } private final ExternalTask task; private ExternalTaskCancellationHandler cancellationHandler; /** * Used to deal with situation when task is completed while in cancellation * handler and then exception is thrown from it. */ private boolean inCancellationHandler; private ExternalTaskCompletionHandleImpl completionHandle = new ExternalTaskCompletionHandleImpl(); private String description; public ExternalTaskContext(ExternalTask task, Boolean daemon, Promise<?>[] waitFor) { super(daemon, waitFor, 6); this.task = task; } public ExternalTaskContext(AsyncParentContext parent, ExternalTask task, Boolean daemon, Promise<?>[] waitFor) { super(parent, daemon, waitFor, 6); this.task = task; } public void cancel(final Throwable cause) { if (completionHandle.failure != null || completionHandle.completed) { return; } if (cancelRequested) { return; } cancelRequested = true; if (cancellationHandler != null) { parent.getExecutor().execute(new Runnable() { @Override public void run() { Error error = null; try { inCancellationHandler = true; cancellationHandler.handleCancellation(cause); } catch (Throwable e) { if (e instanceof Error) { error = (Error) e; } else { if (stackTrace != null && !parent.isRethrown(e)) { AsyncStackTrace merged = new AsyncStackTrace(stackTrace, e.getStackTrace(), 0); merged.setStartFrom(getParentTaskMethodName()); e.setStackTrace(merged.getStackTrace()); } completionHandle.setDoExecuteFailed("ExternalTaskCancellationHandler.handleCancellation", e); } } finally { if (error != null) { throw error; } inCancellationHandler = false; if (completionHandle.getFailure() != null) { failToParent(completionHandle.getFailure()); } else if (completionHandle.isCompleted()) { removeFromParent(); } } } }); } else { removeFromParent(); } } @Override public void run() { if (cancelRequested) { return; } setCurrent(parent); try { cancellationHandler = task.doExecute(completionHandle); } catch (Throwable e) { completionHandle.setDoExecuteFailed("ExternalTask.doExecute", e); if (stackTrace != null && !parent.isRethrown(e)) { AsyncStackTrace merged = new AsyncStackTrace(stackTrace, e.getStackTrace(), 0); merged.setStartFrom(getParentTaskMethodName()); e.setStackTrace(merged.getStackTrace()); } parent.fail(this, e); } finally { setCurrent(null); } } @Override public void add(AsyncContextBase async, Promise<?> waitFor) { parent.add(async, waitFor); } @Override public void remove(AsyncContextBase async) { parent.remove(async); } @Override public void fail(AsyncContextBase async, Throwable e) { parent.fail(async, e); } @Override public Executor getExecutor() { return parent.getExecutor(); } @Override public boolean isRethrown(Throwable e) { return parent.isRethrown(e); } @Override public AsyncParentContext getCurrentTryCatchFinallyContext() { return parent; } @Override public boolean getDaemonFlagForHeir() { return isDaemon(); } @Override public String getParentTaskMethodName() { if (cancelRequested) { return "handleCancellation"; } return "doExecute"; } private void removeFromParent() { parent.getExecutor().execute(new Runnable() { @Override public void run() { parent.remove(ExternalTaskContext.this); } }); } private void failToParent(final Throwable e) { parent.getExecutor().execute(new Runnable() { @Override public void run() { parent.fail(ExternalTaskContext.this, e); } }); } public void setDescription(String description) { this.description = description; } public String getDescription() { return description; } public String toString() { if (stackTrace != null) { return stackTrace.toString(); } return super.toString(); } }
3,531
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/TryCatchFinally.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.Future; import com.amazonaws.services.simpleworkflow.flow.annotations.Asynchronous; /** * Asynchronous equivalent of synchronous try-catch-finally. <h3>Overview</h3> * <p> * SWF Flow error handling relies on the idea that any asynchronous task (which * includes methods annotated as {@link Asynchronous}) is executed in a parent * context. In the case of an exception being thrown from a task, all sibling * tasks that share the same parent context are canceled. After successful * cancellation the exception is propagated to the parent context for handling. * </p> * <p> * <code>TryCatchFinally</code> {@link #doTry()}, {@link #doFinally()} and * {@link #doCatch(Throwable)} methods serve as parent scopes for tasks created * during their execution. * </p> * <p> * For example if any {@link Task} (or method annotated with * {@link Asynchronous}) that originates (possibly indirectly through parent * task) in {@link #doTry()} throws an exception all other tasks that originated * in {@link #doTry()} are canceled and only then {@link #doCatch(Throwable)} is * called. Through this cancellation mechanism it is guaranteed that * {@link #doCatch(Throwable)} is called at most once even if there are multiple * parallel tasks executing in the {@link #doTry()} scope. * </p> * <p> * If failure happens in a task originated in {@link #doCatch(Throwable)} then * all its siblings are canceled first and then {@link #doFinally()} is called. * </p> * <p> * The same happens if task originated in {@link #doFinally()} fails. All it * siblings are canceled and then parent scope of the * <code>TryCatchFinally</code> is given chance to handle the exception. * </p> * <h3>Cancellation</h3> * <p> * The cancellation semantic depends on the task implementation. {@link Task} * (or method annotated with {@link Asynchronous}) that has not started * execution is never given chance to execute after cancellation. Task which is * already executing is not interrupted and completes (or fails). * {@link ExternalTask} cancellation depends on the external resource. For * example SWF activities and child workflows that are modeled as * {@link ExternalTask}s are canceled through SWF API. * </p> * <p> * When <code>TryCatchFinally</code> itself is canceled because of sibling task * failure it handles its own cancellation in the following order: * </p> * <ol> * <li>If doTry hasn't started yet then <code>TryCatchFinally</code> is * considered canceled immediately.</li> * <li>If are any outstanding task that originated in {@link #doTry()} then * cancellation of all of them is requested.</li> * <li>After all tasks originated in doTry are canceled call * {@link #doCatch(Throwable)} with {@link CancellationException}.</li> * <li>After all tasks originated in doCatch are completed call * {@link #doFinally()}.</li> * <li>After all tasks originated in {@link #doFinally()} are completed consider * TryCathFinally canceled</li> * </ol> * <p> * {@link #doCatch(Throwable)} and {@link #doFinally()} * <em>are not cancelable</em>. It means that cancellation request always waits * for completion of all tasks that originate in these methods. Special care * should be taken when writing code in {@link #doCatch(Throwable)} and in * {@link #doFinally()} to ensure that in all possible failure scenarios they * don't end up in a stuck state. * </p> * <p> * <code>TryCatchFinally</code> can be canceled explicitly through * {@link #cancel(Throwable)} method. In case of explicit cancellation any * exception including {@link CancellationException} that is rethrown from * {@link #doCatch(Throwable)} or {@link #doFinally()} is propagated to the * parent context. * </p> * <h3>Daemon Tasks</h3> * <p> * It is pretty common to have tasks that have their lifecycle linked to some * other tasks. For example notification activity that is sent out if some other * activity is not completed in a specified period of time. The timer and the * notification activity should be canceled as soon as the monitored activity is * completed. Such use case can be supported by wrapping timer and notification * activity in <code>TryCatchFinally</code> which is explicitly canceled upon * monitored activity completion. The more convenient way to perform such * cleanup is by marking a Task (or method annotated with {@link Asynchronous}) * as daemon. The asynchronous scope in absence of failures is executed in the * following sequence: * <ol> * <li>The scope method (for example {@link #doTry()}) is executed.</li> * <li>All tasks that are created during its execution are executed (when * Promises they are waiting on become ready) possibly creating more tasks.</li> * <li>When all <em>non daemon</em> tasks originated in the scope method are * completed cancellation requests are sent to all <em>daemon</em> siblings.</li> * <li>The scope is completed after all daemon tasks are canceled. * </ol> * <p> * Pass <code>true</code> to the first argument of * {@link Task#Task(boolean, Promise...)} constructor to mark a Task as daemon. * Use {@link Asynchronous#daemon()} annotation parameter to mark an * asynchronous method as daemon. Any task that is created during execution of a * daemon task is marked as daemon. <code>TryCatchFinally</code> also can be * marked as daemon through {@link #TryCatchFinally(boolean, Promise...)} * constructor or by by being created by a daemon task. Note that * TryCatchFinally doesn't pass its daemon flag to tasks created in * {@link #doTry()}, {@link #doCatch(Throwable)} and {@link #doFinally()}. It is * because each of these methods acts as a separate asynchronous scope and the * rules of execution described above apply to them. * </p> * <h3>Miscellaneous</h3> * <p> * In case of multiple simultaneous exceptions (which is possible for external * tasks) or if cancellation of a child results in any exception that is not * {@link CancellationException} the last exception "wins". I.e. it becomes the * exception delivered to {@link #doCatch(Throwable)} method. * </p> * <p> * Note that instances of {@link Promise} do not participate in error handling * the way {@link Future} does. If method that returns Promise throws an * exception the Promise state and return value are not changed. It is similar * to behavior of variables in case of synchronous code. * </p> * <h3>Usage Examples</h3> * <p> * Basic error handling: * </p> * * <pre> * new TryCatchFinally() { * * final List&lt;Promise&lt;String&gt;&gt; instances = new ArrayList&lt;Promise&lt;String&gt;&gt;(); * * protected void doTry() throws Throwable { * for (int i = 0; i &lt; count; i++) { * Promise&lt;String&gt; instanceId = ec2.startInstance(); * instances.add(instanceId); * } * performSimulation(instances); * } * * protected void doCatch(Throwable e) throws Throwable { * mail.notifySimulationFailure(e); * } * * protected void doFinally() throws Throwable { * for (int i = 0; i &lt; count; i++) { * Promise&lt;String&gt; instanceId = instances.get(i); * if (instanceId.isReady()) { * ec2.stopInstance(instanceId.get()); * } * } * } * }; * </pre> * <p> * Daemon example: * </p> * * <pre> * * * protected void doTry() throws Throwable { * for (int i = 0; i &lt; count; i++) { * Promise&lt;String&gt; instanceId = ec2.startInstance(); * instances.add(instanceId); * } * performSimulation(instances); * notifyOnDelay(); * } * * &#064;Asynchronous(daemon = true) * public void notifyOnDelay() { * Promise&lt;Void&gt; timer = clock.scheduleTimer(3600); * mail.notifyDelay(timer); * } * </pre> * * @author fateev */ public abstract class TryCatchFinally extends AsyncContextAware implements Cancelable { public enum State { CREATED, TRYING, CATCHING, FINALIZING, CLOSED } private final TryCatchFinallyContext context; public TryCatchFinally() { this(null, null, 7, null); } public TryCatchFinally(Promise<?>... waitFor) { this(null, null, 7, waitFor); } public TryCatchFinally(boolean daemon, Promise<?>... waitFor) { this(daemon, null, 7, waitFor); } public TryCatchFinally(AsyncContextAware parent, boolean daemon, Promise<?>... waitFor) { context = new TryCatchFinallyContext(parent.getContext(), this, daemon, null, 5, waitFor); } public TryCatchFinally(AsyncContextAware parent, Promise<?>... waitFor) { context = new TryCatchFinallyContext(parent.getContext(), this, null, null, 5, waitFor); } protected TryCatchFinally(Boolean daemon, String parentTaskMethodName, int skipStackLines, Promise<?>[] waitFor) { context = new TryCatchFinallyContext(this, daemon, parentTaskMethodName, skipStackLines, waitFor); } protected TryCatchFinally(AsyncContextAware parent, Boolean daemon, String parentTaskMethodName, int skipStackLines, Promise<?>[] waitFor) { context = new TryCatchFinallyContext(parent.getContext(), this, daemon, parentTaskMethodName, skipStackLines, waitFor); } public String getName() { return context.getName(); } public void setName(String name) { context.setName(name); } @Override AsyncParentContext getContext() { return context; } public void cancel(Throwable cause) { context.cancel(cause); } public boolean isCancelRequested() { return context.isCancelRequested(); } public StackTraceElement[] getStackTrace() { return context.getStackTrace().getStackTrace(); } public List<AsyncTaskInfo> getAsynchronousStackTraceDump() { List<AsyncTaskInfo> result = new ArrayList<AsyncTaskInfo>(); context.getAsynchronousStackTraceDump(result); return result; } public String getAsynchronousStackTraceDumpAsString() { return context.getAsynchronousStackTraceDumpAsString(); } public State getState() { return context.getState(); } @Override public String toString() { return context.toString(); } protected void rethrow(final Throwable e, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { throw e; } }; } protected abstract void doTry() throws Throwable; protected abstract void doCatch(Throwable e) throws Throwable; protected abstract void doFinally() throws Throwable; }
3,532
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/Settable.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.ArrayList; import java.util.List; /** * It is an implementation of Promise, which exposes an additional * {@link #set(Object)} and {@link #chain(Promise)} methods. Calling * {@link #set(Object)} puts it in ready state, with value retrievable through * {@link #get()} method. {@link #chain(Promise)} links state of this Settable * to another Promise. When another promise changes its state to ready the * chained one is also becomes ready. * * <p> * Use <code>settable.set(null)</code> to set <code>Settable&lt;Void&gt;</code> * to the ready state. * * <p> * Settable is frequently used to return data from code contained in anonymous * classes. For example: * * <pre> * <code> * Promise&lt;Integer&gt; foo() { * final Settable&lt;Integer&gt; result = new Settable&lt;Integer&gt;(); * new TryCatch() { * * protected void doTry() throws Throwable { * Promise&lt;Integer&gt; activity1Result = activities.callActivity1(); * result.chain(activity1Result); * } * * protected void doCatch(Throwable e) throws Throwable { * Promise&lt;Void&gt; handled = handleFailure(e); * rethrow(e, handled); * } * }; * return result; * } * </code> * </pre> * * @param <V> * The type of value accepted and returned by this Settable.Use * {@link Void} to represent Promise that indicates completion of * operation that doesn't return a value. */ public class Settable<V> extends Promise<V> { private final List<Runnable> callbacks = new ArrayList<Runnable>(); private Runnable chainCallback; private Promise<V> chainedTo; private V value; private boolean ready; private String description; public Settable(V value) { set(value); } public Settable() { } /** * @return The value passed in when set() is called * @throws IllegalStateException * If set() is never called for this instance of Settable */ @Override public V get() { if (!ready) { throw new IllegalStateException("not ready"); } return value; } /** * @return <code>true</code> if set() is called for this Settable */ @Override public boolean isReady() { return ready; } /** * * @param value * Object to return when get() is called for this Settable. Use * <code>null</code> to set <code>Settable&lt;Void&gt;</code> to * the ready state. * @throws IllegalStateException * if the Promise is already in ready state */ public void set(V value) { if (ready) { throw new IllegalStateException("already set to " + this.value); } this.value = value; this.ready = true; for (Runnable callback : callbacks) { callback.run(); } } /** * Used to chain this Settable with the passed in Promise. This allows the * Settable to be ready whenever the passed in Promise is ready and the * value for the chained Promise can be retrieved by calling get() method on * this Settable. * * @see #unchain() * @param chainTo * Promise object to chain this Settable to. Chaining to * <code>null</code> equates calling {@link #set(Object)} with * <code>null</code> argument. * @throws IllegalStateException * if Settable is already in ready state or it is already * chained to some other Promise */ public void chain(final Promise<V> chainTo) { if (ready) { throw new IllegalStateException("already ready"); } if (chainCallback != null) { throw new IllegalStateException("Already chained. Call unchain() to get rid of the previous chaining."); } if (chainTo == null) { set(null); return; } chainCallback = new Runnable() { @Override public void run() { set(chainTo.get()); } }; chainTo.addCallback(chainCallback); chainedTo = chainTo; } /** * Used to unchain this Settable from the Promise object passed in last * invocation of chain. There is no requirement to unchain unless there is a * need to chain the Settable to another Promise. Such need usually appears * when implementing recursive functions or in * {@link TryCatchFinally#doCatch(Throwable)} blocks. It is safe to call * unchain if chain is never called for this Settable. * * @throws IllegalStateException * If the Promise it is chained to is already in the ready state */ public void unchain() { if (chainedTo == null) { return; } if (chainedTo.isReady()) { throw new IllegalStateException("Cannot unchain from a value which is ready"); } if (chainCallback != null) { chainedTo.removeCallback(chainCallback); chainCallback = null; chainedTo = null; } } protected void addCallback(Runnable callback) { if (ready) { callback.run(); } else { callbacks.add(callback); } } @Override protected void removeCallback(Runnable callback) { callbacks.remove(callback); } @Override public String getDescription() { if (description == null && chainedTo != null) { return chainedTo.getDescription(); } return description; } /** * @param description * human readable description of what this Promise represents. * @see Promise#getDescription() */ public void setDescription(String description) { this.description = description; } @Override public String toString() { return "Settable [value=" + value + ", ready=" + ready + "]"; } }
3,533
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/AsyncContextBase.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.ArrayList; import java.util.List; abstract class AsyncContextBase implements Runnable, AsyncParentContext { private final static ThreadLocal<AsyncParentContext> currentContext = new ThreadLocal<AsyncParentContext>(); static AsyncParentContext current() { AsyncParentContext result = currentContext.get(); if (result == null) { throw new IllegalStateException("Attempt to execute asynchronous code outside of AsyncScope.doAsync() method"); } return result; } static void setCurrent(AsyncParentContext newCurrent) { currentContext.set(newCurrent); } private final boolean daemon; protected final AsyncParentContext parent; protected AsyncStackTrace stackTrace; private final Promise<?>[] waitFor; private String name; protected boolean cancelRequested; public AsyncContextBase(Boolean daemon, Promise<?>[] waitFor, int skipStackLines) { this(current(), daemon, waitFor, skipStackLines); } public AsyncContextBase(AsyncParentContext parent, Boolean daemon, Promise<?>[] waitFor, int skipStackLines) { this.parent = parent; this.daemon = daemon == null ? parent.getDaemonFlagForHeir() : daemon; this.waitFor = waitFor; this.name = parent == null ? null : parent.getName(); AsyncStackTrace parentStack = parent.getStackTrace(); if (parentStack != null) { StackTraceElement[] stacktrace = System.getProperty("com.amazonaws.simpleworkflow.disableAsyncStackTrace", "false").equalsIgnoreCase("true") ? new StackTraceElement[0] : Thread.currentThread().getStackTrace(); stackTrace = new AsyncStackTrace(parentStack, stacktrace, skipStackLines); stackTrace.setStartFrom(parent.getParentTaskMethodName()); stackTrace.setHideStartFromMethod(parent.getHideStartFromMethod()); } this.cancelRequested = parent.isCancelRequested(); if (!this.cancelRequested) { this.parent.add(this, waitFor == null || waitFor.length == 0 ? null : new AndPromise(waitFor)); } } public boolean isDaemon() { return daemon; } @Override public boolean isCancelRequested() { return cancelRequested; } public AsyncStackTrace getStackTrace() { return stackTrace; } public AsyncTaskInfo getTaskInfo() { return new AsyncTaskInfo(name, stackTrace == null ? null : stackTrace.getStackTrace(), daemon, waitFor); } public String getName() { return name; } public void setName(String name) { this.name = name; } /** * @param cause * the cancellation cause. Can be <code>null</code> */ public abstract void cancel(Throwable cause); public String getAsynchronousStackTraceDumpAsString() { List<AsyncTaskInfo> infos = new ArrayList<AsyncTaskInfo>(); getAsynchronousStackTraceDump(infos); StringBuffer sb = new StringBuffer(); for (int j = 0; j < infos.size(); j++) { AsyncTaskInfo info = infos.get(j); if (j > 0) { sb.append("-----------------------------------------------------\n"); } sb.append(info); } return sb.toString(); } @Override public boolean getHideStartFromMethod() { return false; } protected void getAsynchronousStackTraceDump(List<AsyncTaskInfo> result) { result.add(getTaskInfo()); } }
3,534
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/TryCatchFinallyContext.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.Executor; import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally.State; class TryCatchFinallyContext extends AsyncContextBase { private List<AsyncContextBase> heirs = new ArrayList<AsyncContextBase>(); private int nonDaemonHeirsCount; private Executor executor; private State state = State.CREATED; private Throwable failure; private boolean executed; private boolean daemondCausedCancellation; private final TryCatchFinally tryCatchFinally; private final String parentTaskMethodName; TryCatchFinallyContext(TryCatchFinally tryCatchFinally, Boolean daemon, String parentTaskMethodName, int skipStackLines, Promise<?>[] waitFor) { super(daemon, waitFor, skipStackLines); this.tryCatchFinally = tryCatchFinally; this.executor = parent.getExecutor(); this.parentTaskMethodName = parentTaskMethodName; } TryCatchFinallyContext(AsyncParentContext parent, TryCatchFinally tryCatchFinally, Boolean daemon, String parentTaskMethodName, int skipStackLines, Promise<?>[] waitFor) { super(parent, daemon, waitFor, skipStackLines); this.tryCatchFinally = tryCatchFinally; this.executor = parent.getExecutor(); this.parentTaskMethodName = parentTaskMethodName; } public Executor getExecutor() { return executor; } @Override public void add(final AsyncContextBase async, Promise<?> waitFor) { assert !cancelRequested; checkClosed(); heirs.add(async); if (!async.isDaemon()) { nonDaemonHeirsCount++; } if (waitFor == null) { executor.execute(async); } else { waitFor.addCallback(new Runnable() { @Override public void run() { executor.execute(async); } }); } } private void checkClosed() { if (state == State.CLOSED) { throw new IllegalStateException(state.toString()); } } public void cancel(Throwable cause) { if (cause instanceof Error) { throw (Error) cause; } if (cancelRequested) { return; } if (state == State.CREATED) { assert heirs.size() == 0; state = State.CLOSED; parent.remove(this); return; } if (failure == null && state == State.TRYING) { cancelRequested = true; failure = new CancellationException(); if (stackTrace != null) { failure.setStackTrace(stackTrace.getStackTrace()); } failure.initCause(cause); cancelHeirs(); } } public void remove(AsyncContextBase async) { checkClosed(); boolean removed = heirs.remove(async); assert removed; if (!async.isDaemon()) { nonDaemonHeirsCount--; assert nonDaemonHeirsCount >= 0; } updateState(); } public void fail(AsyncContextBase async, Throwable e) { checkClosed(); boolean cancellationException = e instanceof CancellationException; // Explicit cancellation through cancel() call leads to CancellationException being // thrown from the cancelled component. At the same time cancellation caused by the // daemon flag is ignored. if (!cancellationException || (failure == null && !daemondCausedCancellation)) { failure = e; } boolean removed = heirs.remove(async); assert removed; if (!async.isDaemon()) { nonDaemonHeirsCount--; assert nonDaemonHeirsCount >= 0; } cancelHeirs(); updateState(); } @Override public void run() { if (state == State.CLOSED) { return; } if (state == State.CREATED) { state = State.TRYING; } setCurrent(this); Throwable f = failure; Error error = null; try { switch (state) { case TRYING: if (cancelRequested) { return; } tryCatchFinally.doTry(); break; case CATCHING: failure = null; // Need to reset cancelRequested to allow addition of new child tasks cancelRequested = false; tryCatchFinally.doCatch(f); break; case FINALIZING: // Need to reset cancelRequested to allow addition of new child tasks cancelRequested = false; tryCatchFinally.doFinally(); } } catch (Throwable e) { if (e instanceof Error) { error = (Error) e; } else { if (stackTrace != null && e != f) { AsyncStackTrace merged = new AsyncStackTrace(stackTrace, e.getStackTrace(), 0); merged.setStartFrom(getParentTaskMethodName()); e.setStackTrace(merged.getStackTrace()); } failure = e; cancelHeirs(); } } finally { if (error != null) { throw error; } setCurrent(null); executed = true; updateState(); } } private void cancelHeirs() { List<AsyncContextBase> toCancel = new ArrayList<AsyncContextBase>(heirs); for (AsyncContextBase heir : toCancel) { heir.cancel(failure); } } private void updateState() { if (state == State.CLOSED || !executed) { return; } if (nonDaemonHeirsCount == 0) { if (heirs.isEmpty()) { if (state == State.TRYING) { if (failure == null) { state = State.FINALIZING; execute(); } else { state = State.CATCHING; execute(); } } else if (state == State.CATCHING) { state = State.FINALIZING; execute(); } else if (state == State.FINALIZING) { assert state != State.CLOSED; state = State.CLOSED; if (failure == null) { parent.remove(this); } else { parent.fail(this, failure); } } else { throw new IllegalStateException("Unknown state " + state); } } else { if (failure == null) { daemondCausedCancellation = true; } cancelHeirs(); } } } private void execute() { executed = false; executor.execute(this); } @Override protected void getAsynchronousStackTraceDump(List<AsyncTaskInfo> result) { if (heirs.size() == 0) { result.add(getTaskInfo()); } else { for (AsyncContextBase heir : heirs) { heir.getAsynchronousStackTraceDump(result); } } } public boolean isRethrown(Throwable e) { return e == failure; } @Override public AsyncParentContext getCurrentTryCatchFinallyContext() { return this; } /** * Heirs of the TryCatchFinally do not inherit daemon flag. */ @Override public boolean getDaemonFlagForHeir() { return false; } @Override public String getParentTaskMethodName() { if (parentTaskMethodName != null) { return parentTaskMethodName; } if (state == State.TRYING) { return "doTry"; } if (state == State.CATCHING) { return "doCatch"; } if (state == State.FINALIZING) { return "doFinally"; } return null; } public State getState() { return state; } @Override public String toString() { if (stackTrace != null) { return stackTrace.toString(); } return super.toString(); } }
3,535
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/AsyncParentContext.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.concurrent.Executor; interface AsyncParentContext { void add(AsyncContextBase async, Promise<?> waitFor); void remove(AsyncContextBase async); void fail(AsyncContextBase async, Throwable e); /** * Only Task passes daemon flag to its heirs. Daemon TryCatchFinally doesn't * pass it to heirs as cancellation of the daemon TryCatchFinally causes * heirs cancellation independently of their daemon status. */ boolean getDaemonFlagForHeir(); Executor getExecutor(); AsyncStackTrace getStackTrace(); String getParentTaskMethodName(); boolean isRethrown(Throwable e); AsyncParentContext getCurrentTryCatchFinallyContext(); boolean getHideStartFromMethod(); String getName(); boolean isCancelRequested(); }
3,536
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/Task.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; /** * Asynchronous task that is executed when all {@link Promise}s passed to its * constructor are ready (<code>null</code> parameter is considered ready). * * <p> * Should be created in the context of {@link AsyncScope#doAsync()} method, from * {@link Task#doExecute()} or from {@link TryCatchFinally} do... methods. * Exceptions thrown from {@link #doExecute()} are delivered asynchronously to * the wrapping {@link TryCatchFinally#doCatch(Throwable)} method or rethrown * from {@link AsyncScope#eventLoop()} if no wrapping {@link TryCatchFinally} is * found. * * <p> * Example of using {@link Task} to implement asynchronous function that sums * parameters when both of them are ready: * * <pre> * <tt> * public Promise&lt;Integer&gt; sum(Promise&lt;Integer&gt; a, Promise&lt;Integer&gt; b) { * Settable&lt;Integer&gt; result = new Settable&lt;Integer&gt;(); * new Task(a, b) { * public void doExecute() { * result.set(a.get() + b.get()); * } * }; * return result; * } * </tt> * </pre> * * @see AsyncScope * @see TryCatchFinally * @see Promise */ public abstract class Task extends AsyncContextAware { private TaskContext context; public Task(Promise<?>... waitFor) { this((Boolean) null, waitFor); } public Task(boolean daemon, Promise<?>... waitFor) { context = new TaskContext(this, daemon, waitFor); } private Task(Boolean daemon, Promise<?>... waitFor) { context = new TaskContext(this, daemon, waitFor); } public Task(AsyncContextAware parent, boolean daemon, Promise<?>... waitFor) { context = new TaskContext(parent.getContext(), this, daemon, waitFor); } public Task(AsyncContextAware parent, Promise<?>... waitFor) { context = new TaskContext(parent.getContext(), this, null, waitFor); } protected Task(AsyncContextAware parent, Boolean daemon, String parentTaskMethodName, boolean hideParentTaskMethodName, int skipStackLines, Promise<?>... waitFor) { context = new TaskContext(parent.getContext(), this, daemon, parentTaskMethodName, hideParentTaskMethodName, skipStackLines, waitFor); } protected Task(Boolean daemon, String parentTaskMethodName, boolean hideParentTaskMethodName, int skipStackLines, Promise<?>... waitFor) { context = new TaskContext(this, daemon, parentTaskMethodName, hideParentTaskMethodName, skipStackLines, waitFor); } public String getName() { return context.getName(); } public void setName(String name) { context.setName(name); } public StackTraceElement[] getStackTrace() { return context.getStackTrace().getStackTrace(); } @Override AsyncParentContext getContext() { return context; } public String toString() { return context.toString(); } protected abstract void doExecute() throws Throwable; }
3,537
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/AsyncTaskInfo.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public final class AsyncTaskInfo { private final StackTraceElement[] asyncStackTrace; private final boolean daemon; private final Promise<?>[] waitingFor; private final String name; public AsyncTaskInfo(String name, StackTraceElement[] asyncStackTrace, boolean daemon, Promise<?>[] waitFor) { this.name = name; this.asyncStackTrace = asyncStackTrace; this.daemon = daemon; this.waitingFor = waitFor; } public String getName() { return name; } public StackTraceElement[] getAsyncStackTrace() { return asyncStackTrace; } public boolean isDaemon() { return daemon; } public Promise<?>[] getWaitingFor() { return waitingFor; } @Override public String toString() { StringBuilder result = new StringBuilder(); if (name != null) { result.append("\""); result.append(name); result.append("\""); } if (daemon) { if (result.length() > 0) { result.append(" "); } result.append("daemon"); } if (waitingFor != null) { Map<Integer, String> waitingOnArguments = new HashMap<Integer, String>(); for (int i = 0; i < waitingFor.length; i++) { Promise<?> promise = waitingFor[i]; if (promise != null && !promise.isReady()) { if (promise instanceof AndPromise) { AndPromise andPromise = (AndPromise) promise; Promise<?>[] elements = andPromise.getValues(); StringBuilder description = new StringBuilder(); description.append("PromiseCollection["); boolean first = true; for (int j = 0; j < elements.length; j++) { Promise<?> e = elements[j]; if (e == null) { continue; } if (first) { first = false; } else { description.append(" "); } description.append(j); String d = e.getDescription(); if (d != null) { description.append(":\""); description.append(d); description.append("\""); } } description.append("]"); waitingOnArguments.put(i + 1, description.toString()); } else { String quotedDescription = promise.getDescription() == null ? null : "\"" + promise.getDescription() + "\""; waitingOnArguments.put(i + 1, quotedDescription); } } } if (waitingOnArguments.size() > 0) { if (result.length() > 0) { result.append(" "); } result.append("waiting on argument"); if (waitingOnArguments.size() > 1) { result.append("s"); } result.append(" (starting from 1)"); for (Entry<Integer, String> pair : waitingOnArguments.entrySet()) { result.append(" "); result.append(pair.getKey()); String description = pair.getValue(); if (description != null) { result.append(":"); result.append(description); } } } } if (result.length() > 0) { result.append("\n"); } if (asyncStackTrace != null) { for (int i = 0; i < asyncStackTrace.length; i++) { result.append("\tat "); result.append(asyncStackTrace[i]); result.append("\n"); } } else { result.append("Async Trace is Disabled."); } return result.toString(); } }
3,538
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/AsyncScope.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.List; /** * Interface between synchronous and asynchronous code. Serves as a root scope * for asynchronous computation and as event loop for the owning synchronous * code. * * @author fateev */ public abstract class AsyncScope extends AsyncContextAware implements Cancelable { private final AsyncScopeContext context; public AsyncScope() { // The reason this(...) is not called is to keep the same stack depth for both constructors. // It simplifies creation of async stack traces this.context = new AsyncScopeContext(this, false, false); } public AsyncScope(boolean disableAsyncStackTrace, boolean excludeAsyncScopeStack) { this.context = new AsyncScopeContext(this, disableAsyncStackTrace, excludeAsyncScopeStack); } public void cancel(Throwable cause) { context.cancel(cause); } @Override public boolean isCancelRequested() { return context.isCancelRequested(); } public List<AsyncTaskInfo> getAsynchronousThreadDump() { return context.getAsynchronousStackTraceDump(); } public String getAsynchronousThreadDumpAsString() { return context.getAsynchronousStackTraceDumpAsString(); } /** * Execute all queued tasks. If execution of those tasks result in addition * of new tasks to the queue execute them as well. * <p> * Unless there are external dependencies or bugs single call to this method * performs the complete asynchronous execution. * <p> * In presence of external dependencies it is expected that * <code>eventLoop()</code> is called every time after change in their state * can unblock the asynchronous execution. * * @return true means there are no tasks originated from this scope that are * not done yet. */ public boolean eventLoop() throws Throwable { return context.eventLoop(); } public boolean isComplete() { return context.isComplete(); } public Throwable getFailure() { return context.getFailure(); } @Override AsyncParentContext getContext() { return context.getRootContext(); } protected abstract void doAsync() throws Throwable; }
3,539
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/Functor.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; public abstract class Functor<T> extends Promise<T> { private final Settable<T> result = new Settable<T>(); public Functor(Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { result.chain(Functor.this.doExecute()); } }; } protected abstract Promise<T> doExecute() throws Throwable; @Override public T get() { return result.get(); } @Override public boolean isReady() { return result.isReady(); } @Override protected void addCallback(Runnable callback) { result.addCallback(callback); } @Override protected void removeCallback(Runnable callback) { result.removeCallback(callback); } }
3,540
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/AsyncScopeContext.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.List; import java.util.concurrent.Executor; class AsyncScopeContext { private final class RootTryCatchFinally extends TryCatchFinally { private RootTryCatchFinally(boolean daemon, int skipStackLines) { super(daemon, "doAsync", skipStackLines, new Promise<?>[0]); } @Override protected void doTry() throws Throwable { asyncScope.doAsync(); } @Override protected void doCatch(Throwable e) throws Throwable { throw e; } @Override protected void doFinally() { } @Override AsyncParentContext getContext() { if (super.getState() != TryCatchFinally.State.CREATED && super.getState() != TryCatchFinally.State.TRYING) { throw new IllegalStateException("Already executed"); } return super.getContext(); } } private final class RootAsyncContext implements AsyncParentContext { @Override public void remove(AsyncContextBase async) { assert !complete; complete = true; } @Override public Executor getExecutor() { return executor; } @Override public void fail(AsyncContextBase async, Throwable e) { assert !complete; failure = e; complete = true; } @Override public void add(AsyncContextBase async, Promise<?> waitFor) { if (waitFor != null) { throw new IllegalArgumentException(); } executor.execute(async); } @Override public AsyncStackTrace getStackTrace() { return stackTrace; } @Override public boolean isRethrown(Throwable e) { throw new IllegalStateException("should not be called"); } @Override public AsyncParentContext getCurrentTryCatchFinallyContext() { throw new IllegalStateException("should not be called"); } @Override public boolean getDaemonFlagForHeir() { return false; } @Override public String getParentTaskMethodName() { return null; } @Override public boolean getHideStartFromMethod() { return false; } @Override public String getName() { return name; } @Override public boolean isCancelRequested() { return false; } } private final AsyncScope asyncScope; private boolean complete; private Throwable failure; private AsyncEventLoop executor; private TryCatchFinally root; private AsyncStackTrace stackTrace; private String name; public AsyncScopeContext(AsyncScope asyncScope, boolean disableAsyncStackTrace, boolean excludeAsyncScopeStack) { this.asyncScope = asyncScope; if (!disableAsyncStackTrace) { stackTrace = new AsyncStackTrace(null, new StackTraceElement[0], 0); } executor = new AsyncEventLoop(); AsyncParentContext rootContext = new RootAsyncContext(); AsyncContextBase.setCurrent(rootContext); try { int skipStackLines = excludeAsyncScopeStack ? Integer.MAX_VALUE : 10; root = new RootTryCatchFinally(false, skipStackLines); } finally { AsyncContextBase.setCurrent(null); } } public boolean eventLoop() throws Throwable { if (complete) { throw new IllegalStateException("already complete"); } executor.executeAllQueued(); if (complete && failure != null) { throw failure; } return complete; } public boolean isComplete() { return complete; } public Throwable getFailure() { return failure; } public void cancel(Throwable cause) { root.cancel(cause); } public boolean isCancelRequested() { return root.isCancelRequested(); } public List<AsyncTaskInfo> getAsynchronousStackTraceDump() { return root.getAsynchronousStackTraceDump(); } public String getAsynchronousStackTraceDumpAsString() { return root.getAsynchronousStackTraceDumpAsString(); } public AsyncParentContext getRootContext() { return root.getContext(); } public String getName() { return name; } public void setName(String name) { this.name = name; } }
3,541
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/ExternalTask.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; /** * Used to bridge asynchronous execution to external asynchronous APIs or * events. {@link ExternalTask#doExecute(ExternalTaskCompletionHandle)} method is expected to initiate * call to an external API and return without blocking. Then completion or * failure of the external task is reported through * {@link ExternalTaskCompletionHandle}. A cancellation handler returned by the * doExecute is used to report cancellation of the external task. */ public abstract class ExternalTask extends AsyncContextAware { private final ExternalTaskContext context; public ExternalTask(Promise<?>... waitFor) { context = new ExternalTaskContext(this, null, waitFor); } public ExternalTask(boolean daemon, Promise<?>... waitFor) { context = new ExternalTaskContext(this, daemon, waitFor); } public ExternalTask(AsyncContextAware parent, Promise<?>... waitFor) { context = new ExternalTaskContext(parent.getContext(), this, null, waitFor); } public ExternalTask(AsyncContextAware parent, boolean daemon, Promise<?>... waitFor) { context = new ExternalTaskContext(parent.getContext(), this, daemon, waitFor); } public String getName() { return context.getName(); } public void setName(String name) { context.setName(name); } public StackTraceElement[] getStackTrace() { return context.getStackTrace().getStackTrace(); } @Override AsyncParentContext getContext() { return context; } protected abstract ExternalTaskCancellationHandler doExecute(ExternalTaskCompletionHandle handle) throws Throwable; }
3,542
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/TryCatch.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; public abstract class TryCatch extends TryCatchFinally { public TryCatch(Promise<?>... waitFor) { // The reason this() is not called here is to pass correct value of the skipStackLines. // While this() passes the same value it also adds its own line into the stack trace. super(null, null, 7, waitFor); } public TryCatch(boolean daemon, Promise<?>... waitFor) { super(daemon, null, 7, waitFor); } public TryCatch(AsyncContextAware parent, boolean daemon, Promise<?>... waitFor) { super(parent, daemon, null, 7, waitFor); } public TryCatch(AsyncContextAware parent, Promise<?>... waitFor) { super(parent, null, null, 7, waitFor); } @Override protected void doFinally() throws Throwable { } }
3,543
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/AsyncStackTrace.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.ArrayList; import java.util.List; /** * <pre> * TODO: Deal with repeating async stack frames due to recursion. * So * at a * at -- continuation -- (repeated:1) * at b * at -- continuation -- (repeated:1) * at c * at -- continuation -- (repeated:1) * at d * at -- continuation -- (repeated:1) * at c * at -- continuation -- (repeated:1) * at d * </pre> * Should become something like * <pre> * at a * at -- continuation -- (repeated:1) * at b * at -- continuation -- (repeated:2) * at c * at -- continuation -- (repeated:1) * at d * </pre> */ class AsyncStackTrace { private final StackTraceElement[] stackTrace; private final AsyncStackTrace parentTrace; private String startFrom; private boolean hideStartFromMethod; private final int skip; /** * When set to true disables the removal of any stack elements. * Useful for troubleshooting the broken traces. */ private static final boolean printRawTrace = false; public AsyncStackTrace(AsyncStackTrace parentTrace, StackTraceElement[] stackTrace, int skip) { super(); this.parentTrace = parentTrace; this.stackTrace = stackTrace; this.skip = skip; } public StackTraceElement[] getStackTrace() { if (printRawTrace) { return printRawTrace(); } List<StackTraceElement> result = new ArrayList<StackTraceElement>(); getStackTrace(result); return result.toArray(new StackTraceElement[0]); } private void getStackTrace(List<StackTraceElement> result) { for (int i = skip; i < stackTrace.length; i++) { StackTraceElement element = stackTrace[i]; if (i == skip && result.size() > 0) { StackTraceElement separator = new StackTraceElement("--- continuation ---", "", "", 0); result.add(separator); } if (startFrom != null && element.getMethodName().contains(startFrom)) { if (!hideStartFromMethod) { result.add(element); } break; } result.add(element); } if (parentTrace != null) { parentTrace.getStackTrace(result); } } private StackTraceElement[] printRawTrace() { if (parentTrace != null) { StackTraceElement[] parentStack = parentTrace.getStackTrace(); int parentLength = parentStack.length; if (parentLength > 0) { StackTraceElement separator = new StackTraceElement("---continuation---", "", "", 0); StackTraceElement[] result = new StackTraceElement[stackTrace.length + parentLength + 1]; System.arraycopy(stackTrace, 0, result, 0, stackTrace.length); result[stackTrace.length] = separator; System.arraycopy(parentStack, 0, result, stackTrace.length + 1, parentLength); return result; } } return stackTrace; } public void setStartFrom(String startFrom) { this.startFrom = startFrom; } public void setHideStartFromMethod(boolean hideStartFromMethod) { this.hideStartFromMethod = hideStartFromMethod; } public String toString() { return stackTraceToString(getStackTrace()); } private String stackTraceToString(StackTraceElement[] trace) { StringBuffer result = new StringBuffer(); for (int i = 0; i < trace.length; i++) { if (i > 0) { result.append("\n\tat "); } else { result.append("\tat "); } result.append(trace[i]); } return result.toString(); } }
3,544
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/core/AsyncEventLoop.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.core; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.Executor; class AsyncEventLoop implements Executor { private final Queue<Runnable> tasks = new LinkedList<Runnable>(); @Override public void execute(Runnable task) { synchronized (tasks) { tasks.add(task); } } public void executeAllQueued() { while (executeQueuedTask()) { } } public boolean executeQueuedTask() { synchronized (tasks) { Runnable task = tasks.peek(); if (task == null) { return false; } task.run(); tasks.remove(); return true; } } }
3,545
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/test/TestDecisionContext.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.test; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.WorkflowContext; import com.amazonaws.services.simpleworkflow.flow.generic.GenericActivityClient; import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClient; import com.amazonaws.services.simpleworkflow.flow.worker.LambdaFunctionClient; public class TestDecisionContext extends DecisionContext { private final GenericActivityClient activityClient; private final GenericWorkflowClient workflowClient; private final WorkflowClock workflowClock; private final WorkflowContext workfowContext; private final LambdaFunctionClient lambdaFunctionClient; public TestDecisionContext(GenericActivityClient activityClient, GenericWorkflowClient workflowClient, WorkflowClock workflowClock, WorkflowContext workfowContext, LambdaFunctionClient lambdaFunctionClient) { this.activityClient = activityClient; this.workflowClient = workflowClient; this.workflowClock = workflowClock; this.workfowContext = workfowContext; this.lambdaFunctionClient = lambdaFunctionClient; } @Override public GenericActivityClient getActivityClient() { return activityClient; } @Override public GenericWorkflowClient getWorkflowClient() { return workflowClient; } @Override public WorkflowClock getWorkflowClock() { return workflowClock; } @Override public WorkflowContext getWorkflowContext() { return workfowContext; } @Override public LambdaFunctionClient getLambdaFunctionClient() { return lambdaFunctionClient; } }
3,546
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/test/TestPOJOWorkflowImplementationGenericWorkflowClient.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.test; import java.util.Collection; import java.util.Map; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProvider; import com.amazonaws.services.simpleworkflow.flow.WorkflowException; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.generic.ContinueAsNewWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClient; import com.amazonaws.services.simpleworkflow.flow.generic.SignalExternalWorkflowParameters; import com.amazonaws.services.simpleworkflow.flow.generic.StartChildWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.flow.generic.StartChildWorkflowReply; import com.amazonaws.services.simpleworkflow.flow.pojo.POJOWorkflowDefinitionFactoryFactory; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; import com.amazonaws.services.simpleworkflow.model.WorkflowType; public class TestPOJOWorkflowImplementationGenericWorkflowClient implements GenericWorkflowClient { private final TestGenericWorkflowClient genericClient; private final POJOWorkflowDefinitionFactoryFactory factoryFactory; public TestPOJOWorkflowImplementationGenericWorkflowClient() { factoryFactory = new POJOWorkflowDefinitionFactoryFactory(); genericClient = new TestGenericWorkflowClient(factoryFactory); } public DecisionContextProvider getDecisionContextProvider() { return genericClient.getDecisionContextProvider(); } public void setDecisionContextProvider(DecisionContextProvider decisionContextProvider) { genericClient.setDecisionContextProvider(decisionContextProvider); } public Promise<StartChildWorkflowReply> startChildWorkflow(StartChildWorkflowExecutionParameters parameters) { return genericClient.startChildWorkflow(parameters); } public Promise<String> startChildWorkflow(String workflow, String version, String input) { return genericClient.startChildWorkflow(workflow, version, input); } public Promise<String> startChildWorkflow(String workflow, String version, Promise<String> input) { return genericClient.startChildWorkflow(workflow, version, input); } public Promise<Void> signalWorkflowExecution(SignalExternalWorkflowParameters signalParameters) { return genericClient.signalWorkflowExecution(signalParameters); } public void requestCancelWorkflowExecution(WorkflowExecution execution) { genericClient.requestCancelWorkflowExecution(execution); } public String getWorkflowState(WorkflowExecution execution) throws WorkflowException { return genericClient.getWorkflowState(execution); } public void continueAsNewOnCompletion(ContinueAsNewWorkflowExecutionParameters parameters) { genericClient.continueAsNewOnCompletion(parameters); } public String generateUniqueId() { return genericClient.generateUniqueId(); } public void setDataConverter(DataConverter converter) { factoryFactory.setDataConverter(converter); } public Iterable<WorkflowType> getWorkflowTypesToRegister() { return factoryFactory.getWorkflowTypesToRegister(); } public void addWorkflowImplementationType(Class<?> workflowImplementationType) throws InstantiationException, IllegalAccessException { factoryFactory.addWorkflowImplementationType(workflowImplementationType); } public void addWorkflowImplementationType(Class<?> workflowImplementationType, DataConverter converterOverride) throws InstantiationException, IllegalAccessException { factoryFactory.addWorkflowImplementationType(workflowImplementationType, converterOverride); } public void addWorkflowImplementationType(Class<?> workflowImplementationType, DataConverter converterOverride, Object[] constructorArgs, Map<String, Integer> maximumAllowedComponentImplementationVersions) throws InstantiationException, IllegalAccessException { factoryFactory.addWorkflowImplementationType(workflowImplementationType, converterOverride, constructorArgs, maximumAllowedComponentImplementationVersions); } public void setWorkflowImplementationTypes(Collection<Class<?>> workflowImplementationTypes) throws InstantiationException, IllegalAccessException { factoryFactory.setWorkflowImplementationTypes(workflowImplementationTypes); } }
3,547
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/test/TestLambdaFunctionInvoker.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.test; public interface TestLambdaFunctionInvoker { String invoke(String name, String input, long timeout); }
3,548
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/test/TestPOJOActivityImplementationGenericActivityClient.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.test; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.generic.ExecuteActivityParameters; import com.amazonaws.services.simpleworkflow.flow.generic.GenericActivityClient; public class TestPOJOActivityImplementationGenericActivityClient implements GenericActivityClient { private final TestGenericActivityClient genericClient; public TestPOJOActivityImplementationGenericActivityClient() { genericClient = new TestGenericActivityClient(); } public void addWorker(TestPOJOActivityImplementationWorker worker) { genericClient.addFactory(worker.getTaskList(), worker.getFactory()); } public Promise<String> scheduleActivityTask(ExecuteActivityParameters parameters) { return genericClient.scheduleActivityTask(parameters); } public Promise<String> scheduleActivityTask(String activity, String version, String input) { return genericClient.scheduleActivityTask(activity, version, input); } public Promise<String> scheduleActivityTask(String activity, String version, Promise<String> input) { return genericClient.scheduleActivityTask(activity, version, input); } }
3,549
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/test/TestWorkflowClock.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.test; import java.util.PriorityQueue; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.core.ExternalTask; import com.amazonaws.services.simpleworkflow.flow.core.ExternalTaskCancellationHandler; import com.amazonaws.services.simpleworkflow.flow.core.ExternalTaskCompletionHandle; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.core.Task; public class TestWorkflowClock implements WorkflowClock { private static final int SECOND = 1000; private static class TimerInfo<T> implements Comparable<TimerInfo<T>> { final Long fireTime; final Settable<T> timerResult = new Settable<T>(); final T context; private Settable<ExternalTaskCompletionHandle> handle = new Settable<ExternalTaskCompletionHandle>(); public TimerInfo(long fireTime, T context) { this.fireTime = fireTime; this.context = context; } public void fire() { timerResult.set(context); if (handle.isReady()) { handle.get().complete(); } else { new Task(handle) { @Override protected void doExecute() throws Throwable { handle.get().complete(); } }; } } public Promise<T> getResult() { return timerResult; } @Override public int compareTo(TimerInfo<T> o) { return fireTime.compareTo(o.fireTime); } public void cancel() { handle.get().complete(); } public long getFireTime() { return fireTime; } public void setCompletionHandle(ExternalTaskCompletionHandle handle) { this.handle.set(handle); } public void setResultDescription(String description) { timerResult.setDescription(description); } } private long clockTime = 0L; private PriorityQueue<TimerInfo<?>> timers = new PriorityQueue<TimerInfo<?>>(); @Override public long currentTimeMillis() { return clockTime; } public void setCurrentTimeMillis(long timeMillis) { clockTime = timeMillis; } @Override public boolean isReplaying() { // Unit test never replays return false; } @Override public Promise<Void> createTimer(long delaySeconds) { return createTimer(delaySeconds, null); } @Override public <T> Promise<T> createTimer(final long delaySeconds, final T context, final String timerId) { return createTimer(delaySeconds, context); } @Override public <T> Promise<T> createTimer(final long delaySeconds, final T context) { if (delaySeconds < 0) { throw new IllegalArgumentException("negative delaySeconds"); } if (delaySeconds == 0) { return Promise.asPromise(context); } long fireTime = clockTime + delaySeconds * 1000; final TimerInfo<T> timer = new TimerInfo<T>(fireTime, context); String timerName = "delay=" + delaySeconds; timer.setResultDescription("createTimer " + timerName); timers.add(timer); new ExternalTask() { @Override protected ExternalTaskCancellationHandler doExecute(ExternalTaskCompletionHandle handle) throws Throwable { timer.setCompletionHandle(handle); return new ExternalTaskCancellationHandler() { @Override public void handleCancellation(Throwable e) { timers.remove(timer); timer.cancel(); } }; } }.setName(timerName); return timer.getResult(); } public Long fireTimers() { while (true) { TimerInfo<?> timer = timers.peek(); if (timer == null) { return null; } long timerTime = timer.getFireTime(); if (timerTime > clockTime) { return timerTime - clockTime; } timers.poll(); timer.fire(); } } public void advanceSeconds(long seconds) { advanceMilliseconds(seconds * SECOND); } public void advanceMilliseconds(long milliseconds) { clockTime += milliseconds; while (true) { TimerInfo<?> timer = timers.peek(); if (timer == null) { break; } long timerTime = timer.getFireTime(); if (timerTime > clockTime) { break; } timer.fire(); timers.poll(); } } }
3,550
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/test/TestLambdaFunctionClient.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.test; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProvider; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProviderImpl; import com.amazonaws.services.simpleworkflow.flow.LambdaFunctionException; import com.amazonaws.services.simpleworkflow.flow.LambdaFunctionFailedException; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.core.Task; import com.amazonaws.services.simpleworkflow.flow.worker.LambdaFunctionClient; public class TestLambdaFunctionClient implements LambdaFunctionClient { protected final DecisionContextProvider decisionContextProvider; protected TestLambdaFunctionInvoker invoker; public TestLambdaFunctionClient() { this.decisionContextProvider = new DecisionContextProviderImpl(); } @Override public Promise<String> scheduleLambdaFunction(final String name, final String input) { return scheduleLambdaFunction(name, input, FlowConstants.DEFAULT_LAMBDA_FUNCTION_TIMEOUT); } @Override public Promise<String> scheduleLambdaFunction(final String name, final Promise<String> input) { return scheduleLambdaFunction(name, input, FlowConstants.DEFAULT_LAMBDA_FUNCTION_TIMEOUT); } @Override public Promise<String> scheduleLambdaFunction(final String name, final Promise<String> input, final long timeoutSeconds) { final Settable<String> result = new Settable<String>(); new Task(input) { @Override protected void doExecute() throws Throwable { result.chain(scheduleLambdaFunction(name, input.get(), timeoutSeconds)); } }; return result; } @Override public Promise<String> scheduleLambdaFunction(final String name, final String input, final long timeoutSeconds) { final String functionId = decisionContextProvider.getDecisionContext() .getWorkflowClient().generateUniqueId(); return scheduleLambdaFunction(name, input, timeoutSeconds, functionId); } @Override public Promise<String> scheduleLambdaFunction(String name, String input, long timeoutSeconds, final String functionId) { final Settable<String> result = new Settable<String>(); try { result.set(invoker.invoke(name, input, timeoutSeconds)); } catch (Throwable e) { if (e instanceof LambdaFunctionException) { throw (LambdaFunctionException) e; } else { LambdaFunctionFailedException failure = new LambdaFunctionFailedException( 0, name, functionId, e.getMessage()); failure.initCause(e); throw failure; } } return result; } public void setInvoker(TestLambdaFunctionInvoker invoker) { this.invoker = invoker; } }
3,551
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/test/TestGenericWorkflowClient.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.test; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.CancellationException; import com.amazonaws.services.simpleworkflow.flow.ChildWorkflowFailedException; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProvider; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProviderImpl; import com.amazonaws.services.simpleworkflow.flow.SignalExternalWorkflowException; import com.amazonaws.services.simpleworkflow.flow.StartChildWorkflowFailedException; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.WorkflowException; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.flow.core.Functor; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.core.Task; import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally; import com.amazonaws.services.simpleworkflow.flow.generic.ContinueAsNewWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.flow.generic.GenericActivityClient; import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClient; import com.amazonaws.services.simpleworkflow.flow.generic.SignalExternalWorkflowParameters; import com.amazonaws.services.simpleworkflow.flow.generic.StartChildWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.flow.generic.StartChildWorkflowReply; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinition; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactory; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactoryFactory; import com.amazonaws.services.simpleworkflow.flow.worker.LambdaFunctionClient; import com.amazonaws.services.simpleworkflow.model.StartChildWorkflowExecutionFailedCause; import com.amazonaws.services.simpleworkflow.model.UnknownResourceException; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; import com.amazonaws.services.simpleworkflow.model.WorkflowType; public class TestGenericWorkflowClient implements GenericWorkflowClient { private static class StartChildWorkflowReplyImpl implements StartChildWorkflowReply { private final Settable<String> result; private final String runId; private final String workflowId; private StartChildWorkflowReplyImpl(Settable<String> result, String workflowId, String runId) { this.result = result; this.workflowId = workflowId; this.runId = runId; } @Override public String getWorkflowId() { return workflowId; } @Override public String getRunId() { return runId; } @Override public Promise<String> getResult() { return result; } } private final class ChildWorkflowTryCatchFinally extends TryCatchFinally { private final StartChildWorkflowExecutionParameters parameters; private final WorkflowExecution childExecution; private final Settable<String> result; /** * Child workflow doesn't set result to ready state before completing * all its tasks. So we need to set external result only in doFinally. */ private final Settable<String> executeResult = new Settable<String>(); private final WorkflowDefinition childWorkflowDefinition; private final DecisionContext childContext; private boolean failed; private final Settable<ContinueAsNewWorkflowExecutionParameters> continueAsNew = new Settable<ContinueAsNewWorkflowExecutionParameters>(); private ChildWorkflowTryCatchFinally(StartChildWorkflowExecutionParameters parameters, WorkflowExecution childExecution, WorkflowDefinition childWorkflowDefinition, DecisionContext context, Settable<String> result) { this.parameters = parameters; this.childExecution = childExecution; this.childWorkflowDefinition = childWorkflowDefinition; this.childContext = context; this.result = result; } @Override protected void doTry() throws Throwable { executeResult.chain(childWorkflowDefinition.execute(parameters.getInput())); } @Override protected void doCatch(Throwable e) throws Throwable { failed = true; if (e instanceof WorkflowException) { WorkflowException we = (WorkflowException) e; throw new ChildWorkflowFailedException(0, childExecution, parameters.getWorkflowType(), e.getMessage(), we.getDetails()); } else if (e instanceof CancellationException) { throw e; } // Unless there is problem in the framework or generic workflow implementation this shouldn't be executed Exception failure = new ChildWorkflowFailedException(0, childExecution, parameters.getWorkflowType(), e.getMessage(), "null"); failure.initCause(e); throw failure; } @Override protected void doFinally() throws Throwable { if (!failed) { continueAsNew.set(childContext.getWorkflowContext().getContinueAsNewOnCompletion()); if (continueAsNew.get() == null && executeResult.isReady()) { result.set(executeResult.get()); } } else { continueAsNew.set(null); } workflowExecutions.remove(this.childExecution.getWorkflowId()); } public void signalRecieved(final String signalName, final String details) { if (getState() != State.TRYING) { throw new SignalExternalWorkflowException(0, childExecution, "UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION"); } new Task(this) { @Override protected void doExecute() throws Throwable { childWorkflowDefinition.signalRecieved(signalName, details); } }; } public StartChildWorkflowExecutionParameters getParameters() { return parameters; } public String getWorkflowState() throws WorkflowException { return childWorkflowDefinition.getWorkflowState(); } public WorkflowExecution getWorkflowExecution() { return childExecution; } public Promise<ContinueAsNewWorkflowExecutionParameters> getContinueAsNew() { return continueAsNew; } } private final Map<String, ChildWorkflowTryCatchFinally> workflowExecutions = new HashMap<String, ChildWorkflowTryCatchFinally>(); protected WorkflowDefinitionFactoryFactory factoryFactory; protected DecisionContextProvider decisionContextProvider; public TestGenericWorkflowClient(WorkflowDefinitionFactoryFactory factoryFactory, DecisionContextProvider decisionContextProvider) { this.factoryFactory = factoryFactory; this.decisionContextProvider = decisionContextProvider; } public TestGenericWorkflowClient(WorkflowDefinitionFactoryFactory factoryFactory) { this(factoryFactory, new DecisionContextProviderImpl()); } public TestGenericWorkflowClient() { this(null, new DecisionContextProviderImpl()); } public WorkflowDefinitionFactoryFactory getFactoryFactory() { return factoryFactory; } public void setFactoryFactory(WorkflowDefinitionFactoryFactory factoryFactory) { this.factoryFactory = factoryFactory; } public DecisionContextProvider getDecisionContextProvider() { return decisionContextProvider; } public void setDecisionContextProvider(DecisionContextProvider decisionContextProvider) { this.decisionContextProvider = decisionContextProvider; } @Override public Promise<StartChildWorkflowReply> startChildWorkflow(final StartChildWorkflowExecutionParameters parameters) { Settable<StartChildWorkflowReply> reply = new Settable<StartChildWorkflowReply>(); Settable<String> result = new Settable<String>(); startChildWorkflow(parameters, reply, result); return reply; } private void startChildWorkflow(final StartChildWorkflowExecutionParameters parameters, final Settable<StartChildWorkflowReply> reply, final Settable<String> result) { String workflowId = parameters.getWorkflowId(); WorkflowType workflowType = parameters.getWorkflowType(); WorkflowExecution childExecution = new WorkflowExecution(); final String runId = UUID.randomUUID().toString(); //TODO: Validate parameters against registration options to find missing timeouts or other options try { DecisionContext parentDecisionContext = decisionContextProvider.getDecisionContext(); if (workflowId == null) { workflowId = decisionContextProvider.getDecisionContext().getWorkflowClient().generateUniqueId(); } childExecution.setWorkflowId(workflowId); childExecution.setRunId(runId); final GenericActivityClient activityClient = parentDecisionContext.getActivityClient(); final WorkflowClock workflowClock = parentDecisionContext.getWorkflowClock(); final LambdaFunctionClient lambdaFunctionClient = parentDecisionContext.getLambdaFunctionClient(); WorkflowDefinitionFactory factory; if (factoryFactory == null) { throw new IllegalStateException("required property factoryFactory is null"); } factory = factoryFactory.getWorkflowDefinitionFactory(workflowType); if (factory == null) { String cause = StartChildWorkflowExecutionFailedCause.WORKFLOW_TYPE_DOES_NOT_EXIST.toString(); throw new StartChildWorkflowFailedException(0, childExecution, workflowType, cause); } TestWorkflowContext workflowContext = new TestWorkflowContext(); workflowContext.setWorkflowExecution(childExecution); workflowContext.setWorkflowType(parameters.getWorkflowType()); workflowContext.setParentWorkflowExecution(parentDecisionContext.getWorkflowContext().getWorkflowExecution()); workflowContext.setTagList(parameters.getTagList()); workflowContext.setTaskList(parameters.getTaskList()); DecisionContext context = new TestDecisionContext(activityClient, TestGenericWorkflowClient.this, workflowClock, workflowContext, lambdaFunctionClient); //this, parameters, childExecution, workflowClock, activityClient); final WorkflowDefinition childWorkflowDefinition = factory.getWorkflowDefinition(context); final ChildWorkflowTryCatchFinally tryCatch = new ChildWorkflowTryCatchFinally(parameters, childExecution, childWorkflowDefinition, context, result); workflowContext.setRootTryCatch(tryCatch); ChildWorkflowTryCatchFinally currentRun = workflowExecutions.get(workflowId); if (currentRun != null) { String cause = StartChildWorkflowExecutionFailedCause.WORKFLOW_ALREADY_RUNNING.toString(); throw new StartChildWorkflowFailedException(0, childExecution, workflowType, cause); } workflowExecutions.put(workflowId, tryCatch); continueAsNewWorkflowExecution(tryCatch, result); } catch (StartChildWorkflowFailedException e) { throw e; } catch (Throwable e) { // This cause is chosen to represent internal error for sub-workflow creation String cause = StartChildWorkflowExecutionFailedCause.OPEN_CHILDREN_LIMIT_EXCEEDED.toString(); StartChildWorkflowFailedException failure = new StartChildWorkflowFailedException(0, childExecution, workflowType, cause); failure.initCause(e); throw failure; } finally { reply.set(new StartChildWorkflowReplyImpl(result, workflowId, runId)); } } private void continueAsNewWorkflowExecution(final ChildWorkflowTryCatchFinally tryCatch, final Settable<String> result) { // It is always set to ready with null if no continuation is necessary final Promise<ContinueAsNewWorkflowExecutionParameters> continueAsNew = tryCatch.getContinueAsNew(); new Task(continueAsNew) { @Override protected void doExecute() throws Throwable { ContinueAsNewWorkflowExecutionParameters cp = continueAsNew.get(); if (cp == null) { return; } StartChildWorkflowExecutionParameters nextParameters = new StartChildWorkflowExecutionParameters(); nextParameters.setInput(cp.getInput()); WorkflowExecution previousWorkflowExecution = tryCatch.getWorkflowExecution(); String workflowId = previousWorkflowExecution.getWorkflowId(); nextParameters.setWorkflowId(workflowId); StartChildWorkflowExecutionParameters previousParameters = tryCatch.getParameters(); nextParameters.setWorkflowType(previousParameters.getWorkflowType()); long startToClose = cp.getExecutionStartToCloseTimeoutSeconds(); if (startToClose == FlowConstants.NONE) { startToClose = previousParameters.getExecutionStartToCloseTimeoutSeconds(); } nextParameters.setExecutionStartToCloseTimeoutSeconds(startToClose); long taskStartToClose = cp.getTaskStartToCloseTimeoutSeconds(); if (taskStartToClose == FlowConstants.NONE) { taskStartToClose = previousParameters.getTaskStartToCloseTimeoutSeconds(); } nextParameters.setTaskStartToCloseTimeoutSeconds(taskStartToClose); int taskPriority = cp.getTaskPriority(); nextParameters.setTaskPriority(taskPriority); Settable<StartChildWorkflowReply> reply = new Settable<StartChildWorkflowReply>(); startChildWorkflow(nextParameters, reply, result); } }; } @Override public Promise<String> startChildWorkflow(String workflow, String version, String input) { StartChildWorkflowExecutionParameters parameters = new StartChildWorkflowExecutionParameters(); WorkflowType workflowType = new WorkflowType().withName(workflow).withVersion(version); parameters.setWorkflowType(workflowType); parameters.setInput(input); Settable<StartChildWorkflowReply> reply = new Settable<StartChildWorkflowReply>(); Settable<String> result = new Settable<String>(); startChildWorkflow(parameters, reply, result); return result; } @Override public Promise<String> startChildWorkflow(final String workflow, final String version, final Promise<String> input) { return new Functor<String>(input) { @Override protected Promise<String> doExecute() throws Throwable { return startChildWorkflow(workflow, version, input.get()); } }; } @Override public Promise<Void> signalWorkflowExecution(final SignalExternalWorkflowParameters signalParameters) { WorkflowExecution signaledExecution = new WorkflowExecution(); signaledExecution.setWorkflowId(signalParameters.getWorkflowId()); signaledExecution.setRunId(signalParameters.getRunId()); final ChildWorkflowTryCatchFinally childTryCatch = workflowExecutions.get(signalParameters.getWorkflowId()); if (childTryCatch == null) { throw new SignalExternalWorkflowException(0, signaledExecution, "UNKNOWN_EXTERNAL_WORKFLOW_EXECUTION"); } String openExecutionRunId = childTryCatch.getWorkflowExecution().getRunId(); if (signalParameters.getRunId() != null && !openExecutionRunId.equals(signalParameters.getRunId())) { throw new SignalExternalWorkflowException(0, signaledExecution, "Unknown Execution (runId doesn't match)"); } childTryCatch.signalRecieved(signalParameters.getSignalName(), signalParameters.getInput()); return Promise.Void(); } @Override public void requestCancelWorkflowExecution(WorkflowExecution execution) { String workflowId = execution.getWorkflowId(); if (workflowId == null) { throw new IllegalArgumentException("null workflowId"); } final ChildWorkflowTryCatchFinally childTryCatch = workflowExecutions.get(workflowId); if (childTryCatch == null) { throw new UnknownResourceException("Unknown excution: " + execution.toString()); } String openExecutionRunId = childTryCatch.getWorkflowExecution().getRunId(); if (execution.getRunId() != null && !openExecutionRunId.equals(execution.getRunId())) { throw new UnknownResourceException("Unknown Execution (runId doesn't match)"); } childTryCatch.cancel(new CancellationException()); } public String getWorkflowState(WorkflowExecution execution) throws WorkflowException { String workflowId = execution.getWorkflowId(); if (workflowId == null) { throw new IllegalArgumentException("null workflowId"); } final ChildWorkflowTryCatchFinally childTryCatch = workflowExecutions.get(workflowId); if (childTryCatch == null) { throw new UnknownResourceException(execution.toString()); } String openExecutionRunId = childTryCatch.getWorkflowExecution().getRunId(); if (execution.getRunId() != null && !openExecutionRunId.equals(execution.getRunId())) { throw new UnknownResourceException("Unknown Execution (runId doesn't match)"); } return childTryCatch.getWorkflowState(); } @Override public void continueAsNewOnCompletion(ContinueAsNewWorkflowExecutionParameters parameters) { DecisionContext decisionContext = decisionContextProvider.getDecisionContext(); decisionContext.getWorkflowContext().setContinueAsNewOnCompletion(parameters); } @Override public String generateUniqueId() { return UUID.randomUUID().toString(); } }
3,552
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/test/TestPOJOActivityImplementationWorker.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.test; import java.util.List; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.generic.ActivityImplementation; import com.amazonaws.services.simpleworkflow.flow.pojo.POJOActivityImplementationFactory; import com.amazonaws.services.simpleworkflow.model.ActivityType; public class TestPOJOActivityImplementationWorker { private final POJOActivityImplementationFactory factory = new POJOActivityImplementationFactory(); private final String taskList; public TestPOJOActivityImplementationWorker(String taskList) { this.taskList = taskList; } POJOActivityImplementationFactory getFactory() { return factory; } public String getTaskList() { return taskList; } public void setActivitiesImplementations(Iterable<Object> activitiesImplementations) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { factory.setActivitiesImplementations(activitiesImplementations); } public Iterable<Object> getActivitiesImplementations() { return factory.getActivitiesImplementations(); } public List<ActivityType> addActivitiesImplementations(Iterable<Object> activitiesImplementations) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { return factory.addActivitiesImplementations(activitiesImplementations); } public List<ActivityType> addActivitiesImplementations(Iterable<Object> activitiesImplementations, DataConverter dataConverter) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { return factory.addActivitiesImplementations(activitiesImplementations, dataConverter); } public List<ActivityType> addActivitiesImplementation(Object activitiesImplementation) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { return factory.addActivitiesImplementation(activitiesImplementation); } public List<ActivityType> addActivitiesImplementation(Object activitiesImplementation, DataConverter converter) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { return factory.addActivitiesImplementation(activitiesImplementation, converter); } public Iterable<ActivityType> getActivityTypesToRegister() { return factory.getActivityTypesToRegister(); } public ActivityImplementation getActivityImplementation(ActivityType activityType) { return factory.getActivityImplementation(activityType); } public DataConverter getDataConverter() { return factory.getDataConverter(); } public void setDataConverter(DataConverter dataConverter) { factory.setDataConverter(dataConverter); } }
3,553
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/test/TestGenericActivityClient.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.test; import java.util.HashMap; import java.util.Map; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContext; import com.amazonaws.services.simpleworkflow.flow.ActivityFailureException; import com.amazonaws.services.simpleworkflow.flow.ActivityTaskFailedException; import com.amazonaws.services.simpleworkflow.flow.ActivityTaskTimedOutException; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProvider; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProviderImpl; import com.amazonaws.services.simpleworkflow.flow.ScheduleActivityTaskFailedException; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.flow.core.*; import com.amazonaws.services.simpleworkflow.flow.generic.*; import com.amazonaws.services.simpleworkflow.flow.worker.ActivityTypeRegistrationOptions; import com.amazonaws.services.simpleworkflow.model.ActivityTask; import com.amazonaws.services.simpleworkflow.model.ActivityTaskTimeoutType; import com.amazonaws.services.simpleworkflow.model.ActivityType; import com.amazonaws.services.simpleworkflow.model.ScheduleActivityTaskFailedCause; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; public class TestGenericActivityClient implements GenericActivityClient { private final class TestActivityExecutionContext extends ActivityExecutionContext { private final ActivityTask activityTask; private final WorkflowExecution workflowExecution; private TestActivityExecutionContext(ActivityTask activityTask, WorkflowExecution workflowExecution) { this.activityTask = activityTask; this.workflowExecution = workflowExecution; } @Override public void recordActivityHeartbeat(String details) throws AmazonServiceException, AmazonClientException { //TODO: timeouts } @Override public ActivityTask getTask() { return activityTask; } @Override public AmazonSimpleWorkflow getService() { throw new UnsupportedOperationException("not implemented"); } @Override public String getTaskToken() { return activityTask.getTaskToken(); } @Override public WorkflowExecution getWorkflowExecution() { return workflowExecution; } @Override public String getDomain() { return "dummyTestDomain"; } } /** * Key is TaskList */ protected final Map<String, ActivityImplementationFactory> factories = new HashMap<String, ActivityImplementationFactory>(); protected final Map<ActivityType, ActivityTypeRegistrationOptions> registrationOptions = new HashMap<ActivityType, ActivityTypeRegistrationOptions>(); protected final Map<ActivityType, String> workerTaskLists = new HashMap<ActivityType, String>(); protected final DecisionContextProvider decisionContextProvider; public TestGenericActivityClient(DecisionContextProvider decisionContextProvider) { this.decisionContextProvider = decisionContextProvider; } public TestGenericActivityClient() { this(new DecisionContextProviderImpl()); } public void addFactory(String taskListToListen, ActivityImplementationFactory factory) { factories.put(taskListToListen, factory); Iterable<ActivityType> typesToRegister = factory.getActivityTypesToRegister(); for (ActivityType activityType : typesToRegister) { ActivityImplementation implementation = factory.getActivityImplementation(activityType); ActivityTypeRegistrationOptions ro = implementation.getRegistrationOptions(); registrationOptions.put(activityType, ro); workerTaskLists.put(activityType, taskListToListen); } } @Override public Promise<String> scheduleActivityTask(final ExecuteActivityParameters parameters) { final ActivityType activityType = parameters.getActivityType(); final Settable<String> result = new Settable<String>(); final ActivityTask activityTask = new ActivityTask(); String activityId = parameters.getActivityId(); if (activityId == null) { activityId = decisionContextProvider.getDecisionContext().getWorkflowClient().generateUniqueId(); } activityTask.setActivityId(activityId); activityTask.setActivityType(activityType); activityTask.setInput(parameters.getInput()); activityTask.setStartedEventId(0L); activityTask.setTaskToken("dummyTaskToken"); DecisionContext decisionContext = decisionContextProvider.getDecisionContext(); final WorkflowExecution workflowExecution = decisionContext.getWorkflowContext().getWorkflowExecution(); activityTask.setWorkflowExecution(workflowExecution); String taskList = parameters.getTaskList(); if (taskList == null) { ActivityTypeRegistrationOptions ro = registrationOptions.get(activityType); if (ro == null) { String cause = ScheduleActivityTaskFailedCause.ACTIVITY_TYPE_DOES_NOT_EXIST.toString(); throw new ScheduleActivityTaskFailedException(0, activityType, activityId, cause); } taskList = ro.getDefaultTaskList(); if (FlowConstants.NO_DEFAULT_TASK_LIST.equals(taskList)) { String cause = ScheduleActivityTaskFailedCause.DEFAULT_TASK_LIST_UNDEFINED.toString(); throw new ScheduleActivityTaskFailedException(0, activityType, activityId, cause); } else if (taskList == null) { taskList = workerTaskLists.get(activityType); } } ActivityImplementationFactory factory = factories.get(taskList); // Nobody listens on the specified task list. So in case of a real service it causes // ScheduleToStart timeout. //TODO: Activity heartbeats and passing details to the exception. if (factory == null) { String timeoutType = ActivityTaskTimeoutType.SCHEDULE_TO_START.toString(); throw new ActivityTaskTimedOutException(0, activityType, activityId, timeoutType, null); } final ActivityImplementation impl = factory.getActivityImplementation(activityType); if (impl == null) { String cause = ScheduleActivityTaskFailedCause.ACTIVITY_TYPE_DOES_NOT_EXIST.toString(); throw new ScheduleActivityTaskFailedException(0, activityType, activityId, cause); } ActivityExecutionContext executionContext = new TestActivityExecutionContext(activityTask, workflowExecution); try { String activityResult = impl.execute(executionContext); result.set(activityResult); } catch (Throwable e) { if (e instanceof ActivityFailureException) { ActivityFailureException falure = (ActivityFailureException) e; throw new ActivityTaskFailedException(0, activityType, parameters.getActivityId(), falure.getReason(), falure.getDetails()); } // Unless there is problem in the framework or generic activity implementation this shouldn't be executed ActivityTaskFailedException failure = new ActivityTaskFailedException(0, activityType, parameters.getActivityId(), e.getMessage(), null); failure.initCause(e); throw failure; } return result; } @Override public Promise<String> scheduleActivityTask(String activity, String version, String input) { ExecuteActivityParameters parameters = new ExecuteActivityParameters(); ActivityType activityType = new ActivityType(); activityType.setName(activity); activityType.setVersion(version); parameters.setActivityType(activityType); parameters.setInput(input); return scheduleActivityTask(parameters); } @Override public Promise<String> scheduleActivityTask(final String activity, final String version, final Promise<String> input) { final Settable<String> result = new Settable<String>(); new Task(input) { @Override protected void doExecute() throws Throwable { result.chain(scheduleActivityTask(activity, version, input.get())); } }; return result; } }
3,554
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/test/TestWorkflowContext.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.test; import java.util.List; import com.amazonaws.services.simpleworkflow.flow.WorkflowContext; import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally; import com.amazonaws.services.simpleworkflow.flow.generic.ContinueAsNewWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.model.ChildPolicy; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; import com.amazonaws.services.simpleworkflow.model.WorkflowType; public class TestWorkflowContext implements WorkflowContext { private WorkflowExecution workflowExecution; private WorkflowType workflowType; private ContinueAsNewWorkflowExecutionParameters continueAsNewOnCompletion; private WorkflowExecution parentWorkflowExecution; private List<String> tagList; private ChildPolicy childPolicy; private String continuedExecutionRunId; private long executionStartToCloseTimeout; private String taskList; private int taskPriority; private String lambdaRole; private TryCatchFinally rootTryCatch; public WorkflowExecution getWorkflowExecution() { return workflowExecution; } public void setWorkflowExecution(WorkflowExecution workflowExecution) { this.workflowExecution = workflowExecution; } public WorkflowType getWorkflowType() { return workflowType; } public void setWorkflowType(WorkflowType workflowType) { this.workflowType = workflowType; } public ContinueAsNewWorkflowExecutionParameters getContinueAsNewOnCompletion() { return continueAsNewOnCompletion; } public void setContinueAsNewOnCompletion(ContinueAsNewWorkflowExecutionParameters continueAsNewOnCompletion) { this.continueAsNewOnCompletion = continueAsNewOnCompletion; } public WorkflowExecution getParentWorkflowExecution() { return parentWorkflowExecution; } public void setParentWorkflowExecution(WorkflowExecution parentWorkflowExecution) { this.parentWorkflowExecution = parentWorkflowExecution; } public List<String> getTagList() { return tagList; } public void setTagList(List<String> tagList) { this.tagList = tagList; } public ChildPolicy getChildPolicy() { return childPolicy; } public void setChildPolicy(ChildPolicy childPolicy) { this.childPolicy = childPolicy; } public String getContinuedExecutionRunId() { return continuedExecutionRunId; } public void setContinuedExecutionRunId(String continuedExecutionRunId) { this.continuedExecutionRunId = continuedExecutionRunId; } public long getExecutionStartToCloseTimeout() { return executionStartToCloseTimeout; } public void setExecutionStartToCloseTimeout(long executionStartToCloseTimeout) { this.executionStartToCloseTimeout = executionStartToCloseTimeout; } public String getTaskList() { return taskList; } public void setTaskList(String taskList) { this.taskList = taskList; } public String getLambdaRole() { return lambdaRole; } public void setLambdaRole(String lambdaRole) { this.lambdaRole = lambdaRole; } public boolean isCancelRequested() { return rootTryCatch.isCancelRequested(); } public void setRootTryCatch(TryCatchFinally rootTryCatch) { this.rootTryCatch = rootTryCatch; } public int getTaskPriority() { return taskPriority; } public void setTaskPriority(int taskPriority) { this.taskPriority = taskPriority; } @Override public boolean isImplementationVersion(String component, int version) { return true; } @Override public Integer getVersion(String component) { return null; } }
3,555
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/retry/Retrier.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.retry; import com.amazonaws.services.simpleworkflow.flow.worker.BackoffThrottler; import com.amazonaws.services.simpleworkflow.flow.worker.ExponentialRetryParameters; import org.apache.commons.logging.Log; /** * This class is for internal use only and may be changed or removed without prior notice. * */ public abstract class Retrier { private final ExponentialRetryParameters retryParameters; private final Log logger; public Retrier(ExponentialRetryParameters retryParameters, Log logger) { if (retryParameters.getBackoffCoefficient() < 0) { throw new IllegalArgumentException("negative backoffCoefficient"); } if (retryParameters.getInitialInterval() < 10) { throw new IllegalArgumentException("initialInterval cannot be less then 10: " + retryParameters.getInitialInterval()); } if (retryParameters.getExpirationInterval() < retryParameters.getInitialInterval()) { throw new IllegalArgumentException("expirationInterval < initialInterval"); } if (retryParameters.getMaximumRetries() < retryParameters.getMinimumRetries()) { throw new IllegalArgumentException("maximumRetries < minimumRetries"); } this.retryParameters = retryParameters; this.logger = logger; } protected abstract BackoffThrottler createBackoffThrottler(); protected abstract boolean shouldRetry(RuntimeException e); public void retry(Runnable r) { int attempt = 0; long startTime = System.currentTimeMillis(); BackoffThrottler throttler = createBackoffThrottler(); boolean success = false; do { try { attempt++; throttler.throttle(); r.run(); success = true; throttler.success(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } catch (RuntimeException e) { throttler.failure(); if (!shouldRetry(e)) { throw e; } long elapsed = System.currentTimeMillis() - startTime; if (attempt > retryParameters.getMaximumRetries() || (elapsed >= retryParameters.getExpirationInterval() && attempt > retryParameters.getMinimumRetries())) { throw e; } logger.warn("Retrying after failure", e); } } while (!success); } public ExponentialRetryParameters getRetryParameters() { return retryParameters; } }
3,556
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/retry/ThrottlingRetrier.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.retry; import com.amazonaws.AmazonServiceException; import com.amazonaws.retry.RetryUtils; import com.amazonaws.services.simpleworkflow.flow.worker.BackoffThrottler; import com.amazonaws.services.simpleworkflow.flow.worker.BackoffThrottlerWithJitter; import com.amazonaws.services.simpleworkflow.flow.worker.ExponentialRetryParameters; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A retrier only for throttling exception. * This class is for internal use only and may be changed or removed without prior notice. */ public class ThrottlingRetrier extends Retrier { private static final Log logger = LogFactory.getLog(ThrottlingRetrier.class); public ThrottlingRetrier(ExponentialRetryParameters retryParameters) { super(retryParameters, logger); } @Override protected BackoffThrottler createBackoffThrottler() { return new BackoffThrottlerWithJitter(getRetryParameters().getInitialInterval(), getRetryParameters().getMaximumRetryInterval(), getRetryParameters().getBackoffCoefficient()); } @Override protected boolean shouldRetry(RuntimeException e) { return e instanceof AmazonServiceException && RetryUtils.isThrottlingException((AmazonServiceException) e); } }
3,557
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/retry/SynchronousRetrier.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.retry; import com.amazonaws.services.simpleworkflow.flow.worker.BackoffThrottler; import com.amazonaws.services.simpleworkflow.flow.worker.ExponentialRetryParameters; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * This class is for internal use only and may be changed or removed without prior notice. * */ public class SynchronousRetrier extends Retrier { private static final Log logger = LogFactory.getLog(SynchronousRetrier.class); private final Class<?>[] exceptionsToNotRetry; public SynchronousRetrier(ExponentialRetryParameters retryParameters, Class<?>... exceptionsToNotRetry) { super(retryParameters, logger); this.exceptionsToNotRetry = exceptionsToNotRetry; } public Class<?>[] getExceptionsToNotRetry() { return exceptionsToNotRetry; } @Override protected BackoffThrottler createBackoffThrottler() { return new BackoffThrottler(getRetryParameters().getInitialInterval(), getRetryParameters().getMaximumRetryInterval(), getRetryParameters().getBackoffCoefficient()); } @Override protected boolean shouldRetry(RuntimeException e) { for (Class<?> exceptionToNotRetry : getExceptionsToNotRetry()) { if (exceptionToNotRetry.isAssignableFrom(e.getClass())) { return false; } } return true; } }
3,558
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/config/SimpleWorkflowClientConfig.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.config; import java.time.Duration; public class SimpleWorkflowClientConfig { private final Duration dataPlaneRequestTimeout; private final Duration pollingRequestTimeout; private final Duration controlPlaneRequestTimeout; private static final int DEFAULT_POLLING_REQUEST_TIMEOUT_IN_SEC = 70; private static final int DEFAULT_DATA_PLANE_REQUEST_TIMEOUT_IN_SEC = 6; private static final int DEFAULT_CONTROL_PLANE_REQUEST_TIMEOUT_IN_SEC = 10; /** * Class method to provide SimpleWorkflowClientConfig with default timeouts * * @return SimpleWorkflowClientConfig instance */ public static SimpleWorkflowClientConfig ofDefaults() { return new SimpleWorkflowClientConfig(Duration.ofSeconds(DEFAULT_POLLING_REQUEST_TIMEOUT_IN_SEC), Duration.ofSeconds(DEFAULT_DATA_PLANE_REQUEST_TIMEOUT_IN_SEC), Duration.ofSeconds(DEFAULT_CONTROL_PLANE_REQUEST_TIMEOUT_IN_SEC)); } /** * Create SimpleWorkflowClientConfig with polling/dataPlane/controlPlane timeouts * * @param pollingRequestTimeout timeout for polling APIs like PollForActivityTask, PollForDecisionTask * @param dataPlaneRequestTimeout timeout for dataPlane APIs like StartWorkflowExecution, RespondActivityTaskCompleted * @param controlPlaneRequestTimeout timeout for controlPlane APIs like ListDomains, ListActivityTypes */ public SimpleWorkflowClientConfig(Duration pollingRequestTimeout, Duration dataPlaneRequestTimeout, Duration controlPlaneRequestTimeout) { this.pollingRequestTimeout = pollingRequestTimeout; this.dataPlaneRequestTimeout = dataPlaneRequestTimeout; this.controlPlaneRequestTimeout = controlPlaneRequestTimeout; } public int getDataPlaneRequestTimeoutInMillis() { return (int) dataPlaneRequestTimeout.toMillis(); } public int getPollingRequestTimeoutInMillis() { return (int) pollingRequestTimeout.toMillis(); } public int getControlPlaneRequestTimeoutInMillis() { return (int) controlPlaneRequestTimeout.toMillis(); } }
3,559
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/junit/GenericWorkflowTest.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.junit; import com.amazonaws.services.simpleworkflow.flow.generic.ActivityImplementationFactory; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactoryFactory; import com.amazonaws.services.simpleworkflow.flow.test.TestDecisionContext; import com.amazonaws.services.simpleworkflow.flow.test.TestGenericActivityClient; import com.amazonaws.services.simpleworkflow.flow.test.TestGenericWorkflowClient; import com.amazonaws.services.simpleworkflow.flow.test.TestLambdaFunctionClient; import com.amazonaws.services.simpleworkflow.flow.test.TestWorkflowClock; import com.amazonaws.services.simpleworkflow.flow.test.TestWorkflowContext; public class GenericWorkflowTest extends WorkflowTestBase { private TestGenericActivityClient activityClient; public GenericWorkflowTest(WorkflowDefinitionFactoryFactory factoryFactory) { super(new TestDecisionContext(new TestGenericActivityClient(), new TestGenericWorkflowClient(factoryFactory), new TestWorkflowClock(), new TestWorkflowContext(), new TestLambdaFunctionClient())); activityClient = (TestGenericActivityClient) decisionContext.getActivityClient(); } public void addFactory(String taskListToListen, ActivityImplementationFactory factory) { activityClient.addFactory(taskListToListen, factory); } public void addFactory(ActivityImplementationFactory factory) { addFactory(defaultActivitiesTaskListToPoll, factory); } }
3,560
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/junit/AsyncAssert.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.junit; import org.junit.Assert; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Task; /** * Similar to {@link Assert} which waits on {@link Promise} argument before * calling correspondent Assert... function. * <p> * To avoid overload conflicts "WaitFor" postfix is used for methods that define * varargs "waitFor" argument. * <p> * For example when <code>AsyncAssert.assertEquals("expected", "expected", * waitForMe)</code> is called Java resolves it to * <code>void assertEquals(final String message, final Object expected, final Promise&lt;?&gt; actual)</code> * when * <code>void assertEquals(final Object expected, final Object actual, Promise&lt;?&gt;... waitFor)</code> * was assumed. * * * @see Assert */ public class AsyncAssert { protected AsyncAssert() { } static public void assertReady(String message, Promise<?> condition) { Assert.assertTrue(message, condition.isReady()); } static public void assertReady(Promise<?> condition) { Assert.assertTrue(condition.isReady()); } static public void assertNotReady(String message, Promise<?> condition) { Assert.assertFalse(message, condition.isReady()); } static public void assertNotReady(Promise<?> condition) { Assert.assertFalse(condition.isReady()); } static public void assertTrueWaitFor(final String message, final boolean condition, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertTrue(message, condition); } }; } static public void assertTrue(final String message, final Promise<Boolean> condition) { new Task(condition) { @Override protected void doExecute() throws Throwable { Assert.assertTrue(message, condition.get()); } }; } static public void assertTrueWaitFor(final boolean condition, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertTrue(condition); } }; } static public void assertTrue(final Promise<Boolean> condition) { new Task(condition) { @Override protected void doExecute() throws Throwable { Assert.assertTrue(condition.get()); } }; } static public void assertFalseWaitFor(final String message, final boolean condition, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertFalse(message, condition); } }; } static public void assertFalse(final String message, final Promise<Boolean> condition) { new Task(condition) { @Override protected void doExecute() throws Throwable { Assert.assertFalse(message, condition.get()); } }; } static public void assertFalseWaitFor(final boolean condition, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertFalse(condition); } }; } static public void assertFalse(final Promise<Boolean> condition) { new Task(condition) { @Override protected void doExecute() throws Throwable { Assert.assertFalse(condition.get()); } }; } static public void assertEquals(final String message, final Object expected, final Promise<?> actual) { new Task(actual) { @Override protected void doExecute() throws Throwable { Assert.assertEquals(message, expected, actual.get()); } }; } static public void assertEqualsWaitFor(final String message, final Object expected, final Object actual, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertEquals(message, expected, actual); } }; } static public void assertEquals(final Object expected, final Promise<?> actual) { new Task(actual) { @Override protected void doExecute() throws Throwable { Assert.assertEquals(expected, actual.get()); } }; } static public void assertEqualsWaitFor(final Object expected, final Object actual, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertEquals(expected, actual); } }; } public static void assertArrayEquals(final String message, final Object[] expected, final Object[] actual, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertArrayEquals(message, expected, actual); } }; } public static void assertArrayEquals(final String message, final Object[] expected, final Promise<Object[]> actual) { new Task(actual) { @Override protected void doExecute() throws Throwable { Assert.assertArrayEquals(message, expected, actual.get()); } }; } public static void assertArrayEqualsWaitFor(final Object[] expected, final Object[] actual, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertArrayEquals(expected, actual); } }; } public static void assertArrayEquals(final Object[] expected, final Promise<Object[]> actual) { new Task(actual) { @Override protected void doExecute() throws Throwable { Assert.assertArrayEquals(expected, actual.get()); } }; } static public void assertEqualsWaitFor(final String message, final double expected, final double actual, final double delta, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertEquals(message, expected, actual, delta); } }; } static public void assertEquals(final String message, final double expected, final Promise<Double> actual, final double delta) { new Task(actual) { @Override protected void doExecute() throws Throwable { Assert.assertEquals(message, expected, actual.get(), delta); } }; } static public void assertEqualsWaitFor(final double expected, final double actual, final double delta, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertEquals(expected, actual, delta); } }; } static public void assertEquals(final double expected, final Promise<Double> actual, final double delta) { new Task(actual) { @Override protected void doExecute() throws Throwable { Assert.assertEquals(expected, actual.get(), delta); } }; } static public void assertNotNullWaitFor(final String message, final Object object, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertNotNull(message, object); } }; } /** * Asserts that an object Promise and its content isn't null. If it is an * {@link AssertionError} is thrown with the given message. * * @param message * the identifying message for the {@link AssertionError} ( * <code>null</code> okay) * @param object * Object to check or <code>null</code> */ static public void assertNotNull(final String message, final Promise<Object> object) { Assert.assertNotNull(message, object); new Task(object) { @Override protected void doExecute() throws Throwable { Assert.assertNotNull(message, object.get()); } }; } static public void assertNotNullWaitFor(final Object object, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertNotNull(object); } }; } /** * Asserts that an object its content isn't null. */ static public void assertNotNull(final Promise<Object> object) { Assert.assertNotNull(object); new Task(object) { @Override protected void doExecute() throws Throwable { Assert.assertNotNull(object.get()); } }; } static public void assertNullWaitFor(final String message, final Object object, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertNull(message, object); } }; } /** * Asserts that an object is not <code>null</code> while * <code>object.get()</code> is <code>null</code>. */ static public void assertNull(final String message, final Promise<Object> object) { Assert.assertNotNull(object); new Task(object) { @Override protected void doExecute() throws Throwable { Assert.assertNull(message, object.get()); } }; } static public void assertNullWaitFor(final Object object, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertNull(object); } }; } /** * Asserts that an object is not <code>null</code> while * <code>object.get()</code> is <code>null</code>. */ static public void assertNull(final Promise<Object> object) { Assert.assertNotNull(object); new Task(object) { @Override protected void doExecute() throws Throwable { Assert.assertNull(object.get()); } }; } static public void assertSameWaitFor(final String message, final Object expected, final Object actual, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertSame(message, expected, actual); } }; } /** * Asserts that two Promises content refer to the same object. If they are * not, an {@link AssertionError} is thrown with the given message. */ static public void assertSame(final String message, final Object expected, final Promise<Object> actual) { new Task(actual) { @Override protected void doExecute() throws Throwable { Assert.assertSame(message, expected, actual.get()); } }; } static public void assertSameWaitFor(final Object expected, final Object actual, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertSame(expected, actual); } }; } /** * Asserts that two Promises content refer to the same object. If they are * not, an {@link AssertionError} is thrown with the given message. */ static public void assertSame(final Object expected, final Promise<Object> actual) { new Task(actual) { @Override protected void doExecute() throws Throwable { Assert.assertSame(expected, actual.get()); } }; } static public void assertNotSameWaitFor(final String message, final Object expected, final Object actual, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertNotSame(message, expected, actual); } }; } /** * Asserts that two Promises content do not refer to the same object. If * they are an {@link AssertionError} is thrown with the given message. */ static public void assertNotSame(final String message, final Object expected, final Promise<Object> actual) { new Task(actual) { @Override protected void doExecute() throws Throwable { Assert.assertNotSame(message, expected, actual.get()); } }; } static public void assertNotSameWaitFor(final Object expected, final Object actual, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { Assert.assertNotSame(expected, actual); } }; } /** * Asserts that two Promises content do not refer to the same object. If * they are an {@link AssertionError} is thrown with the given message. */ static public void assertNotSame(final Object expected, final Promise<Object> actual) { new Task(actual) { @Override protected void doExecute() throws Throwable { Assert.assertNotSame(expected, actual.get()); } }; } }
3,561
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/junit/WorkflowTest.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.junit; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import com.amazonaws.services.simpleworkflow.flow.JsonDataConverter; import com.amazonaws.services.simpleworkflow.flow.test.TestDecisionContext; import com.amazonaws.services.simpleworkflow.flow.test.TestLambdaFunctionClient; import com.amazonaws.services.simpleworkflow.flow.test.TestLambdaFunctionInvoker; import com.amazonaws.services.simpleworkflow.flow.test.TestPOJOActivityImplementationGenericActivityClient; import com.amazonaws.services.simpleworkflow.flow.test.TestPOJOActivityImplementationWorker; import com.amazonaws.services.simpleworkflow.flow.test.TestPOJOWorkflowImplementationGenericWorkflowClient; import com.amazonaws.services.simpleworkflow.flow.test.TestWorkflowClock; import com.amazonaws.services.simpleworkflow.flow.test.TestWorkflowContext; /** * JUnit Rule that should be present as a public field of the test class * annotated with @Rule. Requires that test is executed with * {@link FlowBlockJUnit4ClassRunner}. * @author fateev */ public class WorkflowTest extends WorkflowTestBase { private TestPOJOActivityImplementationGenericActivityClient activityClient; private TestPOJOWorkflowImplementationGenericWorkflowClient workflowClient; private TestLambdaFunctionClient lambdaFunctionClient; private Map<String, TestPOJOActivityImplementationWorker> workers = new HashMap<String, TestPOJOActivityImplementationWorker>(); public WorkflowTest() { super(new TestDecisionContext(new TestPOJOActivityImplementationGenericActivityClient(), new TestPOJOWorkflowImplementationGenericWorkflowClient(), new TestWorkflowClock(), new TestWorkflowContext(), new TestLambdaFunctionClient())); activityClient = (TestPOJOActivityImplementationGenericActivityClient) decisionContext.getActivityClient(); workflowClient = (TestPOJOWorkflowImplementationGenericWorkflowClient) decisionContext.getWorkflowClient(); lambdaFunctionClient = (TestLambdaFunctionClient) decisionContext.getLambdaFunctionClient(); } public void addActivitiesImplementation(Object activitiesImplementation) { addActivitiesImplementation(defaultActivitiesTaskListToPoll, activitiesImplementation); } public void addActivitiesImplementation(String taskList, Object activitiesImplementation) { try { TestPOJOActivityImplementationWorker worker = getActivityWorker(taskList); worker.addActivitiesImplementation(activitiesImplementation); activityClient.addWorker(worker); } catch (Exception e) { throw new IllegalArgumentException("Invalid activities implementation: " + activitiesImplementation, e); } } private TestPOJOActivityImplementationWorker getActivityWorker(String taskList) { TestPOJOActivityImplementationWorker result = workers.get(taskList); if (result == null) { result = new TestPOJOActivityImplementationWorker(taskList); workers.put(taskList, result); } return result; } public void addWorkflowImplementationType(Class<?> workflowImplementationType) { addWorkflowImplementationType(workflowImplementationType, null); } public void addWorkflowImplementationType(Class<?> workflowImplementationType, Object[] constructorArgs) { try { workflowClient.addWorkflowImplementationType(workflowImplementationType, null /* use annotation specified or default */, constructorArgs, null); } catch (Exception e) { throw new IllegalArgumentException("Invalid workflow type: " + workflowImplementationType, e); } } public void setActivitiesImplementations(Iterable<Object> activitiesImplementationObjects) { workers.clear(); addActivitiesImplementations(defaultActivitiesTaskListToPoll, activitiesImplementationObjects); } public void setTaskListActivitiesImplementationMap(Map<String, Object> map) { workers.clear(); for (Entry<String, Object> taskImplPair : map.entrySet()) { addActivitiesImplementation(taskImplPair.getKey(), taskImplPair.getValue()); } } public Map<String, Object> getTaskListActivitiesImplementationMap() { Map<String, Object> result = new HashMap<String, Object>(); for (Entry<String, TestPOJOActivityImplementationWorker> pair : workers.entrySet()) { Iterable<Object> implementations = pair.getValue().getActivitiesImplementations(); for (Object impelementation : implementations) { result.put(pair.getKey(), impelementation); } } return result; } public void addActivitiesImplementations(String taskList, Iterable<Object> activityImplementationObjects) { try { TestPOJOActivityImplementationWorker worker = getActivityWorker(taskList); worker.addActivitiesImplementations(activityImplementationObjects); activityClient.addWorker(worker); } catch (Exception e) { throw new IllegalArgumentException("Invalid activities implementation: " + activityImplementationObjects, e); } } public Iterable<Object> getActivitiesImplementations() { TestPOJOActivityImplementationWorker worker = getActivityWorker(defaultActivitiesTaskListToPoll); return worker.getActivitiesImplementations(); } public void setWorkflowImplementationTypes(Collection<Class<?>> workflowImplementationTypes) throws InstantiationException, IllegalAccessException { workflowClient.setWorkflowImplementationTypes(workflowImplementationTypes); } public void setTestLambdaFunctionInvoker(TestLambdaFunctionInvoker testLambdaFunctionInvoker) { lambdaFunctionClient.setInvoker(testLambdaFunctionInvoker); } }
3,562
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/junit/WorkflowTestBase.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.junit; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import org.junit.rules.MethodRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.core.AsyncScope; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.core.Task; import com.amazonaws.services.simpleworkflow.flow.junit.spring.FlowSpringJUnit4ClassRunner; import com.amazonaws.services.simpleworkflow.flow.test.TestWorkflowClock; import com.amazonaws.services.simpleworkflow.flow.test.TestWorkflowContext; import com.amazonaws.services.simpleworkflow.flow.worker.CurrentDecisionContext; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; import com.amazonaws.services.simpleworkflow.model.WorkflowType; public abstract class WorkflowTestBase implements MethodRule { protected String defaultActivitiesTaskListToPoll = "TestTaskList"; boolean disableOutstandingTasksCheck; protected DecisionContext decisionContext; protected TestWorkflowContext workflowContext; protected TestWorkflowClock workflowClock; AsyncScope scope; List<Settable<Void>> waits = new ArrayList<Settable<Void>>(); double clockAcceleration = 1.0; boolean flowTestRunner; private long testTimeoutActualTimeMilliseconds; private WorkflowTestStatement workflowTestStatement; private Class<? extends Throwable> expectedException; public WorkflowTestBase(DecisionContext decisionContext) { this.decisionContext = decisionContext; workflowContext = (TestWorkflowContext) decisionContext.getWorkflowContext(); workflowClock = (TestWorkflowClock) decisionContext.getWorkflowClock(); WorkflowExecution we = new WorkflowExecution(); we.setWorkflowId("testWorkflowId"); we.setRunId("testRunId"); workflowContext.setWorkflowExecution(we); WorkflowType wt = new WorkflowType(); wt.setName("testWorkflow"); wt.setVersion("0.0"); workflowContext.setWorkflowType(wt); } public boolean isDisableOutstandingTasksCheck() { return disableOutstandingTasksCheck; } /** * When set to <code>true</code> it is considered a test failure to have * outstanding tasks that are blocked on non external events or timers. Such * blockage is usually indicates a bug that can lead to a workflow * "getting stuck". Default is <code>true</code>. */ public void setDisableOutstandingTasksCheck(boolean disableOutstandingTasksCheck) { this.disableOutstandingTasksCheck = disableOutstandingTasksCheck; } public DecisionContext getDecisionContext() { return decisionContext; } public void setWorkflowExecution(WorkflowExecution workflowExecution) { workflowContext.setWorkflowExecution(workflowExecution); } public void setWorkflowType(WorkflowType workflowType) { workflowContext.setWorkflowType(workflowType); } public WorkflowExecution getWorkflowExecution() { return workflowContext.getWorkflowExecution(); } public WorkflowType getWorkflowType() { return workflowContext.getWorkflowType(); } public String getDefaultActivitiesTaskListToPoll() { return defaultActivitiesTaskListToPoll; } public void setDefaultActivitiesTaskListToPoll(String defaultActivitiesTaskListToPoll) { this.defaultActivitiesTaskListToPoll = defaultActivitiesTaskListToPoll; } public double getClockAcceleration() { return clockAcceleration; } /** * Accelerate workflow clock according the coefficient. Note that the clock * acceleration affects time returned by {@link WorkflowClock} and timers * firing only. The default is 1.0 (no acceleration). * * @param clockAcceleration * value that is larger then 1.0 */ public void setClockAccelerationCoefficient(double clockAcceleration) { if (clockAcceleration < 1.0) { throw new IllegalArgumentException("clock acceleration less then 1: " + clockAcceleration); } this.clockAcceleration = clockAcceleration; } @Override public Statement apply(final Statement base, FrameworkMethod method, Object target) { Callable<WorkflowTestBase> accessor = new Callable<WorkflowTestBase>() { @Override public WorkflowTestBase call() throws Exception { return WorkflowTestBase.this; } }; workflowTestStatement = new WorkflowTestStatement(accessor, base, testTimeoutActualTimeMilliseconds, expectedException); workflowTestStatement.setFlowTestRunner(flowTestRunner); return workflowTestStatement; } /** * Here blocked means that there are no any tasks that are ready to be * executed. Usually these tasks wait for timers or some other external * events. * * @return Promise that becomes ready when there are not tasks to execute */ public Promise<Void> waitBlocked(Promise<?>... waitFor) { if (scope == null) { throw new IllegalArgumentException("Called outside of test method"); } final Settable<Void> result = new Settable<Void>(); new Task(waitFor) { @Override protected void doExecute() throws Throwable { waits.add(result); } }; return result; } public void setClockCurrentTimeMillis(long timeMillis) { workflowClock.setCurrentTimeMillis(timeMillis); } public void clockAdvanceSeconds(final long seconds) { workflowClock.advanceSeconds(seconds); } public void clockAdvanceSeconds(final long seconds, Promise<?>... waitFor) { new Task(waitFor) { @Override protected void doExecute() throws Throwable { workflowClock.advanceSeconds(seconds); } }; } protected void beforeEvaluate(DecisionContext decisionContext) { CurrentDecisionContext.set(decisionContext); } protected void afterEvaluate() { CurrentDecisionContext.unset(); } /** * Test timeout time. Uses real clock that ignores acceleration (see * {@link #setClockAccelerationCoefficient(double)}). Instead of calling * this method consider using {@link FlowBlockJUnit4ClassRunner} or * {@link FlowSpringJUnit4ClassRunner} and timeout parameter of @Test * annotation. * * @param timeout * time in milliseconds. */ public void setTestTimeoutActualTimeMilliseconds(long timeout) { this.testTimeoutActualTimeMilliseconds = timeout; if (workflowTestStatement != null) { workflowTestStatement.setTestTimeoutActualTimeMilliseconds(timeout); } } public void setExpectedException(Class<? extends Throwable> expectedException) { this.expectedException = expectedException; if (workflowTestStatement != null) { workflowTestStatement.setExpectedException(expectedException); } } public void setFlowTestRunner(boolean flowTestRunner) { this.flowTestRunner = flowTestRunner; if (workflowTestStatement != null) { workflowTestStatement.setFlowTestRunner(flowTestRunner); } } }
3,563
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/junit/WorkflowTestStatement.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.junit; import java.util.concurrent.Callable; import org.junit.runners.model.Statement; import com.amazonaws.services.simpleworkflow.flow.core.AsyncScope; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally; public class WorkflowTestStatement extends Statement { private final Callable<WorkflowTestBase> workflowTestAccessor; private final Statement base; private Long timeout; boolean completed; private Throwable failure; boolean waitingOnTimer; private Class<? extends Throwable> expectedException; private boolean flowTestRunner; public WorkflowTestStatement(Callable<WorkflowTestBase> workflowTestAccessor, Statement base, Long timeout, Class<? extends Throwable> expectedException) { this.workflowTestAccessor = workflowTestAccessor; this.base = base; this.timeout = timeout; this.expectedException = expectedException; } @Override public void evaluate() throws Throwable { if (!flowTestRunner) { throw new IllegalStateException( "WorkflowTest rule can be used only with flow specific test runners: FlowBlockJUnit4ClassRunner and FlowSpringJUnit4ClassRunner"); } final WorkflowTestBase workflowTest = workflowTestAccessor.call(); Thread t = null; if (timeout == null || timeout == 0) { try { asyncEvaluate(workflowTest); completed = true; } catch (Throwable e) { failure = e; } } else { t = new Thread() { public void run() { try { asyncEvaluate(workflowTest); completed = true; } catch (Throwable e) { failure = e; } } }; t.start(); t.join(timeout); } if (failure != null) { if (expectedException != null && expectedException.isAssignableFrom(failure.getClass())) { return; } throw failure; } if (!completed) { if (waitingOnTimer) { AssertionError e = new AssertionError("Test timed out after " + timeout + " milliseconds. The following asynchrous tasks are outstanding: \n" + workflowTest.scope.getAsynchronousThreadDumpAsString()); throw e; } else { AssertionError e = new AssertionError("Test timed out after " + timeout + " milliseconds"); if (t != null) { e.setStackTrace(t.getStackTrace()); } throw e; } } if (expectedException != null) { throw new AssertionError("Expected exception: " + expectedException); } } private void asyncEvaluate(final WorkflowTestBase workflowTest) throws Throwable, InterruptedException { try { workflowTest.scope = new AsyncScope() { @Override protected void doAsync() throws Throwable { new TryCatchFinally() { @Override protected void doTry() throws Throwable { workflowTest.beforeEvaluate(workflowTest.decisionContext); base.evaluate(); } @Override protected void doCatch(Throwable e) throws Throwable { if (e instanceof IllegalStateException) { if ("Called outside of the workflow definition code.".equals(e.getMessage())) { throw new RuntimeException( "Possible use of \"timeout\" parameter of @Test annotation without using Flow JUnit runner. " + "Supported runners are FlowBlockJUnit4ClassRunner and FlowSpringJUnit4ClassRunner.", e); } } throw e; } @Override protected void doFinally() throws Throwable { workflowTest.afterEvaluate(); } }; } }; boolean outstandingTasks = false; while (!workflowTest.scope.isComplete()) { outstandingTasks = workflowTest.scope.eventLoop(); if (workflowTest.waits.size() == 0) { Long toNextTimerDelay = workflowTest.workflowClock.fireTimers(); if (toNextTimerDelay == null) { break; } long timeToSleep = (long) (toNextTimerDelay / workflowTest.clockAcceleration); if (timeToSleep > 5) { waitingOnTimer = true; try { // If you are using @Test(timeout=...) annotation and your test timed out // pointing to the Thread.sleep that follows this comment consider // changing test runner to FlowBlockJUnit4ClassRunner or // FlowSpringJUnit4ClassRunner to enable asynchronous thread dump. Thread.sleep(timeToSleep); } finally { waitingOnTimer = false; } } if (!workflowTest.scope.isComplete()) { workflowTest.workflowClock.advanceMilliseconds(toNextTimerDelay); } continue; } for (Settable<Void> listener : workflowTest.waits) { listener.set(null); } workflowTest.waits.clear(); } if (!workflowTest.disableOutstandingTasksCheck && !outstandingTasks) { throw new IllegalStateException("There are outstanding tasks after test completed execution: \n" + workflowTest.scope.getAsynchronousThreadDumpAsString()); } } finally { workflowTest.afterEvaluate(); } } public void setTestTimeoutActualTimeMilliseconds(long timeout) { if (timeout > 0) { this.timeout = timeout; } } public void setExpectedException(Class<? extends Throwable> expectedException) { this.expectedException = expectedException; } public void setFlowTestRunner(boolean flowTestRunner) { this.flowTestRunner = flowTestRunner; } }
3,564
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/junit/FlowBlockJUnit4ClassRunner.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.junit; import java.util.List; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; /** * To be used instead of {@link BlockJUnit4ClassRunner} when testing * asynchronous code. Requires {@link WorkflowTest} rule (annotated with @Rule) * to be present in the tested class. * * @author fateev */ public class FlowBlockJUnit4ClassRunner extends BlockJUnit4ClassRunner { private WorkflowTestBase workflowTestRule; private long timeout; private Class<? extends Throwable> expectedException; public FlowBlockJUnit4ClassRunner(Class<?> klass) throws InitializationError { super(klass); } @Override protected Statement withPotentialTimeout(FrameworkMethod method, final Object test, Statement next) { Test annotation = method.getAnnotation(Test.class); timeout = annotation.timeout(); if (timeout > 0 && workflowTestRule != null) { workflowTestRule.setTestTimeoutActualTimeMilliseconds(timeout); } return next; } @Override protected List<MethodRule> rules(Object test) { List<MethodRule> result = super.rules(test); for (MethodRule methodRule : result) { if (WorkflowTestBase.class.isAssignableFrom(methodRule.getClass())) { workflowTestRule = (WorkflowTestBase) methodRule; workflowTestRule.setFlowTestRunner(true); if (timeout > 0) { workflowTestRule.setTestTimeoutActualTimeMilliseconds(timeout); } workflowTestRule.setExpectedException(expectedException); } } return result; } @Override protected Statement possiblyExpectingExceptions(FrameworkMethod method, Object test, Statement next) { Test annotation = method.getAnnotation(Test.class); Class<? extends Throwable> expected = annotation.expected(); if (expected == Test.None.class) { expectedException = null; } else { expectedException = expected; } if (workflowTestRule != null) { workflowTestRule.setExpectedException(expectedException); } return next; } }
3,565
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/junit
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/junit/spring/FlowSpringJUnit4ClassRunner.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.junit.spring; import java.util.List; import org.junit.Test; import org.junit.rules.MethodRule; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; import org.junit.runners.model.Statement; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.amazonaws.services.simpleworkflow.flow.junit.WorkflowTestBase; /** * To be used instead of {@link SpringJUnit4ClassRunner} when testing * asynchronous code. Requires {@link SpringWorkflowTest} rule (annotated with @Rule) * to be present in the tested class. * * @author fateev */ public class FlowSpringJUnit4ClassRunner extends SpringJUnit4ClassRunner { private WorkflowTestBase workflowTestRule; private long timeout; private Class<? extends Throwable> expectedException; public FlowSpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError { super(clazz); } @Override protected Statement withPotentialTimeout(final FrameworkMethod method, final Object test, Statement next) { Test annotation = method.getAnnotation(Test.class); long timeout = annotation.timeout(); if (timeout > 0) { long springTimeout = getSpringTimeout(method); if (workflowTestRule != null && springTimeout == 0) { workflowTestRule.setTestTimeoutActualTimeMilliseconds(timeout); } } return next; } @Override protected List<MethodRule> rules(Object test) { List<MethodRule> result = super.rules(test); for (MethodRule methodRule : result) { if (WorkflowTestBase.class.isAssignableFrom(methodRule.getClass())) { workflowTestRule = (WorkflowTestBase) methodRule; workflowTestRule.setFlowTestRunner(true); if (timeout > 0) { workflowTestRule.setTestTimeoutActualTimeMilliseconds(timeout); } if (expectedException != null) { workflowTestRule.setExpectedException(expectedException); } } } return result; } @Override protected Statement possiblyExpectingExceptions(FrameworkMethod method, Object test, Statement next) { Test annotation = method.getAnnotation(Test.class); Class<? extends Throwable> expected = annotation.expected(); if (expected != Test.None.class) { expectedException = expected; if (workflowTestRule != null) { workflowTestRule.setExpectedException(expectedException); } } return next; } }
3,566
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/junit
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/junit/spring/SpringWorkflowTest.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.junit.spring; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.junit.WorkflowTestBase; import com.amazonaws.services.simpleworkflow.flow.spring.WorkflowScope; import com.amazonaws.services.simpleworkflow.flow.test.TestDecisionContext; import com.amazonaws.services.simpleworkflow.flow.test.TestLambdaFunctionClient; import com.amazonaws.services.simpleworkflow.flow.test.TestPOJOActivityImplementationGenericActivityClient; import com.amazonaws.services.simpleworkflow.flow.test.TestPOJOActivityImplementationWorker; import com.amazonaws.services.simpleworkflow.flow.test.TestWorkflowClock; import com.amazonaws.services.simpleworkflow.flow.test.TestWorkflowContext; import com.amazonaws.services.simpleworkflow.model.WorkflowType; /** * JUnit Rule that should be present as a public field of the test class * annotated with @Rule. Requires that test is executed with * {@link FlowSpringJUnit4ClassRunner}. * */ public class SpringWorkflowTest extends WorkflowTestBase { private TestPOJOActivityImplementationGenericActivityClient activityClient; private SpringTestPOJOWorkflowImplementationGenericWorkflowClient workflowClient; private Map<String, TestPOJOActivityImplementationWorker> workers = new HashMap<String, TestPOJOActivityImplementationWorker>(); private DataConverter dataConverter; public SpringWorkflowTest() { super(new TestDecisionContext(new TestPOJOActivityImplementationGenericActivityClient(), new SpringTestPOJOWorkflowImplementationGenericWorkflowClient(), new TestWorkflowClock(), new TestWorkflowContext(), new TestLambdaFunctionClient())); activityClient = (TestPOJOActivityImplementationGenericActivityClient) decisionContext.getActivityClient(); workflowClient = (SpringTestPOJOWorkflowImplementationGenericWorkflowClient) decisionContext.getWorkflowClient(); } public void addActivitiesImplementation(Object activitiesImplementation) { addActivitiesImplementation(defaultActivitiesTaskListToPoll, activitiesImplementation); } public void addActivitiesImplementation(String taskList, Object activitiesImplementation) { try { TestPOJOActivityImplementationWorker worker = getActivityWorker(taskList); worker.addActivitiesImplementation(activitiesImplementation); activityClient.addWorker(worker); } catch (Exception e) { throw new IllegalArgumentException("Invalid activities implementation: " + activitiesImplementation, e); } } private TestPOJOActivityImplementationWorker getActivityWorker(String taskList) { TestPOJOActivityImplementationWorker result = workers.get(taskList); if (result == null) { result = new TestPOJOActivityImplementationWorker(taskList); if (dataConverter != null) { result.setDataConverter(dataConverter); } workers.put(taskList, result); } return result; } public void setActivitiesImplementations(Iterable<Object> activityImplementationObjects) { workers.clear(); addActivitiesImplementations(defaultActivitiesTaskListToPoll, activityImplementationObjects); } public void addActivitiesImplementations(String taskList, Iterable<Object> activityImplementationObjects) { try { TestPOJOActivityImplementationWorker worker = getActivityWorker(taskList); worker.setActivitiesImplementations(activityImplementationObjects); activityClient.addWorker(worker); } catch (Exception e) { throw new IllegalArgumentException("Invalid activities implementation: " + activityImplementationObjects, e); } } public void setTaskListActivitiesImplementationMap(Map<String, Object> map) { workers.clear(); for (Entry<String, Object> taskImplPair: map.entrySet()) { addActivitiesImplementation(taskImplPair.getKey(), taskImplPair.getValue()); } } public Map<String, Object> getTaskListActivitiesImplementationMap() { Map<String, Object> result = new HashMap<String, Object>(); for (Entry<String, TestPOJOActivityImplementationWorker> pair: workers.entrySet()) { Iterable<Object> implementations = pair.getValue().getActivitiesImplementations(); for (Object impelementation : implementations) { result.put(pair.getKey(), impelementation); } } return result; } public Iterable<Object> getActivitiesImplementations() { TestPOJOActivityImplementationWorker worker = getActivityWorker(defaultActivitiesTaskListToPoll); return worker.getActivitiesImplementations(); } public void setWorkflowImplementations(Iterable<Object> workflowImplementations) throws InstantiationException, IllegalAccessException { workflowClient.setWorkflowImplementations(workflowImplementations); } public Iterable<Object> getWorkflowImplementations() { return workflowClient.getWorkflowImplementations(); } public void addWorkflowImplementation(Object workflowImplementation) throws InstantiationException, IllegalAccessException { workflowClient.addWorkflowImplementation(workflowImplementation); } public DataConverter getDataConverter() { return dataConverter; } public void setDataConverter(DataConverter converter) { dataConverter = converter; workflowClient.setDataConverter(converter); } public Iterable<WorkflowType> getWorkflowTypesToRegister() { return workflowClient.getWorkflowTypesToRegister(); } @Override protected void beforeEvaluate(DecisionContext decisionContext) { WorkflowScope.setDecisionContext(decisionContext); } @Override protected void afterEvaluate() { } }
3,567
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/junit
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/junit/spring/SpringTestPOJOWorkflowImplementationGenericWorkflowClient.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.junit.spring; import java.util.HashMap; import java.util.Map; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProvider; import com.amazonaws.services.simpleworkflow.flow.WorkflowException; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.generic.ContinueAsNewWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClient; import com.amazonaws.services.simpleworkflow.flow.generic.SignalExternalWorkflowParameters; import com.amazonaws.services.simpleworkflow.flow.generic.StartChildWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.flow.generic.StartChildWorkflowReply; import com.amazonaws.services.simpleworkflow.flow.pojo.POJOWorkflowDefinitionFactoryFactory; import com.amazonaws.services.simpleworkflow.flow.pojo.POJOWorkflowImplementationFactory; import com.amazonaws.services.simpleworkflow.flow.spring.POJOWorkflowStubImplementationFactory; import com.amazonaws.services.simpleworkflow.flow.test.TestGenericWorkflowClient; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; import com.amazonaws.services.simpleworkflow.model.WorkflowType; public class SpringTestPOJOWorkflowImplementationGenericWorkflowClient implements GenericWorkflowClient { private final TestGenericWorkflowClient genericClient; public SpringTestPOJOWorkflowImplementationGenericWorkflowClient() { genericClient = new TestGenericWorkflowClient(); genericClient.setFactoryFactory(new POJOWorkflowDefinitionFactoryFactory() { @Override protected POJOWorkflowImplementationFactory getImplementationFactory(Class<?> workflowImplementationType, Class<?> workflowInteface, WorkflowType workflowType) { final Object instanceProxy = workflowImplementations.get(workflowImplementationType); if (instanceProxy == null) { throw new IllegalArgumentException("unknown workflowImplementationType: " + workflowImplementationType); } return new POJOWorkflowStubImplementationFactory(instanceProxy); } }); } private final Map<Class<?>, Object> workflowImplementations = new HashMap<Class<?>, Object>(); public void setWorkflowImplementations(Iterable<Object> workflowImplementations) throws InstantiationException, IllegalAccessException { for (Object workflowImplementation : workflowImplementations) { addWorkflowImplementation(workflowImplementation); } } public Iterable<Object> getWorkflowImplementations() { return workflowImplementations.values(); } public void addWorkflowImplementation(Object workflowImplementation) throws InstantiationException, IllegalAccessException { Class<? extends Object> implementationClass = workflowImplementation.getClass(); workflowImplementations.put(implementationClass, workflowImplementation); getFactoryFactory().addWorkflowImplementationType(implementationClass); } private POJOWorkflowDefinitionFactoryFactory getFactoryFactory() { return ((POJOWorkflowDefinitionFactoryFactory)genericClient.getFactoryFactory()); } public DecisionContextProvider getDecisionContextProvider() { return genericClient.getDecisionContextProvider(); } public void setDecisionContextProvider(DecisionContextProvider decisionContextProvider) { genericClient.setDecisionContextProvider(decisionContextProvider); } public Promise<StartChildWorkflowReply> startChildWorkflow(StartChildWorkflowExecutionParameters parameters) { return genericClient.startChildWorkflow(parameters); } public Promise<String> startChildWorkflow(String workflow, String version, String input) { return genericClient.startChildWorkflow(workflow, version, input); } public Promise<String> startChildWorkflow(String workflow, String version, Promise<String> input) { return genericClient.startChildWorkflow(workflow, version, input); } public Promise<Void> signalWorkflowExecution(SignalExternalWorkflowParameters signalParameters) { return genericClient.signalWorkflowExecution(signalParameters); } public void requestCancelWorkflowExecution(WorkflowExecution execution) { genericClient.requestCancelWorkflowExecution(execution); } public String getWorkflowState(WorkflowExecution execution) throws WorkflowException { return genericClient.getWorkflowState(execution); } public void continueAsNewOnCompletion(ContinueAsNewWorkflowExecutionParameters parameters) { genericClient.continueAsNewOnCompletion(parameters); } public String generateUniqueId() { return genericClient.generateUniqueId(); } public DataConverter getDataConverter() { return getFactoryFactory().getDataConverter(); } public void setDataConverter(DataConverter converter) { getFactoryFactory().setDataConverter(converter); } public Iterable<WorkflowType> getWorkflowTypesToRegister() { return getFactoryFactory().getWorkflowTypesToRegister(); } }
3,568
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/replaydeserializer/TimestampDeserializer.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.replaydeserializer; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import java.io.IOException; import java.util.Date; public class TimestampDeserializer extends StdDeserializer<Date> { public TimestampDeserializer() { super(Date.class); } @Override public Date deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException { double milliseconds = Double.valueOf(jp.getText()); long timeInMillis = (long) (milliseconds * 1000); return new Date(timeInMillis); } }
3,569
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/replaydeserializer/TimeStampMixin.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.replaydeserializer; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.util.Date; public class TimeStampMixin { @JsonDeserialize(using = TimestampDeserializer.class) Date eventTimestamp; }
3,570
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/aspectj/AsynchronousAspectTask.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.aspectj; import org.aspectj.lang.ProceedingJoinPoint; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.core.Task; class AsynchronousAspectTask extends Task { ProceedingJoinPoint pjp; @SuppressWarnings("rawtypes") Settable returnValue = new Settable(); @SuppressWarnings("rawtypes") public AsynchronousAspectTask(Boolean daemon, ProceedingJoinPoint pjp, Promise[] waitFor) { super(daemon, "_aroundBody", true, 7, waitFor); this.pjp = pjp; } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override protected void doExecute() throws Throwable { Object result = pjp.proceed(); if (result != null && !(result instanceof Promise)) { throw new RuntimeException("@Asynchronous annotation is allowed only for methods with void or Promise return types: " + pjp.getStaticPart().getSignature().getName()); } if (result != null) { returnValue.chain((Promise)result); } else { returnValue.set(null); } } @SuppressWarnings("rawtypes") public Promise getReturnValue() { return returnValue; } }
3,571
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/aspectj/ExponentialRetryAspect.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.aspectj; import java.util.Arrays; import java.util.TreeMap; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProvider; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProviderImpl; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.WorkflowContext; import com.amazonaws.services.simpleworkflow.flow.annotations.ExponentialRetry; import com.amazonaws.services.simpleworkflow.flow.annotations.ExponentialRetryUpdate; import com.amazonaws.services.simpleworkflow.flow.annotations.ExponentialRetryVersion; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.interceptors.AsyncExecutor; import com.amazonaws.services.simpleworkflow.flow.interceptors.AsyncRetryingExecutor; import com.amazonaws.services.simpleworkflow.flow.interceptors.AsyncRunnable; import com.amazonaws.services.simpleworkflow.flow.interceptors.ExponentialRetryPolicy; import com.amazonaws.services.simpleworkflow.flow.worker.IncompatibleWorkflowDefinition; /** * This class is for internal use only and may be changed or removed without * prior notice. */ @Aspect public class ExponentialRetryAspect { @SuppressWarnings({ "rawtypes", "unchecked" }) private final class DecoratorInvocationHandler implements AsyncRunnable { private final ProceedingJoinPoint pjp; private final Settable result; public DecoratorInvocationHandler(ProceedingJoinPoint pjp, Settable result) { this.pjp = pjp; this.result = result; } @Override public void run() throws Throwable { if (result != null) { result.unchain(); result.chain((Promise) pjp.proceed()); } else { pjp.proceed(); } } } private final DecisionContextProvider decisionContextProviderImpl = new DecisionContextProviderImpl(); @Around("execution(@com.amazonaws.services.simpleworkflow.flow.annotations.ExponentialRetryUpdate * *(..)) && @annotation(retryUpdateAnnotation)") public Object retry(final ProceedingJoinPoint pjp, ExponentialRetryUpdate retryUpdateAnnotation) throws Throwable { ExponentialRetryVersion[] versions = retryUpdateAnnotation.versions(); TreeMap<Integer, ExponentialRetry> retriesByVersion = new TreeMap<Integer, ExponentialRetry>(); for (ExponentialRetryVersion retryVersion : versions) { int internalVersion = retryVersion.implementationVersion(); ExponentialRetry previous = retriesByVersion.put(internalVersion, retryVersion.retry()); if (previous != null) { throw new IncompatibleWorkflowDefinition("More then one @ExponentialRetry annotation found for version " + internalVersion); } } DecisionContext decisionContext = decisionContextProviderImpl.getDecisionContext(); WorkflowContext workflowContext = decisionContext.getWorkflowContext(); String component = retryUpdateAnnotation.component(); // Checking isImplementationVersion from the largest version to the lowest one for (int internalVersion : retriesByVersion.descendingKeySet()) { ExponentialRetry retryAnnotation = retriesByVersion.get(internalVersion); if (workflowContext.isImplementationVersion(component, internalVersion)) { return retry(pjp, retryAnnotation); } } throw new IncompatibleWorkflowDefinition( "@ExponentialRetryUpdate doesn't include implementationVersion compatible with the workflow execution"); } @Around("execution(@com.amazonaws.services.simpleworkflow.flow.annotations.ExponentialRetry * *(..)) && @annotation(retryAnnotation)") public Object retry(final ProceedingJoinPoint pjp, ExponentialRetry retryAnnotation) throws Throwable { ExponentialRetryPolicy retryPolicy = createExponentialRetryPolicy(retryAnnotation); WorkflowClock clock = decisionContextProviderImpl.getDecisionContext().getWorkflowClock(); AsyncExecutor executor = new AsyncRetryingExecutor(retryPolicy, clock); Settable<?> result; if (isVoidReturnType(pjp)) { result = null; } else { result = new Settable<Object>(); } DecoratorInvocationHandler handler = new DecoratorInvocationHandler(pjp, result); executor.execute(handler); return result; } private boolean isVoidReturnType(final ProceedingJoinPoint pjp) { boolean isVoidReturnType = false; final Signature signature = pjp.getStaticPart().getSignature(); if (signature instanceof MethodSignature) { final MethodSignature methodSignature = (MethodSignature) signature; isVoidReturnType = (methodSignature != null) ? Void.TYPE.equals(methodSignature.getReturnType()) : false; } return isVoidReturnType; } private ExponentialRetryPolicy createExponentialRetryPolicy(ExponentialRetry retryAnnotation) { ExponentialRetryPolicy retryPolicy = new ExponentialRetryPolicy(retryAnnotation.initialRetryIntervalSeconds()).withExceptionsToRetry( Arrays.asList(retryAnnotation.exceptionsToRetry())).withExceptionsToExclude( Arrays.asList(retryAnnotation.excludeExceptions())).withBackoffCoefficient(retryAnnotation.backoffCoefficient()).withMaximumRetryIntervalSeconds( retryAnnotation.maximumRetryIntervalSeconds()).withRetryExpirationIntervalSeconds( retryAnnotation.retryExpirationSeconds()).withMaximumAttempts(retryAnnotation.maximumAttempts()); retryPolicy.validate(); return retryPolicy; } }
3,572
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/aspectj/AsynchronousAspect.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.aspectj; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import com.amazonaws.services.simpleworkflow.flow.annotations.Asynchronous; import com.amazonaws.services.simpleworkflow.flow.annotations.NoWait; import com.amazonaws.services.simpleworkflow.flow.annotations.Wait; import com.amazonaws.services.simpleworkflow.flow.core.AndPromise; import com.amazonaws.services.simpleworkflow.flow.core.Promise; @Aspect public class AsynchronousAspect { @SuppressWarnings({ "rawtypes", "unchecked" }) @Around("call(@com.amazonaws.services.simpleworkflow.flow.annotations.Asynchronous * *(..)) && @annotation(asynchronousAnnotation)") public Object makeAsynchronous(ProceedingJoinPoint pjp, Asynchronous asynchronousAnnotation) throws Throwable { final Signature signature = pjp.getStaticPart().getSignature(); if (signature instanceof MethodSignature) { final MethodSignature methodSignature = (MethodSignature) signature; int i = 0; Object[] methodArguments = pjp.getArgs(); Annotation[][] parameterAnnotations = methodSignature.getMethod().getParameterAnnotations(); List<Promise> valueParams = new ArrayList<Promise>(); for (final Class<?> parameterType : methodSignature.getParameterTypes()) { if ((isPromise(parameterType) || isPromiseArray(parameterType) || (isCollection(parameterType) && hasWaitAnnotation(parameterAnnotations[i]))) && !hasNoWaitAnnotation(parameterAnnotations[i])) { Object param = methodArguments[i]; if (isPromise(parameterType)) { valueParams.add((Promise) param); } else if (isCollection(parameterType)) { valueParams.add(new AndPromise((Collection) param)); } else { valueParams.add(new AndPromise((Promise[]) param)); } } else { valueParams.add(null); } i++; } Promise[] values = valueParams.toArray(new Promise[0]); Boolean daemon = asynchronousAnnotation.daemon() ? true : null; AsynchronousAspectTask task = new AsynchronousAspectTask(daemon, pjp, values); return task.getReturnValue(); } return pjp.proceed(); } private static boolean isPromise(Class<?> clazz) { return Promise.class.isAssignableFrom(clazz); } private static boolean isCollection(Class<?> clazz) { return Collection.class.isAssignableFrom(clazz); } private static boolean isPromiseArray(Class<?> clazz) { if (!clazz.isArray()) { return false; } Class<?> elementType = clazz.getComponentType(); return isPromise(elementType); } private static boolean hasWaitAnnotation(Annotation[] annotations) { for (Annotation annotation : annotations) { if (annotation.annotationType().equals(Wait.class)) { return true; } } return false; } private static boolean hasNoWaitAnnotation(Annotation[] annotations) { for (Annotation annotation : annotations) { if (annotation.annotationType().equals(NoWait.class)) { return true; } } return false; } }
3,573
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/aspectj/ExponentialRetryWithJitterAspect.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.aspectj; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProvider; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProviderImpl; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.annotations.ExponentialRetryWithJitter; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.interceptors.AsyncExecutor; import com.amazonaws.services.simpleworkflow.flow.interceptors.AsyncRetryingExecutor; import com.amazonaws.services.simpleworkflow.flow.interceptors.AsyncRunnable; import com.amazonaws.services.simpleworkflow.flow.interceptors.ExponentialRetryWithJitterPolicy; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.Signature; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import java.util.Arrays; import java.util.Random; /** * See {@link com.amazonaws.services.simpleworkflow.flow.aspectj.ExponentialRetryAspect} * for reference. */ @Aspect public class ExponentialRetryWithJitterAspect { @SuppressWarnings({ "rawtypes", "unchecked" }) private final class DecoratorInvocationHandler implements AsyncRunnable { private final ProceedingJoinPoint pjp; private final Settable result; public DecoratorInvocationHandler(ProceedingJoinPoint pjp, Settable result) { this.pjp = pjp; this.result = result; } @Override public void run() throws Throwable { if (result != null) { result.unchain(); result.chain((Promise) pjp.proceed()); } else { pjp.proceed(); } } } private final DecisionContextProvider decisionContextProviderImpl = new DecisionContextProviderImpl(); @Around("execution(@com.amazonaws.services.simpleworkflow.flow.annotations.ExponentialRetryWithJitter * *(..)) && @annotation(exponentialRetryWithJitterAnnotation)") public Object retry(final ProceedingJoinPoint pjp, final ExponentialRetryWithJitter exponentialRetryWithJitterAnnotation) throws Throwable { ExponentialRetryWithJitterPolicy retryPolicy = createExponentialRetryWithJitterPolicy(exponentialRetryWithJitterAnnotation); WorkflowClock clock = decisionContextProviderImpl.getDecisionContext().getWorkflowClock(); AsyncExecutor executor = new AsyncRetryingExecutor(retryPolicy, clock); Settable<?> result; if (isVoidReturnType(pjp)) { result = null; } else { result = new Settable<Object>(); } DecoratorInvocationHandler handler = new DecoratorInvocationHandler(pjp, result); executor.execute(handler); return result; } private boolean isVoidReturnType(final ProceedingJoinPoint pjp) { boolean isVoidReturnType = false; final Signature signature = pjp.getStaticPart().getSignature(); if (signature instanceof MethodSignature) { final MethodSignature methodSignature = (MethodSignature) signature; isVoidReturnType = (methodSignature != null) ? Void.TYPE.equals(methodSignature.getReturnType()) : false; } return isVoidReturnType; } private ExponentialRetryWithJitterPolicy createExponentialRetryWithJitterPolicy(final ExponentialRetryWithJitter exponentialRetryWithJitterAnnotation) { final String currentRunId = decisionContextProviderImpl.getDecisionContext().getWorkflowContext().getWorkflowExecution().getRunId(); final Random jitterCoefficientGenerator = new Random(currentRunId.hashCode()); final ExponentialRetryWithJitterPolicy retryPolicy = new ExponentialRetryWithJitterPolicy( exponentialRetryWithJitterAnnotation.initialRetryIntervalSeconds(), jitterCoefficientGenerator, exponentialRetryWithJitterAnnotation.maxJitterCoefficient()); retryPolicy.setBackoffCoefficient(exponentialRetryWithJitterAnnotation.backoffCoefficient()); retryPolicy.setExceptionsToExclude(Arrays.asList(exponentialRetryWithJitterAnnotation.excludeExceptions())); retryPolicy.setExceptionsToRetry(Arrays.asList(exponentialRetryWithJitterAnnotation.exceptionsToRetry())); retryPolicy.setMaximumAttempts(exponentialRetryWithJitterAnnotation.maximumAttempts()); retryPolicy.setMaximumRetryIntervalSeconds(exponentialRetryWithJitterAnnotation.maximumRetryIntervalSeconds()); retryPolicy.setRetryExpirationIntervalSeconds(exponentialRetryWithJitterAnnotation.retryExpirationSeconds()); retryPolicy.validate(); return retryPolicy; } }
3,574
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/Activities.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.JsonDataConverter; import com.amazonaws.services.simpleworkflow.flow.core.Promise; /** * {@literal @}Activities annotation is allowed on interfaces to define a set of activities. * This interface forms the contract between the implementation of the activities and * the clients used to invoke them. The client-side is auto-generated by AWS Flow Framework * annotation processor from the interfaces marked with @Activities annotation. * * Each method on the interface annotated with @Activities annotation corresponds to * an activity. Activity methods are not allowed to have {@link Promise} parameters * or return types. * * @author fateev, samar * */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Activities { /** * Prefix to use for each activity defined within the interface annotated * with @Activities annotation. Default is empty string which means that * name of interface should be used as the prefix for each activity name. */ String activityNamePrefix() default ""; /** * Version to use to each activity defined within the interface annotated * with @Activities annotation. Default is empty string which means that * version should be specified using {@link Activity#version()} on every * method individually. Alternatively you can specify the version for * all activities defined within the interface using this attribute. * * AWS Flow Framework annotation processor will report an error if version * for an activity is not specified through {@link Activities#version()} or * {@link Activity#version()}. */ String version() default ""; /** * This is used to specify {@link DataConverter} type to use for * serialization/de-serialization of activity method parameters and return types. * * Default is {@link NullDataConverter} which means to use the default * DataConverter used by framework. Default DataConverter used by framework is * {@link JsonDataConverter}. */ Class<? extends DataConverter> dataConverter() default NullDataConverter.class; }
3,575
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/Activity.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Optional annotation used on activity methods to override the name * and version. * * @see Activities * @author fateev, samar * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Activity { /** * This is used to override the name of ActivityType. * Default is empty string which means to use the method name. */ String name() default ""; /** * This is used to override the version of ActivityType. * Default is empty string which means to use the version specified on * {@link Activities} annotation for the interface. If * {@link Activities#version()} is also empty string then AWS Flow Framework * annotation processor reports an error. */ String version() default ""; }
3,576
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/ExponentialRetry.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.common.FlowDefaults; import com.amazonaws.services.simpleworkflow.flow.interceptors.RetryDecorator; /** * This annotation can be used for retrying failures on any asynchronous executions. * <p> * For retrying based on dynamic retry policy use {@link RetryDecorator}. * Both @ExponentialRetry annotation and {@link RetryDecorator} should not be * used simultaneously on the same asynchronous method call. * <p> * To allow retries for an individual activity, place the annotation on the desired * activity method in the corresponding @Activities <b>interface</b>. Since a new * activity instance is started per retry, any timeouts configured on the * {@literal @}ActivityRegistrationOptions apply to each individual retry of the activity. * <p> * To allow retries for an entire workflow, place the annotation on the override * of the workflow's @Execute method in the @Workflow's <b>implementation</b> * (rather than on the interface). Since the same workflow instance is reused * for each retry, any timeouts configured on the @WorkflowRegistrationOptions * apply to the total time of the workflow over all retries. * * @author fateev, samar * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ExponentialRetry { /** * Interval to wait after the initial failure, before triggering a retry. * <p> * This value should not be greater than values specified for * maximumRetryPeriod or retryExpirationPeriod. */ long initialRetryIntervalSeconds(); /** * Maximum interval to wait between retry attempts. * <p> * This value should not be less than value specified for * initialRetryPeriod. Default value is unlimited. */ long maximumRetryIntervalSeconds() default FlowDefaults.EXPONENTIAL_RETRY_MAXIMUM_RETRY_INTERVAL_SECONDS; /** * Total duration across all attempts before giving up and attempting * no further retries. * <p> * This duration is measured relative to the initial attempt's starting time. * and * <p> * This value should not be less than value specified for * initialRetryPeriod. Default value is unlimited. */ long retryExpirationSeconds() default FlowDefaults.EXPONENTIAL_RETRY_RETRY_EXPIRATION_SECONDS; /** * Coefficient to use for exponential retry policy. * <p> * The retry interval will be multiplied by this coefficient after each * subsequent failure. Default is 2.0. */ double backoffCoefficient() default FlowDefaults.EXPONENTIAL_RETRY_BACKOFF_COEFFICIENT; /** * Number of maximum retry attempts (including the initial attempt). * Default value is no limit. */ int maximumAttempts() default FlowDefaults.EXPONENTIAL_RETRY_MAXIMUM_ATTEMPTS; /** * Default is {@link Throwable} which means that all exceptions are retried. */ Class<? extends Throwable>[] exceptionsToRetry() default { Throwable.class }; /** * What exceptions that match exceptionsToRetry list should be not retried. * Default is empty list. */ Class<? extends Throwable>[] excludeExceptions() default {}; }
3,577
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/Asynchronous.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally; /** * Call to @Asynchronous method always returns immediately without executing it * code. Method body is scheduled for execution after all parameters that extend * {@link Promise} and not marked with {@link NoWait} are ready. The only valid * return types for @Asynchronous method are <code>void</code> and * {@link Promise}. * * @author fateev */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Asynchronous { /** * if set to true treats asynchronous task as a daemon task, allowing the * parent asynchronous scope to close if all non-daemon child tasks * completes. Default is <code>false</code> which means use the value of the * parent task. See {@link TryCatchFinally} for more info on daemon * semantic. */ boolean daemon() default false; }
3,578
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/SkipTypeRegistration.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.ActivityWorker; import com.amazonaws.services.simpleworkflow.flow.WorkflowWorker; /** * This can be used on interfaces annotated with {@link Activities} or {@link Workflow} * to specify no registration options are needed for ActivityType or WorkflowType * defined by such interfaces. * * Registration of types is skipped by {@link ActivityWorker} or {@link WorkflowWorker} * when interface is annotated with @SkipTypeRegistration. * * @see Activities * @see Workflow * @see ActivityWorker * @see WorkflowWorker * @author fateev, samar * */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface SkipTypeRegistration { }
3,579
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/NullDataConverter.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.DataConverterException; /** * To be used only by annotations as they do not support <code>null</code> parameters. * * @see Activities * @see Workflow * @author fateev, samar */ public final class NullDataConverter extends DataConverter { private NullDataConverter() { } @Override public <T> T fromData(String content, Class<T> valueType) throws DataConverterException { throw new UnsupportedOperationException("not implemented"); } @Override public String toData(Object value) throws DataConverterException { throw new UnsupportedOperationException("not implemented"); } }
3,580
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/WorkflowComponentImplementationVersion.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.WorkflowContext; import com.amazonaws.services.simpleworkflow.flow.WorkflowWorker; /** * Specifies supported implementation versions of a component used to implement * workflow definition. See * {@link WorkflowContext#isImplementationVersion(String, int)} for * implementation version overview. * <p> * To be used as a parameter to {@link WorkflowComponentImplementationVersions}. * * @author fateev */ @Retention(value = RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface WorkflowComponentImplementationVersion { /** * Name of a versioned component. */ String componentName(); /** * Minimum code implementation version supported by the workflow definition * code. Attempt to replay history that was created with a lower * implementation version must fail the decision. */ int minimumSupported() default 0; /** * Maximum code implementation version supported by the workflow definition * code. Attempt to replay history that was created with a higher * implementation version must fail the decision. */ int maximumSupported(); /** * Maximum version that newly executed code path can support. This value is * usually set to a maximumSupported version of the code that is being * upgraded from. After new workflow code is deployed to every worker this * value is changed to the maximumSupported value of the new code. * <p> * To avoid code change after the deployment consider changing maximum * allowed implementation version through * {@link WorkflowWorker#setMaximumAllowedComponentImplementationVersions(java.util.Map)}. */ int maximumAllowed() default Integer.MAX_VALUE; }
3,581
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/ActivityExecutionOptions.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface ActivityExecutionOptions { ActivityCompletionRetryOptions completionRetryOptions() default @ActivityCompletionRetryOptions; ActivityCompletionRetryOptions failureRetryOptions() default @ActivityCompletionRetryOptions; }
3,582
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/Execute.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.WorkflowWorker; import com.amazonaws.services.simpleworkflow.flow.core.Promise; /** * {@literal @}Execute annotation is used on methods of interface annotated with {@link Workflow} * to specify the entry-point for WorkflowType. * * {@literal @}Execute method can only have <code>void</code> or {@link Promise} return types. * Parameters of type {@link Promise} are not allowed. * * @see Workflow * @see WorkflowWorker * @author fateev, samar * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Execute { /** * Optional name of the workflow type. When missing defaults to the * annotated method name. Maximum length is 256 characters. */ String name() default ""; /** * Required version of the workflow type. Maximum length is 64 characters. */ String version(); }
3,583
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/ExponentialRetryUpdate.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.WorkflowContext; /** * Used to update values of &#064;{@link ExponentialRetry} without requiring * workflow type version change. Any changes to &#064;ExponentialRetry might * break determinism of a workflow execution. The standard mechanism for non * backward compatible changes to workflow definition without workflow type * version change is to use "implementation version" documented at * {@link WorkflowContext#isImplementationVersion(String, int)}. * &#064;ExponentialRetryUpdate contains a list of &#064;ExponentialRetry * annotations with associated implementation versions. An interceptor that * implements &#064;ExponentialRetry internally calls * {@link WorkflowContext#isImplementationVersion(String, int)} for each * version. * * @author fateev */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ExponentialRetryUpdate { String component(); ExponentialRetryVersion[] versions(); }
3,584
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/ManualActivityCompletion.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * {@literal @}ManualActivityCompletion is an optional annotation meant to be used on * implementations of activity methods to mark them to be completed * asynchronously. * * If this annotation is specified on an activity implementation method, then * Flow Framework will not try to automatically complete this activity when * method returns. If this method has a return type then return value * from the method is ignored. * * @author fateev, samar * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ManualActivityCompletion { }
3,585
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/ActivityCompletionRetryOptions.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.common.FlowDefaults; @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface ActivityCompletionRetryOptions { /** * Interval to wait after the initial failure, before triggering a retry. * <p> * This value should not be greater than values specified for * maximumRetryPeriod or retryExpirationPeriod. Default is 10 seconds. */ long initialRetryIntervalSeconds() default 10; /** * Maximum interval to wait between retry attempts. * <p> * This value should not be less than value specified for * initialRetryPeriod. Default value is 60 seconds. */ long maximumRetryIntervalSeconds() default 60; /** * Total duration across all attempts before giving up and attempting no * further retries. * <p> * This duration is measured relative to the initial attempt's starting * time. and * <p> * This value should not be less than value specified for * initialRetryPeriod. Default value is 300. */ long retryExpirationSeconds() default 300; /** * Coefficient to use for exponential retry policy. * <p> * The retry interval will be multiplied by this coefficient after each * subsequent failure. Default is 2.0. */ double backoffCoefficient() default FlowDefaults.EXPONENTIAL_RETRY_BACKOFF_COEFFICIENT; /** * Number of maximum retry attempts (including the initial attempt). Default * value is 10. */ int maximumAttempts() default 10; /** * Minimum number of retry attempts (including the initial attempt). In case * of failures at least this number of attempts is executed independently of * {@link #retryExpirationSeconds()}. Default value is 1. */ int minimumAttempts() default 1; }
3,586
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/ExponentialRetryVersion.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to specify implementation version of a &#064;{@link ExponentialRetry} * annotation. * * @see ExponentialRetryUpdate * @author fateev */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface ExponentialRetryVersion { ExponentialRetry retry(); int implementationVersion(); }
3,587
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/ExponentialRetryWithJitter.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; /** * This annotation can be used for retrying failures on any asynchronous executions. * This is an expansion of the annotation * {@link com.amazonaws.services.simpleworkflow.flow.annotations.ExponentialRetry} * * @author congwan * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ExponentialRetryWithJitter { /* * Maximum jitter coefficient to apply to retry interval. * This is the range for coefficient from which we draw a uniform random * number for the variation to be introduced in the delay. Default * value is 0.5. */ double maxJitterCoefficient() default FlowConstants.EXPONENTIAL_RETRY_MAXIMUM_JITTER_COEFFICIENT; /* * Interval to wait after the initial failure, before triggering a retry. * This value must not be greater than values specified for * maximumRetryPeriod or retryExpirationPeriod. Default value is 5. */ long initialRetryIntervalSeconds() default FlowConstants.EXPONENTIAL_INITIAL_RETRY_INTERVAL_SECONDS; /* * Maximum interval to wait between retry attempts. * This value must not be less than value specified for * initialRetryPeriod. Default value is unlimited. */ long maximumRetryIntervalSeconds() default FlowConstants.EXPONENTIAL_RETRY_MAXIMUM_RETRY_INTERVAL_SECONDS; /* * Total duration across all attempts before giving up and attempting no * further retries. * This duration is measured relative to the initial attempt's starting * time. This value must not be less than value specified for * initialRetryPeriod. Default value is unlimited. */ long retryExpirationSeconds() default FlowConstants.EXPONENTIAL_RETRY_EXPIRATION_SECONDS; /* * Coefficient to use for exponential retry policy. * The retry interval will be multiplied by this coefficient after each * subsequent failure. Default is 2.0. * * This value must greater than 1.0. Otherwise the delay would be smaller and smaller. */ double backoffCoefficient() default FlowConstants.EXPONENTIAL_RETRY_BACKOFF_COEFFICIENT; /* * Number of maximum retry attempts (including the initial attempt). Default * value is no limit. */ int maximumAttempts() default FlowConstants.EXPONENTIAL_RETRY_MAXIMUM_ATTEMPTS; /* * Default is {@link Throwable} which means that all exceptions are retried. */ Class<? extends Throwable>[] exceptionsToRetry() default { Throwable.class }; /* * What exceptions that match exceptionsToRetry list must be not retried. * Default is empty list. */ Class<? extends Throwable>[] excludeExceptions() default {}; }
3,588
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/WorkflowRegistrationOptions.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.WorkflowWorker; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.model.ChildPolicy; /** * {@literal @}WorkflowRegistrationOptions is a required annotation, unless * {@link SkipTypeRegistration} is provided, on interfaces annotated with * {@link Workflow}. * * It contains all the registration options for WorkflowType which will be used for * registration with Amazon SWF Service. Registration of types happen on * {@link WorkflowWorker#start()}. * * @see WorkflowWorker * @author fateev, samar * */ @Target(ElementType.TYPE) @Retention(value = RetentionPolicy.RUNTIME) public @interface WorkflowRegistrationOptions { /** * Optional textual description of the workflow type. Maximum length is 1024 * characters. */ String description() default ""; /** * Maximum time that workflow run is allowed to execute. Workflow is * forcefully closed by the SWF service if this timeout is exceeded. */ long defaultExecutionStartToCloseTimeoutSeconds(); /** * Single decision timeout. This timeout defines how long it takes to * reexecute a decision after {@link WorkflowWorker} catastrophic failure in * the middle of one. Do not confuse with the whole worklfow timeout ( * {@link #defaultExecutionStartToCloseTimeoutSeconds()} which can be really * big. Default is 30 seconds. */ long defaultTaskStartToCloseTimeoutSeconds() default 30; /** * Task list that decision task is delivered through for the given workflow * type. * * <p> * Default is {@link FlowConstants#USE_WORKER_TASK_LIST}, which means to use task * list from the {@link WorkflowWorker} that the workflow implementation is * registered with. */ String defaultTaskList() default FlowConstants.USE_WORKER_TASK_LIST; ChildPolicy defaultChildPolicy() default ChildPolicy.TERMINATE; /** * Default is {@link FlowConstants#DEFAULT_TASK_PRIORITY} if it * is not specified on activity invocation */ int defaultTaskPriority() default FlowConstants.DEFAULT_TASK_PRIORITY; String defaultLambdaRole() default ""; }
3,589
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/NoWait.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.core.Promise; /** * Used to mark {@link Promise} arguments of @Asynchronous methods that should * not be waited for. * <p> * Example usage: * * <pre> * <code> * {@literal @}Asynchronous * private void calculate(Promise&lt;Integer&gt; arg1, @NoWait Settable&lt;Integer&gt; result) { * ... * result.set(r); * } * </code> * </pre> * * @see Asynchronous * * @author fateev */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface NoWait { }
3,590
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/GetState.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.core.Promise; /** * Indicates that method is used to retrieve current workflow state. The method * is expected to perform read only access of the workflow implementation object * and is invoked synchronously which disallows use of any asynchronous * operations (like calling methods annotated with {@link Asynchronous}). * * Method is expected to have empty list of parameters. * {@link Promise} or <code>void</code> return types are not allowed for the annotated method. * * The generated external client implementation uses {@link AmazonSimpleWorkflow#describeWorkflowExecution(com.amazonaws.services.simpleworkflow.model.DescribeWorkflowExecutionRequest)} * visibility API to retrieve the state. It allows access to the sate using external client if decider * workers are down and even after workflow execution completion. * * @author fateev, samar */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface GetState { }
3,591
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/WorkflowComponentImplementationVersions.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.WorkflowContext; /** * Used to specify supported implementation versions of components used to * implement workflow definition. See * {@link WorkflowContext#isImplementationVersion(String, int)} for * implementation version overview. */ @Target(ElementType.TYPE) @Retention(value = RetentionPolicy.RUNTIME) public @interface WorkflowComponentImplementationVersions { WorkflowComponentImplementationVersion[] value(); }
3,592
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/Workflow.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.JsonDataConverter; /** * {@literal @}Workflow annotation is allowed on interfaces to define a workflow. This * interface forms the contract between the implementation of WorkflowType * and clients interested in starting executions, sending signals, and getting * current state of execution. * * Use {@link Execute} annotation on the method to mark it as the entry-point * for WorkflowType. @Workflow interface cannot have more than one method marked * with {@link Execute} annotation. * * Use {@link Signal} annotation on the methods to mark them as signals * supported by WorkflowType. @Workflow interface can have zero or more methods * marked with {@link Signal} annotation. * * Use {@link GetState} annotation on the method which framework will use to * update the current workflow state for WorkflowType. @Workflow interface * cannot have more than one method marked with {@link GetState} annotation. * * {@link Execute}, {@link Signal} and {@link GetState} annotations are mutually * exclusive and cannot be used simultaneously on a method. AWS Flow Framework * annotation processor will auto-generate three different clients which can * be used to start new executions, sending signals and retrieving workflow states * for different situations. * * @see DecisionContext * @author fateev, samar * */ @Retention(value = RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Workflow { /** * This is used to specify {@link DataConverter} type to use for * serialization/de-serialization of workflow method parameters and return types. * * Default is {@link NullDataConverter} which means to use the default * DataConverter used by framework. Default DataConverter used by framework is * {@link JsonDataConverter}. */ Class<? extends DataConverter> dataConverter() default NullDataConverter.class; }
3,593
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/ActivityRegistrationOptions.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.ActivitySchedulingOptions; import com.amazonaws.services.simpleworkflow.flow.ActivityWorker; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; /** * {@literal @}ActivityRegistrationOptions is a required annotation, unless * {@link SkipTypeRegistration} is provided, on either interface annotated with * {@link Activities} or activity method. * * It contains all the registration options for ActivityType which will be used * for registration with Amazon SWF Service. Registration of activity types happen * on {@link ActivityWorker#start()}. * * @see ActivityWorker * @author fateev, samar * */ @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface ActivityRegistrationOptions { String description() default ""; long defaultTaskScheduleToStartTimeoutSeconds(); /** * Default is {@link FlowConstants#NONE} which disables separate heartbeat * timeout. */ long defaultTaskHeartbeatTimeoutSeconds() default FlowConstants.NONE; /** * Default is {@link FlowConstants#NONE}. */ long defaultTaskScheduleToCloseTimeoutSeconds() default FlowConstants.NONE; long defaultTaskStartToCloseTimeoutSeconds(); /** * Task list that activity task is delivered through when no task list is * specified on activity invocation. * * <p> * Default is {@link FlowConstants#USE_WORKER_TASK_LIST}, which means to use task * list from the {@link ActivityWorker} that the activity implementation is * registered with. Specify {@link FlowConstants#NO_DEFAULT_TASK_LIST} to * not register any default task list. If no default task list registered it * becomes required scheduling option (specified through * {@link ActivitySchedulingOptions#setTaskList(String)}) when an activity * is called. */ String defaultTaskList() default FlowConstants.USE_WORKER_TASK_LIST; /** * Default is {@link FlowConstants#DEFAULT_TASK_PRIORITY} if it * is not specified on activity invocation */ int defaultTaskPriority() default FlowConstants.DEFAULT_TASK_PRIORITY; }
3,594
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/Wait.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Collection; import java.util.Map; import com.amazonaws.services.simpleworkflow.flow.core.Promise; /** * Used to mark parameters of @{@link Asynchronous} method that should be waited * to be ready. Not necessary for parameters that subclass {@link Promise}. * Required for {@link Collection} of Promises and {@link Map} of values of * Promise type. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Wait { }
3,595
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/annotations/Signal.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.flow.WorkflowWorker; import com.amazonaws.services.simpleworkflow.flow.core.Promise; /** * {@literal @}Signal annotation is used on methods of interface annotated with {@link Workflow} * to specify the method to invoke when a particular signal is received by workflow * execution with a matching name. * * {@literal @}Signal methods are not allowed to have {@link Promise} parameters types and can * only have <code>void</code> as return types. * * @see Workflow * @see WorkflowWorker * @author fateev, samar * */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Signal { /** * Optional name of the signal. * Default is empty-string which means to use the name of annotated method * as signal name. * Maximum length is 256 characters. */ String name() default ""; }
3,596
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/common/FlowValueConstraint.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.common; public enum FlowValueConstraint { FAILURE_REASON("FAILURE_REASON", 0, 256), FAILURE_DETAILS("FAILURE_DETAILS", 0, 32768); private final String value; private final int min; private final int max; private FlowValueConstraint(String value, int min, int max) { this.value = value; this.min = min; this.max = max; } @Override public String toString() { return value; } public int getMinSize() { return min; } public int getMaxSize() { return max; } public static FlowValueConstraint fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } else if ("FAILURE_REASON".equals(value)) { return FlowValueConstraint.FAILURE_REASON; } else if ("FAILURE_DETAILS".equals(value)) { return FlowValueConstraint.FAILURE_DETAILS; } else { throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } } }
3,597
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/common/RequestTimeoutHelper.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.common; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig; public class RequestTimeoutHelper { public static void overrideDataPlaneRequestTimeout(AmazonWebServiceRequest serviceRequest, SimpleWorkflowClientConfig config) { if (serviceRequest != null && config != null) { serviceRequest.setSdkRequestTimeout(config.getDataPlaneRequestTimeoutInMillis()); } } public static void overrideControlPlaneRequestTimeout(AmazonWebServiceRequest serviceRequest, SimpleWorkflowClientConfig config) { if (serviceRequest != null && config != null) { serviceRequest.setSdkRequestTimeout(config.getControlPlaneRequestTimeoutInMillis()); } } public static void overridePollRequestTimeout(AmazonWebServiceRequest serviceRequest, SimpleWorkflowClientConfig config) { if (serviceRequest != null && config != null) { serviceRequest.setSdkRequestTimeout(config.getPollingRequestTimeoutInMillis()); } } }
3,598
0
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/common/FlowConstants.java
/** * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpleworkflow.flow.common; public final class FlowConstants { public static final int NONE = -1; public static final int USE_REGISTERED_DEFAULTS = -2; /** * Do not specify task list on registration. Which means that task list is * required when scheduling activity. */ public static final String NO_DEFAULT_TASK_LIST = "NO_DEFAULT_TASK_LIST"; /** * Use task list of the {@link com.amazonaws.services.simpleworkflow.flow.ActivityWorker} or {@link com.amazonaws.services.simpleworkflow.flow.WorkflowWorker} * that is used to register activity or workflow as the default task list for * the activity or workflow type. */ public static final String USE_WORKER_TASK_LIST = "USE_WORKER_TASK_LIST"; /** * Use task priority 0 */ public static final int DEFAULT_TASK_PRIORITY = 0; public static final long DEFAULT_LAMBDA_FUNCTION_TIMEOUT = 300; /** * ExponentialRetryWithJitterPolicy defaults */ public static final int EXPONENTIAL_INITIAL_RETRY_INTERVAL_SECONDS = 5; public static final int EXPONENTIAL_RETRY_MAXIMUM_ATTEMPTS = -1; public static final long EXPONENTIAL_RETRY_MAXIMUM_RETRY_INTERVAL_SECONDS = -1; public static final long EXPONENTIAL_RETRY_EXPIRATION_SECONDS = -1; public static final double EXPONENTIAL_RETRY_BACKOFF_COEFFICIENT = 2.0; public static final double EXPONENTIAL_RETRY_MAXIMUM_JITTER_COEFFICIENT = 0.5; }
3,599