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/flow
Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/common/FlowHelpers.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 java.lang.reflect.Method; import java.util.Arrays; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.amazonaws.services.simpleworkflow.model.PredefinedDuration; /** * This class is for internal use only and may be changed or removed without * prior notice. * */ public final class FlowHelpers { private static final Map<Class<?>, Object> defaultValues = new ConcurrentHashMap<Class<?>, Object>(); static { defaultValues.put(byte.class, Byte.valueOf((byte) 0)); defaultValues.put(char.class, Character.valueOf((char) 0)); defaultValues.put(short.class, Short.valueOf((short) 0)); defaultValues.put(int.class, Integer.valueOf(0)); defaultValues.put(long.class, Long.valueOf(0)); defaultValues.put(float.class, Float.valueOf(0)); defaultValues.put(double.class, Double.valueOf(0)); defaultValues.put(boolean.class, Boolean.FALSE); } public static String secondsToDuration(Long seconds) { if (seconds == null || seconds == FlowConstants.NONE) { return PredefinedDuration.NONE.toString(); } else if (seconds == FlowConstants.USE_REGISTERED_DEFAULTS) { return null; } return Long.toString(seconds); } public static long durationToSeconds(String duration) { if (duration == null || duration.equals(PredefinedDuration.NONE.toString())) { return FlowConstants.NONE; } else { return Long.parseLong(duration); } } public static Object[] validateInput(Method method, Object[] args) { Class<?>[] paramterTypes = method.getParameterTypes(); int numberOfParameters = paramterTypes.length; if (args == null || args.length != numberOfParameters) { throw new IllegalStateException("Number of parameters does not match args size."); } int index = 0; for (Class<?> paramType : paramterTypes) { Object argument = args[index]; if (argument != null && !paramType.isAssignableFrom(argument.getClass())) { throw new IllegalStateException("Param type '" + paramType.getName() + "' is not assigable from '" + argument.getClass().getName() + "'."); } index++; } return args; } public static String taskPriorityToString(Integer taskPriority) { if (taskPriority == null) { return null; } return String.valueOf(taskPriority); } public static int taskPriorityToInt(String taskPriority) { if (taskPriority == null) { return FlowConstants.DEFAULT_TASK_PRIORITY; } else { return Integer.parseInt(taskPriority); } } /** * Returns array of parameter values which is the same as values if types * and values parameter have the same size. If values is shorter than types * then missing elements of returned array are filled with default values. * <p> * Used to support backward compatible changes in activities and workflow * APIs. */ public static Object[] getInputParameters(Class<?>[] types, Object[] values) { int valuesLength = 0; if (values != null) { valuesLength = values.length; } if (valuesLength == types.length) { return values; } Object[] result; if (values == null) { result = new Object[types.length]; } else { result = Arrays.copyOf(values, types.length); } for (int i = valuesLength; i < types.length; i++) { result[i] = getDefaultValue(types[i]); } return result; } public static Object getDefaultValue(Class<?> clazz) { return defaultValues.get(clazz); } }
3,600
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/FlowDefaults.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 class FlowDefaults { public static final long EXPONENTIAL_RETRY_MAXIMUM_RETRY_INTERVAL_SECONDS = FlowConstants.NONE; public static final long EXPONENTIAL_RETRY_RETRY_EXPIRATION_SECONDS = FlowConstants.NONE; public static final double EXPONENTIAL_RETRY_BACKOFF_COEFFICIENT = 2; public static final int EXPONENTIAL_RETRY_MAXIMUM_ATTEMPTS = FlowConstants.NONE; }
3,601
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/WorkflowExecutionUtils.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 java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.TimeoutException; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig; import com.amazonaws.services.simpleworkflow.model.CloseStatus; import com.amazonaws.services.simpleworkflow.model.Decision; import com.amazonaws.services.simpleworkflow.model.DescribeWorkflowExecutionRequest; import com.amazonaws.services.simpleworkflow.model.EventType; import com.amazonaws.services.simpleworkflow.model.ExecutionStatus; import com.amazonaws.services.simpleworkflow.model.GetWorkflowExecutionHistoryRequest; import com.amazonaws.services.simpleworkflow.model.History; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; import com.amazonaws.services.simpleworkflow.model.WorkflowExecutionCompletedEventAttributes; import com.amazonaws.services.simpleworkflow.model.WorkflowExecutionContinuedAsNewEventAttributes; import com.amazonaws.services.simpleworkflow.model.WorkflowExecutionDetail; import com.amazonaws.services.simpleworkflow.model.WorkflowExecutionInfo; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping; import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator; /** * Convenience methods to be used by unit tests and during development. * * @author fateev */ public class WorkflowExecutionUtils { /** * Blocks until workflow instance completes and returns its result. Useful * for unit tests and during development. <strong>Never</strong> use in * production setting as polling for worklow instance status is an expensive * operation. * * @param workflowExecution * result of * {@link AmazonSimpleWorkflow#startWorkflowExecution(com.amazonaws.services.simpleworkflow.model.StartWorkflowExecutionRequest)} * @return workflow instance result. * @throws InterruptedException * if thread is interrupted * @throws RuntimeException * if workflow instance ended up in any state but completed */ public static WorkflowExecutionCompletedEventAttributes waitForWorkflowExecutionResult(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution) throws InterruptedException { return waitForWorkflowExecutionResult(service, domain, workflowExecution, null); } public static WorkflowExecutionCompletedEventAttributes waitForWorkflowExecutionResult(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, SimpleWorkflowClientConfig config) throws InterruptedException { try { return waitForWorkflowExecutionResult(service, domain, workflowExecution, 0, config); } catch (TimeoutException e) { throw new Error("should never happen", e); } } /** * Waits up to specified timeout until workflow instance completes and * returns its result. Useful for unit tests and during development. * <strong>Never</strong> use in production setting as polling for worklow * instance status is an expensive operation. * * @param workflowExecution * result of * {@link AmazonSimpleWorkflow#startWorkflowExecution(com.amazonaws.services.simpleworkflow.model.StartWorkflowExecutionRequest)} * @return workflow instance result. * @throws InterruptedException * if thread is interrupted * @throws TimeoutException * if instance is not complete after specified timeout * @throws RuntimeException * if workflow instance ended up in any state but completed */ public static WorkflowExecutionCompletedEventAttributes waitForWorkflowExecutionResult(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, long timeoutSeconds) throws InterruptedException, TimeoutException { return waitForWorkflowExecutionResult(service, domain, workflowExecution, timeoutSeconds, null); } public static WorkflowExecutionCompletedEventAttributes waitForWorkflowExecutionResult(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, long timeoutSeconds, SimpleWorkflowClientConfig config) throws InterruptedException, TimeoutException { if (!waitForWorkflowInstanceCompletion(service, domain, workflowExecution, timeoutSeconds, config).equals( CloseStatus.COMPLETED.toString())) { String historyDump = WorkflowExecutionUtils.prettyPrintHistory(service, domain, workflowExecution, config); throw new RuntimeException("Workflow instance is not in completed state:\n" + historyDump); } return getWorkflowExecutionResult(service, domain, workflowExecution, config); } /** * Returns result of workflow instance execution. result of * {@link AmazonSimpleWorkflow#startWorkflowExecution(com.amazonaws.services.simpleworkflow.model.StartWorkflowExecutionRequest)} * * @throws IllegalStateException * if workflow is still running * @throws RuntimeException * if workflow instance ended up in any state but completed */ public static WorkflowExecutionCompletedEventAttributes getWorkflowExecutionResult(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution) { return getWorkflowExecutionResult(service, domain, workflowExecution, null); } public static WorkflowExecutionCompletedEventAttributes getWorkflowExecutionResult(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, SimpleWorkflowClientConfig config) { HistoryEvent closeEvent = getInstanceCloseEvent(service, domain, workflowExecution, config); if (closeEvent == null) { throw new IllegalStateException("Workflow is still running"); } if (closeEvent.getEventType().equals(EventType.WorkflowExecutionCompleted.toString())) { return closeEvent.getWorkflowExecutionCompletedEventAttributes(); } throw new RuntimeException("Workflow end state is not completed: " + prettyPrintHistoryEvent(closeEvent)); } public static HistoryEvent getInstanceCloseEvent(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution) { return getInstanceCloseEvent(service, domain, workflowExecution, null); } public static HistoryEvent getInstanceCloseEvent(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, SimpleWorkflowClientConfig config) { WorkflowExecutionInfo executionInfo = describeWorkflowInstance(service, domain, workflowExecution, config); if (executionInfo == null || executionInfo.getExecutionStatus().equals(ExecutionStatus.OPEN.toString())) { return null; } List<HistoryEvent> events = getHistory(service, domain, workflowExecution, true, config); if (events.size() == 0) { throw new IllegalStateException("empty history"); } HistoryEvent last = events.get(0); if (!isWorkflowExecutionCompletedEvent(last)) { throw new IllegalStateException("unexpected last history event for workflow in " + executionInfo.getExecutionStatus() + " state: " + last.getEventType()); } return last; } public static boolean isWorkflowExecutionCompletedEvent(HistoryEvent event) { return ((event != null) && (event.getEventType().equals(EventType.WorkflowExecutionCompleted.toString()) || event.getEventType().equals(EventType.WorkflowExecutionCanceled.toString()) || event.getEventType().equals(EventType.WorkflowExecutionFailed.toString()) || event.getEventType().equals(EventType.WorkflowExecutionTimedOut.toString()) || event.getEventType().equals(EventType.WorkflowExecutionContinuedAsNew.toString()) || event.getEventType().equals( EventType.WorkflowExecutionTerminated.toString()))); } public static boolean isActivityTaskClosedEvent(HistoryEvent event) { return ((event != null) && (event.getEventType().equals(EventType.ActivityTaskCompleted.toString()) || event.getEventType().equals(EventType.ActivityTaskCanceled.toString()) || event.getEventType().equals(EventType.ActivityTaskFailed.toString()) || event.getEventType().equals( EventType.ActivityTaskTimedOut.toString()))); } public static boolean isExternalWorkflowClosedEvent(HistoryEvent event) { return ((event != null) && (event.getEventType().equals(EventType.ChildWorkflowExecutionCompleted.toString()) || event.getEventType().equals(EventType.ChildWorkflowExecutionCanceled.toString()) || event.getEventType().equals(EventType.ChildWorkflowExecutionFailed.toString()) || event.getEventType().equals(EventType.ChildWorkflowExecutionTerminated.toString()) || event.getEventType().equals( EventType.ChildWorkflowExecutionTimedOut.toString()))); } public static WorkflowExecution getWorkflowIdFromExternalWorkflowCompletedEvent(HistoryEvent event) { if (event != null) { if (event.getEventType().equals(EventType.ChildWorkflowExecutionCompleted.toString())) { return event.getChildWorkflowExecutionCompletedEventAttributes().getWorkflowExecution(); } else if (event.getEventType().equals(EventType.ChildWorkflowExecutionCanceled.toString())) { return event.getChildWorkflowExecutionCanceledEventAttributes().getWorkflowExecution(); } else if (event.getEventType().equals(EventType.ChildWorkflowExecutionFailed.toString())) { return event.getChildWorkflowExecutionFailedEventAttributes().getWorkflowExecution(); } else if (event.getEventType().equals(EventType.ChildWorkflowExecutionTerminated.toString())) { return event.getChildWorkflowExecutionTerminatedEventAttributes().getWorkflowExecution(); } else if (event.getEventType().equals(EventType.ChildWorkflowExecutionTimedOut.toString())) { return event.getChildWorkflowExecutionTimedOutEventAttributes().getWorkflowExecution(); } } return null; } public static String getId(HistoryEvent historyEvent) { String id = null; if (historyEvent != null) { if (historyEvent.getEventType().equals(EventType.StartChildWorkflowExecutionFailed.toString())) { id = historyEvent.getStartChildWorkflowExecutionFailedEventAttributes().getWorkflowId(); } else if (historyEvent.getEventType().equals(EventType.ScheduleActivityTaskFailed.toString())) { id = historyEvent.getScheduleActivityTaskFailedEventAttributes().getActivityId(); } else if (historyEvent.getEventType().equals(EventType.StartTimerFailed.toString())) { id = historyEvent.getStartTimerFailedEventAttributes().getTimerId(); } } return id; } public static String getFailureCause(HistoryEvent historyEvent) { String failureCause = null; if (historyEvent != null) { if (historyEvent.getEventType().equals(EventType.StartChildWorkflowExecutionFailed.toString())) { failureCause = historyEvent.getStartChildWorkflowExecutionFailedEventAttributes().getCause(); } else if (historyEvent.getEventType().equals(EventType.SignalExternalWorkflowExecutionFailed.toString())) { failureCause = historyEvent.getSignalExternalWorkflowExecutionFailedEventAttributes().getCause(); } else if (historyEvent.getEventType().equals(EventType.ScheduleActivityTaskFailed.toString())) { failureCause = historyEvent.getScheduleActivityTaskFailedEventAttributes().getCause(); } else if (historyEvent.getEventType().equals(EventType.StartTimerFailed.toString())) { failureCause = historyEvent.getStartTimerFailedEventAttributes().getCause(); } else if (historyEvent.getEventType().equals(EventType.ContinueAsNewWorkflowExecutionFailed.toString())) { failureCause = historyEvent.getContinueAsNewWorkflowExecutionFailedEventAttributes().getCause(); } else if (historyEvent.getEventType().equals(EventType.RecordMarkerFailed.toString())) { failureCause = historyEvent.getRecordMarkerFailedEventAttributes().getCause(); } else if (historyEvent.getEventType().equals(EventType.RecordMarkerFailed.toString())) { failureCause = historyEvent.getRecordMarkerFailedEventAttributes().getCause(); } } return failureCause; } /** * Blocks until workflow instance completes. <strong>Never</strong> use in * production setting as polling for worklow instance status is an expensive * operation. * * @param workflowExecution * result of * {@link AmazonSimpleWorkflow#startWorkflowExecution(com.amazonaws.services.simpleworkflow.model.StartWorkflowExecutionRequest)} * @return instance close status */ public static String waitForWorkflowInstanceCompletion(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution) throws InterruptedException { return waitForWorkflowInstanceCompletion(service, domain, workflowExecution, null); } public static String waitForWorkflowInstanceCompletion(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, SimpleWorkflowClientConfig config) throws InterruptedException { try { return waitForWorkflowInstanceCompletion(service, domain, workflowExecution, 0, config); } catch (TimeoutException e) { throw new Error("should never happen", e); } } /** * Waits up to specified timeout for workflow instance completion. * <strong>Never</strong> use in production setting as polling for worklow * instance status is an expensive operation. * * @param workflowExecution * result of * {@link AmazonSimpleWorkflow#startWorkflowExecution(com.amazonaws.services.simpleworkflow.model.StartWorkflowExecutionRequest)} * @param timeoutSeconds * maximum time to wait for completion. 0 means wait forever. * @return instance close status * @throws TimeoutException */ public static String waitForWorkflowInstanceCompletion(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, long timeoutSeconds) throws InterruptedException, TimeoutException { return waitForWorkflowInstanceCompletion(service, domain, workflowExecution, timeoutSeconds, null); } public static String waitForWorkflowInstanceCompletion(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, long timeoutSeconds, SimpleWorkflowClientConfig config) throws InterruptedException, TimeoutException { long start = System.currentTimeMillis(); WorkflowExecutionInfo executionInfo = null; do { if (timeoutSeconds > 0 && System.currentTimeMillis() - start >= timeoutSeconds * 1000) { String historyDump = WorkflowExecutionUtils.prettyPrintHistory(service, domain, workflowExecution, config); throw new TimeoutException("Workflow instance is not complete after " + timeoutSeconds + " seconds: \n" + historyDump); } if (executionInfo != null) { Thread.sleep(1000); } executionInfo = describeWorkflowInstance(service, domain, workflowExecution, config); } while (executionInfo.getExecutionStatus().equals(ExecutionStatus.OPEN.toString())); return executionInfo.getCloseStatus(); } /** * Like * {@link #waitForWorkflowInstanceCompletion(AmazonSimpleWorkflow, String, WorkflowExecution, long)} * , except will wait for continued generations of the original workflow * execution too. * * @param service * @param domain * @param workflowExecution * @param timeoutSeconds * @return * @throws InterruptedException * @throws TimeoutException * * @see #waitForWorkflowInstanceCompletion(AmazonSimpleWorkflow, String, * WorkflowExecution, long) */ public static String waitForWorkflowInstanceCompletionAcrossGenerations(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, long timeoutSeconds) throws InterruptedException, TimeoutException { return waitForWorkflowInstanceCompletionAcrossGenerations(service, domain, workflowExecution, timeoutSeconds, null); } public static String waitForWorkflowInstanceCompletionAcrossGenerations(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, long timeoutSeconds, SimpleWorkflowClientConfig config) throws InterruptedException, TimeoutException { WorkflowExecution lastExecutionToRun = workflowExecution; long millisecondsAtFirstWait = System.currentTimeMillis(); String lastExecutionToRunCloseStatus = waitForWorkflowInstanceCompletion(service, domain, lastExecutionToRun, timeoutSeconds, config); // keep waiting if the instance continued as new while (lastExecutionToRunCloseStatus.equals(CloseStatus.CONTINUED_AS_NEW.toString())) { // get the new execution's information HistoryEvent closeEvent = getInstanceCloseEvent(service, domain, lastExecutionToRun, config); WorkflowExecutionContinuedAsNewEventAttributes continuedAsNewAttributes = closeEvent.getWorkflowExecutionContinuedAsNewEventAttributes(); WorkflowExecution newGenerationExecution = new WorkflowExecution().withWorkflowId(lastExecutionToRun.getWorkflowId()).withRunId( continuedAsNewAttributes.getNewExecutionRunId()); // and wait for it long currentTime = System.currentTimeMillis(); long millisecondsSinceFirstWait = currentTime - millisecondsAtFirstWait; long timeoutInSecondsForNextWait = timeoutSeconds - (millisecondsSinceFirstWait / 1000L); lastExecutionToRunCloseStatus = waitForWorkflowInstanceCompletion(service, domain, newGenerationExecution, timeoutInSecondsForNextWait, config); lastExecutionToRun = newGenerationExecution; } return lastExecutionToRunCloseStatus; } /** * Like * {@link #waitForWorkflowInstanceCompletionAcrossGenerations(AmazonSimpleWorkflow, String, WorkflowExecution, long)} * , but with no timeout. * * @param service * @param domain * @param workflowExecution * @return * @throws InterruptedException */ public static String waitForWorkflowInstanceCompletionAcrossGenerations(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution) throws InterruptedException { try { return waitForWorkflowInstanceCompletionAcrossGenerations(service, domain, workflowExecution, 0L, null); } catch (TimeoutException e) { throw new Error("should never happen", e); } } public static WorkflowExecutionInfo describeWorkflowInstance(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution) { return describeWorkflowInstance(service, domain, workflowExecution, null); } public static WorkflowExecutionInfo describeWorkflowInstance(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, SimpleWorkflowClientConfig config) { DescribeWorkflowExecutionRequest describeRequest = new DescribeWorkflowExecutionRequest(); describeRequest.setDomain(domain); describeRequest.setExecution(workflowExecution); RequestTimeoutHelper.overrideDataPlaneRequestTimeout(describeRequest, config); WorkflowExecutionDetail executionDetail = service.describeWorkflowExecution(describeRequest); WorkflowExecutionInfo instanceMetadata = executionDetail.getExecutionInfo(); return instanceMetadata; } /** * Returns workflow instance history in a human readable format. * * @param workflowExecution * result of * {@link AmazonSimpleWorkflow#startWorkflowExecution(com.amazonaws.services.simpleworkflow.model.StartWorkflowExecutionRequest)} */ public static String prettyPrintHistory(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution) { return prettyPrintHistory(service, domain, workflowExecution, null); } public static String prettyPrintHistory(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, SimpleWorkflowClientConfig config) { return prettyPrintHistory(service, domain, workflowExecution, true, config); } /** * Returns workflow instance history in a human readable format. * * @param workflowExecution * result of * {@link AmazonSimpleWorkflow#startWorkflowExecution(com.amazonaws.services.simpleworkflow.model.StartWorkflowExecutionRequest)} * @param showWorkflowTasks * when set to false workflow task events (decider events) are * not included */ public static String prettyPrintHistory(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, boolean showWorkflowTasks) { return prettyPrintHistory(service, domain, workflowExecution, showWorkflowTasks, null); } public static String prettyPrintHistory(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, boolean showWorkflowTasks, SimpleWorkflowClientConfig config) { List<HistoryEvent> events = getHistory(service, domain, workflowExecution, config); return prettyPrintHistory(events, showWorkflowTasks); } public static List<HistoryEvent> getHistory(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution) { return getHistory(service, domain, workflowExecution, false, null); } public static List<HistoryEvent> getHistory(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, SimpleWorkflowClientConfig config) { return getHistory(service, domain, workflowExecution, false, config); } public static List<HistoryEvent> getHistory(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, boolean reverseOrder) { return getHistory(service, domain, workflowExecution, reverseOrder, null); } public static List<HistoryEvent> getHistory(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, boolean reverseOrder, SimpleWorkflowClientConfig config) { List<HistoryEvent> events = new ArrayList<HistoryEvent>(); String nextPageToken = null; do { History history = getHistoryPage(nextPageToken, service, domain, workflowExecution, reverseOrder, config); events.addAll(history.getEvents()); nextPageToken = history.getNextPageToken(); } while (nextPageToken != null); return events; } public static History getHistoryPage(String nextPageToken, AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution) { return getHistoryPage(nextPageToken, service, domain, workflowExecution, false, null); } public static History getHistoryPage(String nextPageToken, AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, SimpleWorkflowClientConfig config) { return getHistoryPage(nextPageToken, service, domain, workflowExecution, false, config); } public static History getHistoryPage(String nextPageToken, AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, boolean reverseOrder) { return getHistoryPage(nextPageToken, service, domain, workflowExecution, reverseOrder, null); } public static History getHistoryPage(String nextPageToken, AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, boolean reverseOrder, SimpleWorkflowClientConfig config) { GetWorkflowExecutionHistoryRequest getHistoryRequest = new GetWorkflowExecutionHistoryRequest(); getHistoryRequest.setDomain(domain); getHistoryRequest.setExecution(workflowExecution); getHistoryRequest.setReverseOrder(reverseOrder); getHistoryRequest.setNextPageToken(nextPageToken); RequestTimeoutHelper.overrideDataPlaneRequestTimeout(getHistoryRequest, config); History history = service.getWorkflowExecutionHistory(getHistoryRequest); if (history == null) { throw new IllegalArgumentException("unknown workflow execution: " + workflowExecution); } return history; } /** * Returns workflow instance history in a human readable format. * * @param history instance history * @param showWorkflowTasks * when set to false workflow task events (decider events) are * not included */ public static String prettyPrintHistory(History history, boolean showWorkflowTasks) { return prettyPrintHistory(history.getEvents(), showWorkflowTasks); } public static String prettyPrintHistory(Iterable<HistoryEvent> events, boolean showWorkflowTasks) { StringBuffer result = new StringBuffer(); result.append("{"); boolean first = true; for (HistoryEvent event : events) { if (!showWorkflowTasks && event.getEventType().startsWith("WorkflowTask")) { continue; } if (first) { first = false; } else { result.append(","); } result.append("\n "); result.append(prettyPrintHistoryEvent(event)); } result.append("\n}"); return result.toString(); } public static String prettyPrintDecisions(Iterable<Decision> decisions) { StringBuffer result = new StringBuffer(); result.append("{"); boolean first = true; for (Decision decision : decisions) { if (first) { first = false; } else { result.append(","); } result.append("\n "); result.append(prettyPrintDecision(decision)); } result.append("\n}"); return result.toString(); } /** * Returns single event in a human readable format * * @param event * event to pretty print */ public static String prettyPrintHistoryEvent(HistoryEvent event) { String eventType = event.getEventType(); StringBuffer result = new StringBuffer(); result.append(eventType); result.append(prettyPrintObject(event, "getType", true, " ", false)); return result.toString(); } /** * Returns single decision in a human readable format * * @param decision * event to pretty print */ public static String prettyPrintDecision(Decision decision) { return prettyPrintObject(decision, "getType", true, " ", true); } /** * Not really a generic method for printing random object graphs. But it * works for events and decisions. */ private static String prettyPrintObject(Object object, String methodToSkip, boolean skipNullsAndEmptyCollections, String indentation, boolean skipLevel) { StringBuffer result = new StringBuffer(); if (object == null) { return "null"; } Class<? extends Object> clz = object.getClass(); if (Number.class.isAssignableFrom(clz)) { return String.valueOf(object); } if (Boolean.class.isAssignableFrom(clz)) { return String.valueOf(object); } if (clz.equals(String.class)) { return (String) object; } if (clz.equals(Date.class)) { return String.valueOf(object); } if (Map.class.isAssignableFrom(clz)) { return String.valueOf(object); } if (Collection.class.isAssignableFrom(clz)) { return String.valueOf(object); } if (!skipLevel) { result.append(" {"); } Method[] eventMethods = object.getClass().getMethods(); boolean first = true; for (Method method : eventMethods) { String name = method.getName(); if (!name.startsWith("get")) { continue; } if (name.equals(methodToSkip) || name.equals("getClass")) { continue; } if (Modifier.isStatic(method.getModifiers())) { continue; } Object value; try { value = method.invoke(object, (Object[]) null); if (value != null && value.getClass().equals(String.class) && name.equals("getDetails")) { value = printDetails((String) value); } } catch (InvocationTargetException e) { throw new RuntimeException(e.getTargetException()); } catch (RuntimeException e) { throw (RuntimeException) e; } catch (Exception e) { throw new RuntimeException(e); } if (skipNullsAndEmptyCollections) { if (value == null) { continue; } if (value instanceof Map && ((Map<?, ?>) value).isEmpty()) { continue; } if (value instanceof Collection && ((Collection<?>) value).isEmpty()) { continue; } } if (!skipLevel) { if (first) { first = false; } else { result.append(";"); } result.append("\n"); result.append(indentation); result.append(" "); result.append(name.substring(3)); result.append(" = "); result.append(prettyPrintObject(value, methodToSkip, skipNullsAndEmptyCollections, indentation + " ", false)); } else { result.append(prettyPrintObject(value, methodToSkip, skipNullsAndEmptyCollections, indentation, false)); } } if (!skipLevel) { result.append("\n"); result.append(indentation); result.append("}"); } return result.toString(); } public static String printDetails(String details) { Throwable failure = null; try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.activateDefaultTyping( BasicPolymorphicTypeValidator.builder() .allowIfBaseType(Object.class) .build(), DefaultTyping.NON_FINAL); failure = mapper.readValue(details, Throwable.class); } catch (Exception e) { // eat up any data converter exceptions } if (failure != null) { StringBuilder builder = new StringBuilder(); // Also print callstack StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); failure.printStackTrace(pw); builder.append(sw.toString()); details = builder.toString(); } return details; } /** * Simple Workflow limits length of the reason field. This method truncates * the passed argument to the maximum length. * * @param reason * string value to truncate * @return truncated value */ public static String truncateReason(String reason) { if (reason != null && reason.length() > FlowValueConstraint.FAILURE_REASON.getMaxSize()) { reason = reason.substring(0, FlowValueConstraint.FAILURE_REASON.getMaxSize()); } return reason; } public static String truncateDetails(String details) { if (details != null && details.length() > FlowValueConstraint.FAILURE_DETAILS.getMaxSize()) { details = details.substring(0, FlowValueConstraint.FAILURE_DETAILS.getMaxSize()); } return details; } }
3,602
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/generic/GenericWorkflowClient.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.generic; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; public interface GenericWorkflowClient { /** * Start child workflow. * * @return becomes ready when child successfully started. * {@link StartChildWorkflowReply#getResult()} becomes ready upon * child completion. */ public Promise<StartChildWorkflowReply> startChildWorkflow(StartChildWorkflowExecutionParameters parameters); public Promise<String> startChildWorkflow(String workflow, String version, String input); public Promise<String> startChildWorkflow(String workflow, String version, Promise<String> input); public Promise<Void> signalWorkflowExecution(SignalExternalWorkflowParameters signalParameters); public void requestCancelWorkflowExecution(WorkflowExecution execution); public void continueAsNewOnCompletion(ContinueAsNewWorkflowExecutionParameters parameters); /** * Deterministic unique child workflow id generator */ public String generateUniqueId(); }
3,603
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/generic/GenericWorkflowClientExternal.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.generic; import java.util.Map; import com.amazonaws.services.simpleworkflow.flow.WorkflowContext; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; public interface GenericWorkflowClientExternal { public WorkflowExecution startWorkflow(StartWorkflowExecutionParameters startParameters); public void signalWorkflowExecution(SignalExternalWorkflowParameters signalParameters); public void requestCancelWorkflowExecution(WorkflowExecution execution); public String getWorkflowState(WorkflowExecution execution); /** * @see WorkflowContext#isImplementationVersion(String, int) */ public Map<String, Integer> getImplementationVersions(WorkflowExecution execution); public void terminateWorkflowExecution(TerminateWorkflowExecutionParameters terminateParameters); public String generateUniqueId(); }
3,604
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/generic/ActivityImplementationFactory.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.generic; import com.amazonaws.services.simpleworkflow.model.ActivityType; public abstract class ActivityImplementationFactory { public abstract Iterable<ActivityType> getActivityTypesToRegister(); public abstract ActivityImplementation getActivityImplementation(ActivityType activityType); }
3,605
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/generic/StartChildWorkflowExecutionParameters.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.generic; import java.util.List; import java.util.Objects; import com.amazonaws.services.simpleworkflow.flow.StartWorkflowOptions; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.model.ChildPolicy; import com.amazonaws.services.simpleworkflow.model.WorkflowType; public class StartChildWorkflowExecutionParameters implements Cloneable { private String control; private long executionStartToCloseTimeoutSeconds = FlowConstants.USE_REGISTERED_DEFAULTS; private String input; private List<String> tagList; private String taskList; private long taskStartToCloseTimeoutSeconds = FlowConstants.USE_REGISTERED_DEFAULTS; private String workflowId; private WorkflowType workflowType; private ChildPolicy childPolicy; private int taskPriority; private String lambdaRole; public StartChildWorkflowExecutionParameters() { } public String getControl() { return control; } public void setControl(String control) { this.control = control; } public StartChildWorkflowExecutionParameters withControl(String control) { this.control = control; return this; } public long getExecutionStartToCloseTimeoutSeconds() { return executionStartToCloseTimeoutSeconds; } public void setExecutionStartToCloseTimeoutSeconds(long executionStartToCloseTimeoutSeconds) { this.executionStartToCloseTimeoutSeconds = executionStartToCloseTimeoutSeconds; } public StartChildWorkflowExecutionParameters withExecutionStartToCloseTimeoutSeconds(long executionStartToCloseTimeoutSeconds) { this.executionStartToCloseTimeoutSeconds = executionStartToCloseTimeoutSeconds; return this; } public String getInput() { return input; } public void setInput(String input) { this.input = input; } public StartChildWorkflowExecutionParameters withInput(String input) { this.input = input; return this; } public List<String> getTagList() { return tagList; } public void setTagList(List<String> tagList) { this.tagList = tagList; } public StartChildWorkflowExecutionParameters withTagList(List<String> tagList) { this.tagList = tagList; return this; } public String getTaskList() { return taskList; } public void setTaskList(String taskList) { this.taskList = taskList; } public StartChildWorkflowExecutionParameters withTaskList(String taskList) { this.taskList = taskList; return this; } public long getTaskStartToCloseTimeoutSeconds() { return taskStartToCloseTimeoutSeconds; } public void setTaskStartToCloseTimeoutSeconds(long taskStartToCloseTimeoutSeconds) { this.taskStartToCloseTimeoutSeconds = taskStartToCloseTimeoutSeconds; } public StartChildWorkflowExecutionParameters withTaskStartToCloseTimeoutSeconds(long taskStartToCloseTimeoutSeconds) { this.taskStartToCloseTimeoutSeconds = taskStartToCloseTimeoutSeconds; return this; } public String getWorkflowId() { return workflowId; } public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } public StartChildWorkflowExecutionParameters withWorkflowId(String workflowId) { this.workflowId = workflowId; return this; } public WorkflowType getWorkflowType() { return workflowType; } public void setWorkflowType(WorkflowType workflowType) { this.workflowType = workflowType; } public StartChildWorkflowExecutionParameters withWorkflowType(WorkflowType workflowType) { this.workflowType = workflowType; return this; } public ChildPolicy getChildPolicy() { return childPolicy; } public void setChildPolicy(ChildPolicy childPolicy) { this.childPolicy = childPolicy; } public StartChildWorkflowExecutionParameters withChildPolicy(ChildPolicy childPolicy) { this.childPolicy = childPolicy; return this; } public int getTaskPriority() { return taskPriority; } public void setTaskPriority(int taskPriority) { this.taskPriority = taskPriority; } public StartChildWorkflowExecutionParameters withTaskPriority(int taskPriority) { this.taskPriority = taskPriority; return this; } public String getLambdaRole() { return lambdaRole; } public void setLambdaRole(String lambdaRole) { this.lambdaRole = lambdaRole; } public StartChildWorkflowExecutionParameters withLambdaRole(String lambdaRole) { this.lambdaRole = lambdaRole; return this; } public StartChildWorkflowExecutionParameters createStartChildWorkflowExecutionParametersFromOptions( StartWorkflowOptions options, StartWorkflowOptions optionsOverride) { StartChildWorkflowExecutionParameters startChildWorkflowExecutionParameters = this.clone(); if (options != null) { setParametersFromStartWorkflowOptions(startChildWorkflowExecutionParameters, options); } if (optionsOverride != null) { setParametersFromStartWorkflowOptions(startChildWorkflowExecutionParameters, optionsOverride); } return startChildWorkflowExecutionParameters; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("WorkflowType: " + workflowType + ", "); sb.append("WorkflowId: " + workflowId + ", "); sb.append("Input: " + input + ", "); sb.append("Control: " + control + ", "); sb.append("ExecutionStartToCloseTimeout: " + executionStartToCloseTimeoutSeconds + ", "); sb.append("TaskStartToCloseTimeout: " + taskStartToCloseTimeoutSeconds + ", "); sb.append("TagList: " + tagList + ", "); sb.append("TaskList: " + taskList + ", "); sb.append("TaskPriority: " + taskPriority + ", "); sb.append("LambdaRole: " + lambdaRole); sb.append("}"); return sb.toString(); } @Override public StartChildWorkflowExecutionParameters clone() { StartChildWorkflowExecutionParameters result = new StartChildWorkflowExecutionParameters(); result.setControl(control); result.setExecutionStartToCloseTimeoutSeconds(executionStartToCloseTimeoutSeconds); result.setInput(input); result.setTagList(tagList); result.setTaskList(taskList); result.setTaskStartToCloseTimeoutSeconds(taskStartToCloseTimeoutSeconds); result.setWorkflowId(workflowId); result.setWorkflowType(workflowType); result.setTaskPriority(taskPriority); result.setLambdaRole(lambdaRole); return result; } private void setParametersFromStartWorkflowOptions(final StartChildWorkflowExecutionParameters destinationParameters, final StartWorkflowOptions options) { Objects.requireNonNull(destinationParameters, "destinationParameters"); Objects.requireNonNull(options, "options"); Long executionStartToCloseTimeoutSeconds = options.getExecutionStartToCloseTimeoutSeconds(); if (executionStartToCloseTimeoutSeconds != null) { destinationParameters.setExecutionStartToCloseTimeoutSeconds(executionStartToCloseTimeoutSeconds); } Long taskStartToCloseTimeoutSeconds = options.getTaskStartToCloseTimeoutSeconds(); if (taskStartToCloseTimeoutSeconds != null) { destinationParameters.setTaskStartToCloseTimeoutSeconds(taskStartToCloseTimeoutSeconds); } Integer taskPriority = options.getTaskPriority(); if (taskPriority != null) { destinationParameters.setTaskPriority(taskPriority); } List<String> tagList = options.getTagList(); if (tagList != null) { destinationParameters.setTagList(tagList); } String taskList = options.getTaskList(); if (taskList != null && !taskList.isEmpty()) { destinationParameters.setTaskList(taskList); } ChildPolicy childPolicy = options.getChildPolicy(); if (childPolicy != null) { destinationParameters.setChildPolicy(childPolicy); } String lambdaRole = options.getLambdaRole(); if (lambdaRole != null) { destinationParameters.setLambdaRole(lambdaRole); } } }
3,606
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/generic/SignalExternalWorkflowParameters.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.generic; public class SignalExternalWorkflowParameters implements Cloneable { private String input; private String runId; private String signalName; private String workflowId; public SignalExternalWorkflowParameters() { } public String getInput() { return input; } public void setInput(String input) { this.input = input; } public SignalExternalWorkflowParameters withInput(String input) { this.input = input; return this; } public String getRunId() { return runId; } public void setRunId(String runId) { this.runId = runId; } public SignalExternalWorkflowParameters withRunId(String runId) { this.runId = runId; return this; } public String getSignalName() { return signalName; } public void setSignalName(String signalName) { this.signalName = signalName; } public SignalExternalWorkflowParameters withSignalName(String signalName) { this.signalName = signalName; return this; } public String getWorkflowId() { return workflowId; } public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } public SignalExternalWorkflowParameters withWorkflowId(String workflowId) { this.workflowId = workflowId; return this; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("SignalName: " + signalName + ", "); sb.append("Input: " + input + ", "); sb.append("WorkflowId: " + workflowId + ", "); sb.append("RunId: " + runId + ", "); sb.append("}"); return sb.toString(); } public SignalExternalWorkflowParameters clone() { SignalExternalWorkflowParameters result = new SignalExternalWorkflowParameters(); result.setInput(input); result.setRunId(runId); result.setSignalName(signalName); result.setWorkflowId(workflowId); return result; } }
3,607
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/generic/ActivityImplementation.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.generic; import java.util.concurrent.CancellationException; 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.ActivityWorker; import com.amazonaws.services.simpleworkflow.flow.worker.ActivityTypeExecutionOptions; import com.amazonaws.services.simpleworkflow.flow.worker.ActivityTypeRegistrationOptions; import com.amazonaws.services.simpleworkflow.model.ActivityTask; /** * Base class for activity implementation. Extending * {@link ActivityImplementationBase} instead of {@link ActivityImplementation} * is recommended. * * @see ActivityWorker * @see ActivityImplementationBase * * @author fateev, suskin */ public abstract class ActivityImplementation { /** * Options passed to the * {@link AmazonSimpleWorkflow#registerActivityType(com.amazonaws.services.simpleworkflow.model.RegisterActivityTypeRequest)} * call. * * @return null if activity registration is not required on the worker * startup */ public abstract ActivityTypeRegistrationOptions getRegistrationOptions(); public abstract ActivityTypeExecutionOptions getExecutionOptions(); /** * Execute external activity or initiate its execution . * * @param context * information about activity to be executed. Use * {@link ActivityTask#getInput()} to get activity input * arguments. * @return result of activity execution. */ public abstract String execute(ActivityExecutionContext context) throws ActivityFailureException, CancellationException; }
3,608
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/generic/WorkflowDefinition.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.generic; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.WorkflowException; import com.amazonaws.services.simpleworkflow.flow.annotations.Asynchronous; import com.amazonaws.services.simpleworkflow.flow.annotations.Execute; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Task; import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally; import com.amazonaws.services.simpleworkflow.model.RespondDecisionTaskCompletedRequest; /** * Base class for all workflow definitions. Implementation should use * {@link Execute} to specify workflow name different from implementation class * name, different workflow version and other workflow instance registration and * execution parameters. * * @see Execute * @author fateev */ public abstract class WorkflowDefinition { /** * Asynchronous method that implements workflow business logic. This method * invocation is surrounded by {@link TryCatchFinally}. Workflow is * completed when {@link TryCatchFinally#doFinally()} is executed. So even * if return {@link Promise} of the method is ready but there is some * asynchronous task or activity still not completed workflow is not going * to complete. * * @param input * Data passed to the worklfow instance during start instance * call. * @return * @throws WorkflowException * Prefer throwing {@link WorkflowException}. */ public abstract Promise<String> execute(String input) throws WorkflowException; /** * Asynchronous method that implements signals handling logic. This method * invocation is surrounded by the same doTry of {@link TryCatchFinally} * that is used to execute workflow. It means that non handled failure * inside this method causes workflow execution failure. * * @throws WorkflowException * Prefer throwing {@link WorkflowException}. */ public abstract void signalRecieved(String signalName, String input) throws WorkflowException; /** * Return state that is inserted decision completion through * {@link RespondDecisionTaskCompletedRequest#setExecutionContext(String)} * and later can be retrieved through * {@link AmazonSimpleWorkflow#describeWorkflowExecution(com.amazonaws.services.simpleworkflow.model.DescribeWorkflowExecutionRequest)} * visibility call. * * Implementation of this call is expected to be synchronous and is not * allowed to invoke any asynchronous operations like creation of new * {@link Task} or calling methods marked with {@link Asynchronous} * annotation. It is also expected to be read only operation which is not * allowed to modify state of workflow in any way. * * @return current state of the workflow execution. * @throws WorkflowException * Prefer throwing {@link WorkflowException}. */ public abstract String getWorkflowState() throws WorkflowException; }
3,609
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/generic/GenericActivityClient.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.generic; import com.amazonaws.services.simpleworkflow.flow.core.Promise; public interface GenericActivityClient { /** * Used to dynamically schedule an activity for execution * * @param parameters * An object which encapsulates all the information required to * schedule an activity for execution * @return Promise to the result returned by the activity */ public abstract Promise<String> scheduleActivityTask(ExecuteActivityParameters parameters); /** * Used to dynamically schedule an activity for execution * * @param activity * Name of activity * @param input * A map of all input parameters to that activity * @return Promise to a result returned by the activity */ public abstract Promise<String> scheduleActivityTask(String activity, String version, String input); /** * Used to dynamically schedule an activity using its name * * @param activity * name of activity to schedule * @param input * a Value containing a map of all input parameters to that * activity * @return a Value which contains a Map of results returned by the activity */ public abstract Promise<String> scheduleActivityTask(final String activity, final String version, final Promise<String> input); }
3,610
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/generic/WorkflowTypeImplementationOptions.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.generic; import java.util.Collections; import java.util.List; public class WorkflowTypeImplementationOptions { private List<WorkflowTypeComponentImplementationVersion> implementationComponentVersions = Collections.emptyList(); public List<WorkflowTypeComponentImplementationVersion> getImplementationComponentVersions() { return implementationComponentVersions; } public void setImplementationComponentVersions(List<WorkflowTypeComponentImplementationVersion> implementationComponentVersions) { this.implementationComponentVersions = implementationComponentVersions; } }
3,611
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/generic/ExecuteActivityParameters.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.generic; import com.amazonaws.services.simpleworkflow.flow.ActivitySchedulingOptions; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.model.ActivityType; public class ExecuteActivityParameters implements Cloneable { private String activityId; private ActivityType activityType; private String control; private long heartbeatTimeoutSeconds = FlowConstants.USE_REGISTERED_DEFAULTS; private String input; private long scheduleToCloseTimeoutSeconds = FlowConstants.USE_REGISTERED_DEFAULTS; private long scheduleToStartTimeoutSeconds = FlowConstants.USE_REGISTERED_DEFAULTS; private long startToCloseTimeoutSeconds = FlowConstants.USE_REGISTERED_DEFAULTS; private String taskList; private int taskPriority; public ExecuteActivityParameters() { } /** * Returns the value of the Control property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 100000 * * @return The value of the Control property for this object. */ public String getControl() { return control; } /** * Sets the value of the Control property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 100000 * * @param control The new value for the Control property for this object. */ public void setControl(String control) { this.control = control; } /** * Sets the value of the Control property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 100000 * * @param control The new value for the Control property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public ExecuteActivityParameters withControl(String control) { this.control = control; return this; } /** * Returns the value of the ActivityType property for this object. * * @return The value of the ActivityType property for this object. */ public ActivityType getActivityType() { return activityType; } /** * Sets the value of the ActivityType property for this object. * * @param activityType The new value for the ActivityType property for this object. */ public void setActivityType(ActivityType activityType) { this.activityType = activityType; } /** * Sets the value of the ActivityType property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param activityType The new value for the ActivityType property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public ExecuteActivityParameters withActivityType(ActivityType activityType) { this.activityType = activityType; return this; } /** * Returns the value of the ActivityId property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>1 - 64 * * @return The value of the ActivityId property for this object. */ public String getActivityId() { return activityId; } /** * Sets the value of the ActivityId property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>1 - 64 * * @param activityId The new value for the ActivityId property for this object. */ public void setActivityId(String activityId) { this.activityId = activityId; } /** * Sets the value of the ActivityId property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b> * <b>Length: </b>1 - 64 * * @param activityId The new value for the ActivityId property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public ExecuteActivityParameters withActivityId(String activityId) { this.activityId = activityId; return this; } /** * Returns the value of the Input property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 100000 * * @return The value of the Input property for this object. */ public String getInput() { return input; } /** * Sets the value of the Input property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 100000 * * @param input The new value for the Input property for this object. */ public void setInput(String input) { this.input = input; } /** * Sets the value of the Input property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 100000 * * @param input The new value for the Input property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public ExecuteActivityParameters withInput(String input) { this.input = input; return this; } public long getHeartbeatTimeoutSeconds() { return heartbeatTimeoutSeconds; } public void setHeartbeatTimeoutSeconds(long heartbeatTimeoutSeconds) { this.heartbeatTimeoutSeconds = heartbeatTimeoutSeconds; } public ExecuteActivityParameters withHeartbeatTimeoutSeconds(long heartbeatTimeoutSeconds) { this.heartbeatTimeoutSeconds = heartbeatTimeoutSeconds; return this; } /** * Returns the value of the ScheduleToStartTimeout property for this * object. * <p> * <b>Constraints:</b> * <b>Length: </b>1 - 64 * * @return The value of the ScheduleToStartTimeout property for this object. */ public long getScheduleToStartTimeoutSeconds() { return scheduleToStartTimeoutSeconds; } /** * Sets the value of the ScheduleToStartTimeout property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>1 - 64 * * @param scheduleToStartTimeoutSeconds The new value for the ScheduleToStartTimeout property for this object. */ public void setScheduleToStartTimeoutSeconds(long scheduleToStartTimeoutSeconds) { this.scheduleToStartTimeoutSeconds = scheduleToStartTimeoutSeconds; } /** * Sets the value of the ScheduleToStartTimeout property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b> * <b>Length: </b>1 - 64 * * @param scheduleToStartTimeoutSeconds The new value for the ScheduleToStartTimeout property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public ExecuteActivityParameters withScheduleToStartTimeoutSeconds(long scheduleToStartTimeoutSeconds) { this.scheduleToStartTimeoutSeconds = scheduleToStartTimeoutSeconds; return this; } /** * Returns the value of the ScheduleToCloseTimeout property for this * object. * <p> * <b>Constraints:</b> * <b>Length: </b>1 - 64 * * @return The value of the ScheduleToCloseTimeout property for this object. */ public long getScheduleToCloseTimeoutSeconds() { return scheduleToCloseTimeoutSeconds; } /** * Sets the value of the ScheduleToCloseTimeout property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>1 - 64 * * @param scheduleToCloseTimeoutSeconds The new value for the ScheduleToCloseTimeout property for this object. */ public void setScheduleToCloseTimeoutSeconds(long scheduleToCloseTimeoutSeconds) { this.scheduleToCloseTimeoutSeconds = scheduleToCloseTimeoutSeconds; } /** * Sets the value of the ScheduleToCloseTimeout property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b> * <b>Length: </b>1 - 64 * * @param scheduleToCloseTimeoutSeconds The new value for the ScheduleToCloseTimeout property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public ExecuteActivityParameters withScheduleToCloseTimeoutSeconds(long scheduleToCloseTimeoutSeconds) { this.scheduleToCloseTimeoutSeconds = scheduleToCloseTimeoutSeconds; return this; } public long getStartToCloseTimeoutSeconds() { return startToCloseTimeoutSeconds; } public void setStartToCloseTimeoutSeconds(long startToCloseTimeoutSeconds) { this.startToCloseTimeoutSeconds = startToCloseTimeoutSeconds; } public ExecuteActivityParameters withStartToCloseTimeoutSeconds(long startToCloseTimeoutSeconds) { this.startToCloseTimeoutSeconds = startToCloseTimeoutSeconds; return this; } /** * Returns the value of the TaskList property for this object. * * @return The value of the TaskList property for this object. */ public String getTaskList() { return taskList; } /** * Sets the value of the TaskList property for this object. * * @param taskList The new value for the TaskList property for this object. */ public void setTaskList(String taskList) { this.taskList = taskList; } /** * Sets the value of the TaskList property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param taskList The new value for the TaskList property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public ExecuteActivityParameters withTaskList(String taskList) { this.taskList = taskList; return this; } public int getTaskPriority() { return taskPriority; } public void setTaskPriority(int taskPriority) { this.taskPriority = taskPriority; } public ExecuteActivityParameters withTaskPriority(int taskPriority) { this.taskPriority = taskPriority; return this; } public ExecuteActivityParameters createExecuteActivityParametersFromOptions(ActivitySchedulingOptions options, ActivitySchedulingOptions optionsOverride) { ExecuteActivityParameters scheduleActivityParameters = this.clone(); if (options != null) { Long heartbeatTimeoutSeconds = options.getHeartbeatTimeoutSeconds(); if (heartbeatTimeoutSeconds != null) { scheduleActivityParameters.setHeartbeatTimeoutSeconds(heartbeatTimeoutSeconds); } Long scheduleToCloseTimeout = options.getScheduleToCloseTimeoutSeconds(); if (scheduleToCloseTimeout != null) { scheduleActivityParameters.setScheduleToCloseTimeoutSeconds(scheduleToCloseTimeout); } Long scheduleToStartTimeout = options.getScheduleToStartTimeoutSeconds(); if (scheduleToStartTimeout != null) { scheduleActivityParameters.setScheduleToStartTimeoutSeconds(scheduleToStartTimeout); } Long startToCloseTimeoutSeconds = options.getStartToCloseTimeoutSeconds(); if (startToCloseTimeoutSeconds != null) { scheduleActivityParameters.setStartToCloseTimeoutSeconds(startToCloseTimeoutSeconds); } String taskList = options.getTaskList(); if (taskList != null && !taskList.isEmpty()) { scheduleActivityParameters.setTaskList(taskList); } Integer taskPriority = options.getTaskPriority(); if (taskPriority != null) { scheduleActivityParameters.setTaskPriority(taskPriority); } } if (optionsOverride != null) { Long heartbeatTimeoutSeconds = optionsOverride.getHeartbeatTimeoutSeconds(); if (heartbeatTimeoutSeconds != null) { scheduleActivityParameters.setHeartbeatTimeoutSeconds(heartbeatTimeoutSeconds); } Long scheduleToCloseTimeout = optionsOverride.getScheduleToCloseTimeoutSeconds(); if (scheduleToCloseTimeout != null) { scheduleActivityParameters.setScheduleToCloseTimeoutSeconds(scheduleToCloseTimeout); } Long scheduleToStartTimeout = optionsOverride.getScheduleToStartTimeoutSeconds(); if (scheduleToStartTimeout != null) { scheduleActivityParameters.setScheduleToStartTimeoutSeconds(scheduleToStartTimeout); } Long startToCloseTimeoutSeconds = optionsOverride.getStartToCloseTimeoutSeconds(); if (startToCloseTimeoutSeconds != null) { scheduleActivityParameters.setStartToCloseTimeoutSeconds(startToCloseTimeoutSeconds); } String taskList = optionsOverride.getTaskList(); if (taskList != null && !taskList.isEmpty()) { scheduleActivityParameters.setTaskList(taskList); } Integer taskPriority = optionsOverride.getTaskPriority(); if (taskPriority != null) { scheduleActivityParameters.setTaskPriority(taskPriority); } } return scheduleActivityParameters; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("ActivityType: " + activityType + ", "); sb.append("ActivityId: " + activityId + ", "); sb.append("Input: " + input + ", "); sb.append("Control: " + control + ", "); sb.append("HeartbeatTimeout: " + heartbeatTimeoutSeconds + ", "); sb.append("ScheduleToStartTimeout: " + scheduleToStartTimeoutSeconds + ", "); sb.append("ScheduleToCloseTimeout: " + scheduleToCloseTimeoutSeconds + ", "); sb.append("StartToCloseTimeout: " + startToCloseTimeoutSeconds + ", "); sb.append("TaskList: " + taskList + ", "); sb.append("TaskPriority: " + taskPriority); sb.append("}"); return sb.toString(); } public ExecuteActivityParameters clone() { ExecuteActivityParameters result = new ExecuteActivityParameters(); result.setActivityType(activityType); result.setActivityId(activityId); result.setInput(input); result.setControl(control); result.setHeartbeatTimeoutSeconds(heartbeatTimeoutSeconds); result.setScheduleToStartTimeoutSeconds(scheduleToStartTimeoutSeconds); result.setScheduleToCloseTimeoutSeconds(scheduleToCloseTimeoutSeconds); result.setStartToCloseTimeoutSeconds(startToCloseTimeoutSeconds); result.setTaskList(taskList); result.setTaskPriority(taskPriority); return result; } }
3,612
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/generic/TerminateWorkflowExecutionParameters.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.generic; import com.amazonaws.services.simpleworkflow.model.ChildPolicy; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; public class TerminateWorkflowExecutionParameters { private WorkflowExecution workflowExecution; private ChildPolicy childPolicy; private String reason; private String details; public TerminateWorkflowExecutionParameters() { } public TerminateWorkflowExecutionParameters(WorkflowExecution workflowExecution, ChildPolicy childPolicy, String reason, String details) { this.workflowExecution = workflowExecution; this.childPolicy = childPolicy; this.reason = reason; this.details = details; } public WorkflowExecution getWorkflowExecution() { return workflowExecution; } public void setWorkflowExecution(WorkflowExecution workflowExecution) { this.workflowExecution = workflowExecution; } public TerminateWorkflowExecutionParameters withWorkflowExecution(WorkflowExecution workflowExecution) { this.workflowExecution = workflowExecution; return this; } public ChildPolicy getChildPolicy() { return childPolicy; } public void setChildPolicy(ChildPolicy childPolicy) { this.childPolicy = childPolicy; } public TerminateWorkflowExecutionParameters withChildPolicy(ChildPolicy childPolicy) { this.childPolicy = childPolicy; return this; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public TerminateWorkflowExecutionParameters withReason(String reason) { this.reason = reason; return this; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } public TerminateWorkflowExecutionParameters withDetails(String details) { this.details = details; return this; } }
3,613
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/generic/WorkflowTypeComponentImplementationVersion.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.generic; /** * @author fateev * */ public class WorkflowTypeComponentImplementationVersion { private final String componentName; private final int minimumSupported; private final int maximumSupported; private int maximumAllowed; public WorkflowTypeComponentImplementationVersion(String componentName, int minimumSupported, int maximumSupported, int maximumAllowed) { this.componentName = componentName; this.minimumSupported = minimumSupported; this.maximumSupported = maximumSupported; this.maximumAllowed = maximumAllowed; } public String getComponentName() { return componentName; } /** * Minimum version supported for code replay */ public int getMinimumSupported() { return minimumSupported; } /** * Maximum version supported for code replay */ public int getMaximumSupported() { return maximumSupported; } public int getMaximumAllowed() { return maximumAllowed; } /** * Maximum version allowed for a newly executed code */ public void setMaximumAllowed(int maximumAllowed) { this.maximumAllowed = maximumAllowed; } }
3,614
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/generic/ContinueAsNewWorkflowExecutionParameters.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.generic; import java.util.List; import com.amazonaws.services.simpleworkflow.flow.StartWorkflowOptions; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.model.ChildPolicy; public class ContinueAsNewWorkflowExecutionParameters { private String workflowTypeVersion; private long executionStartToCloseTimeoutSeconds = FlowConstants.USE_REGISTERED_DEFAULTS; private String input; private List<String> tagList; private String taskList; private long taskStartToCloseTimeoutSeconds = FlowConstants.USE_REGISTERED_DEFAULTS; private ChildPolicy childPolicy; private int taskPriority; private String lambdaRole; public ContinueAsNewWorkflowExecutionParameters() { } public String getWorkflowTypeVersion() { return workflowTypeVersion; } public void setWorkflowTypeVersion(String workflowTypeVersion) { this.workflowTypeVersion = workflowTypeVersion; } public ChildPolicy getChildPolicy() { return childPolicy; } public void setChildPolicy(ChildPolicy childPolicy) { this.childPolicy = childPolicy; } public long getExecutionStartToCloseTimeoutSeconds() { return executionStartToCloseTimeoutSeconds; } public void setExecutionStartToCloseTimeoutSeconds(long executionStartToCloseTimeoutSeconds) { this.executionStartToCloseTimeoutSeconds = executionStartToCloseTimeoutSeconds; } public ContinueAsNewWorkflowExecutionParameters withExecutionStartToCloseTimeoutSeconds(long executionStartToCloseTimeoutSeconds) { this.executionStartToCloseTimeoutSeconds = executionStartToCloseTimeoutSeconds; return this; } public String getInput() { return input; } public void setInput(String input) { this.input = input; } public ContinueAsNewWorkflowExecutionParameters withInput(String input) { this.input = input; return this; } public List<String> getTagList() { return tagList; } public void setTagList(List<String> tagList) { this.tagList = tagList; } public ContinueAsNewWorkflowExecutionParameters withTagList(List<String> tagList) { this.tagList = tagList; return this; } public String getTaskList() { return taskList; } public void setTaskList(String taskList) { this.taskList = taskList; } public ContinueAsNewWorkflowExecutionParameters withTaskList(String taskList) { this.taskList = taskList; return this; } public int getTaskPriority() { return taskPriority; } public void setTaskPriority(int taskPriority) { this.taskPriority = taskPriority; } public ContinueAsNewWorkflowExecutionParameters withTaskPriority(int taskPriority) { this.taskPriority = taskPriority; return this; } public long getTaskStartToCloseTimeoutSeconds() { return taskStartToCloseTimeoutSeconds; } public void setTaskStartToCloseTimeoutSeconds(long taskStartToCloseTimeoutSeconds) { this.taskStartToCloseTimeoutSeconds = taskStartToCloseTimeoutSeconds; } public ContinueAsNewWorkflowExecutionParameters withTaskStartToCloseTimeoutSeconds(long taskStartToCloseTimeoutSeconds) { this.taskStartToCloseTimeoutSeconds = taskStartToCloseTimeoutSeconds; return this; } public String getLambdaRole() { return lambdaRole; } public void setLambdaRole(String lambdaRole) { this.lambdaRole = lambdaRole; } public ContinueAsNewWorkflowExecutionParameters withLambdaRole(String lambdaRole) { this.lambdaRole = lambdaRole; return this; } public ContinueAsNewWorkflowExecutionParameters createContinueAsNewParametersFromOptions(StartWorkflowOptions options, StartWorkflowOptions optionsOverride) { ContinueAsNewWorkflowExecutionParameters continueAsNewWorkflowExecutionParameters = this.clone(); if (options != null) { Long executionStartToCloseTimeoutSeconds = options.getExecutionStartToCloseTimeoutSeconds(); if (executionStartToCloseTimeoutSeconds != null) { continueAsNewWorkflowExecutionParameters.setExecutionStartToCloseTimeoutSeconds(executionStartToCloseTimeoutSeconds); } Long taskStartToCloseTimeoutSeconds = options.getTaskStartToCloseTimeoutSeconds(); if (taskStartToCloseTimeoutSeconds != null) { continueAsNewWorkflowExecutionParameters.setTaskStartToCloseTimeoutSeconds(taskStartToCloseTimeoutSeconds); } List<String> tagList = options.getTagList(); if (tagList != null) { continueAsNewWorkflowExecutionParameters.setTagList(tagList); } String taskList = options.getTaskList(); if (taskList != null && !taskList.isEmpty()) { continueAsNewWorkflowExecutionParameters.setTaskList(taskList); } ChildPolicy childPolicy = options.getChildPolicy(); if (childPolicy != null) { continueAsNewWorkflowExecutionParameters.setChildPolicy(childPolicy); } Integer taskPriority = options.getTaskPriority(); if (taskPriority != null) { continueAsNewWorkflowExecutionParameters.setTaskPriority(taskPriority); } String lambdaRole = options.getLambdaRole(); if (lambdaRole != null) { continueAsNewWorkflowExecutionParameters.setLambdaRole(lambdaRole); } } if (optionsOverride != null) { Long executionStartToCloseTimeoutSeconds = optionsOverride.getExecutionStartToCloseTimeoutSeconds(); if (executionStartToCloseTimeoutSeconds != null) { continueAsNewWorkflowExecutionParameters.setExecutionStartToCloseTimeoutSeconds(executionStartToCloseTimeoutSeconds); } Long taskStartToCloseTimeoutSeconds = optionsOverride.getTaskStartToCloseTimeoutSeconds(); if (taskStartToCloseTimeoutSeconds != null) { continueAsNewWorkflowExecutionParameters.setTaskStartToCloseTimeoutSeconds(taskStartToCloseTimeoutSeconds); } List<String> tagList = optionsOverride.getTagList(); if (tagList != null) { continueAsNewWorkflowExecutionParameters.setTagList(tagList); } String taskList = optionsOverride.getTaskList(); if (taskList != null && !taskList.isEmpty()) { continueAsNewWorkflowExecutionParameters.setTaskList(taskList); } ChildPolicy childPolicy = optionsOverride.getChildPolicy(); if (childPolicy != null) { continueAsNewWorkflowExecutionParameters.setChildPolicy(childPolicy); } Integer taskPriority = optionsOverride.getTaskPriority(); if (taskPriority != null) { continueAsNewWorkflowExecutionParameters.setTaskPriority(taskPriority); } String lambdaRole = optionsOverride.getLambdaRole(); if (lambdaRole != null) { continueAsNewWorkflowExecutionParameters.setLambdaRole(lambdaRole); } } return continueAsNewWorkflowExecutionParameters; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("Input: " + input + ", "); sb.append("ExecutionStartToCloseTimeout: " + executionStartToCloseTimeoutSeconds + ", "); sb.append("TaskStartToCloseTimeout: " + taskStartToCloseTimeoutSeconds + ", "); sb.append("TagList: " + tagList + ", "); sb.append("TaskList: " + taskList + ", "); sb.append("TaskPriority: " + taskPriority + ", "); sb.append("LambdaRole: " + lambdaRole); sb.append("}"); return sb.toString(); } public ContinueAsNewWorkflowExecutionParameters clone() { ContinueAsNewWorkflowExecutionParameters result = new ContinueAsNewWorkflowExecutionParameters(); result.setWorkflowTypeVersion(workflowTypeVersion); result.setExecutionStartToCloseTimeoutSeconds(executionStartToCloseTimeoutSeconds); result.setInput(input); result.setTagList(tagList); result.setTaskList(taskList); result.setTaskStartToCloseTimeoutSeconds(taskStartToCloseTimeoutSeconds); result.setChildPolicy(childPolicy); result.setTaskPriority(taskPriority); result.setLambdaRole(lambdaRole); return result; } }
3,615
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/generic/ActivityImplementationBase.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.generic; import java.util.concurrent.CancellationException; import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContext; import com.amazonaws.services.simpleworkflow.flow.ActivityFailureException; import com.amazonaws.services.simpleworkflow.flow.ActivityWorker; import com.amazonaws.services.simpleworkflow.flow.worker.ActivityTypeExecutionOptions; import com.amazonaws.services.simpleworkflow.flow.worker.ActivityTypeRegistrationOptions; import com.amazonaws.services.simpleworkflow.model.ActivityTask; /** * Extend this class to implement an activity. There are two types of activity * implementation: synchronous and asynchronous. Synchronous ties thread that * calls {@link #execute(String, ActivityExecutionContext)} method. * * @see ActivityWorker * * @author fateev */ public abstract class ActivityImplementationBase extends ActivityImplementation { /** * @see ActivityImplementation#execute(ActivityExecutionContext) */ @Override public String execute(ActivityExecutionContext context) throws ActivityFailureException, CancellationException { ActivityTask task = context.getTask(); return execute(task.getInput(), context); } @Override public ActivityTypeExecutionOptions getExecutionOptions() { return new ActivityTypeExecutionOptions(); } /** * By default do not register */ @Override public ActivityTypeRegistrationOptions getRegistrationOptions() { return null; } /** * Execute activity. * @param input * activity input. * @return result of activity execution */ protected abstract String execute(String input, ActivityExecutionContext context) throws ActivityFailureException, CancellationException; }
3,616
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/generic/WorkflowDefinitionFactoryFactory.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.generic; import com.amazonaws.services.simpleworkflow.model.WorkflowType; public abstract class WorkflowDefinitionFactoryFactory { public abstract WorkflowDefinitionFactory getWorkflowDefinitionFactory(WorkflowType workflowType); /** * There is no requirement to return any types. If type is returned * {@link #getWorkflowDefinitionFactory(WorkflowType)} should support it. * * @return types that should be registered before polling and executing * decision tasks. */ public abstract Iterable<WorkflowType> getWorkflowTypesToRegister(); }
3,617
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/generic/WorkflowDefinitionFactory.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.generic; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.WorkflowTypeRegistrationOptions; import com.amazonaws.services.simpleworkflow.model.WorkflowType; public abstract class WorkflowDefinitionFactory { /** * * @return options to use when registering workflow type with the service. * <code>null</code> if registration is not necessary on executor * startup. */ public abstract WorkflowTypeRegistrationOptions getWorkflowRegistrationOptions(); public WorkflowTypeImplementationOptions getWorkflowImplementationOptions() { // body is present to not break existing implementations. return null; } /** * Create an instance of {@link WorkflowDefinition} to be used to execute a * decision. {@link #deleteWorkflowDefinition(WorkflowDefinition)} will be * called to release the instance after the decision. */ public abstract WorkflowDefinition getWorkflowDefinition(DecisionContext context) throws Exception; /** * Release resources associated to the instance of WorkflowDefinition * created through {@link #getWorkflowDefinition(DecisionContext)}. Note * that it is not going to delete WorkflowDefinition in SWF, just release * local resources at the end of a decision. */ public abstract void deleteWorkflowDefinition(WorkflowDefinition instance); public abstract WorkflowType getWorkflowType(); }
3,618
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/generic/StartWorkflowExecutionParameters.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.generic; import com.amazonaws.services.simpleworkflow.flow.StartWorkflowOptions; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.model.ChildPolicy; import com.amazonaws.services.simpleworkflow.model.WorkflowType; public class StartWorkflowExecutionParameters { private String workflowId; private WorkflowType workflowType; private String taskList; private String input; private long executionStartToCloseTimeoutSeconds = FlowConstants.USE_REGISTERED_DEFAULTS; private long taskStartToCloseTimeoutSeconds = FlowConstants.USE_REGISTERED_DEFAULTS; private java.util.List<String> tagList; private int taskPriority; private String lambdaRole; private ChildPolicy childPolicy; /** * Returns the value of the WorkflowId property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>1 - 64 * * @return The value of the WorkflowId property for this object. */ public String getWorkflowId() { return workflowId; } /** * Sets the value of the WorkflowId property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>1 - 64 * * @param workflowId The new value for the WorkflowId property for this object. */ public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } /** * Sets the value of the WorkflowId property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b> * <b>Length: </b>1 - 64 * * @param workflowId The new value for the WorkflowId property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public StartWorkflowExecutionParameters withWorkflowId(String workflowId) { this.workflowId = workflowId; return this; } /** * Returns the value of the WorkflowType property for this object. * * @return The value of the WorkflowType property for this object. */ public WorkflowType getWorkflowType() { return workflowType; } /** * Sets the value of the WorkflowType property for this object. * * @param workflowType The new value for the WorkflowType property for this object. */ public void setWorkflowType(WorkflowType workflowType) { this.workflowType = workflowType; } /** * Sets the value of the WorkflowType property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param workflowType The new value for the WorkflowType property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public StartWorkflowExecutionParameters withWorkflowType(WorkflowType workflowType) { this.workflowType = workflowType; return this; } /** * Returns the value of the TaskList property for this object. * * @return The value of the TaskList property for this object. */ public String getTaskList() { return taskList; } /** * Sets the value of the TaskList property for this object. * * @param taskList The new value for the TaskList property for this object. */ public void setTaskList(String taskList) { this.taskList = taskList; } /** * Sets the value of the TaskList property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param taskList The new value for the TaskList property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public StartWorkflowExecutionParameters withTaskList(String taskList) { this.taskList = taskList; return this; } /** * Returns the value of the Input property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 100000 * * @return The value of the Input property for this object. */ public String getInput() { return input; } /** * Sets the value of the Input property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 100000 * * @param input The new value for the Input property for this object. */ public void setInput(String input) { this.input = input; } /** * Sets the value of the Input property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 100000 * * @param input The new value for the Input property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public StartWorkflowExecutionParameters withInput(String input) { this.input = input; return this; } /** * Returns the value of the StartToCloseTimeout property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 64 * * @return The value of the StartToCloseTimeout property for this object. */ public long getExecutionStartToCloseTimeout() { return executionStartToCloseTimeoutSeconds; } /** * Sets the value of the StartToCloseTimeout property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 64 * * @param executionStartToCloseTimeoutSeconds The new value for the StartToCloseTimeout property for this object. */ public void setExecutionStartToCloseTimeoutSeconds(long executionStartToCloseTimeoutSeconds) { this.executionStartToCloseTimeoutSeconds = executionStartToCloseTimeoutSeconds; } /** * Sets the value of the StartToCloseTimeout property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 64 * * @param executionStartToCloseTimeoutSeconds The new value for the StartToCloseTimeout property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public StartWorkflowExecutionParameters withExecutionStartToCloseTimeoutSeconds(long executionStartToCloseTimeoutSeconds) { this.executionStartToCloseTimeoutSeconds = executionStartToCloseTimeoutSeconds; return this; } public long getTaskStartToCloseTimeoutSeconds() { return taskStartToCloseTimeoutSeconds; } public void setTaskStartToCloseTimeoutSeconds(long taskStartToCloseTimeoutSeconds) { this.taskStartToCloseTimeoutSeconds = taskStartToCloseTimeoutSeconds; } public StartWorkflowExecutionParameters withTaskStartToCloseTimeoutSeconds(long taskStartToCloseTimeoutSeconds) { this.taskStartToCloseTimeoutSeconds = taskStartToCloseTimeoutSeconds; return this; } public ChildPolicy getChildPolicy() { return childPolicy; } public void setChildPolicy(ChildPolicy childPolicy) { this.childPolicy = childPolicy; } public StartWorkflowExecutionParameters withChildPolicy(ChildPolicy childPolicy) { this.childPolicy = childPolicy; return this; } /** * Returns the value of the TagList property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 5 * * @return The value of the TagList property for this object. */ public java.util.List<String> getTagList() { if (tagList == null) { tagList = new java.util.ArrayList<String>(); } return tagList; } /** * Sets the value of the TagList property for this object. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 5 * * @param tagList The new value for the TagList property for this object. */ public void setTagList(java.util.Collection<String> tagList) { java.util.List<String> tagListCopy = new java.util.ArrayList<String>(); if (tagList != null) { tagListCopy.addAll(tagList); } this.tagList = tagListCopy; } /** * Sets the value of the TagList property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 5 * * @param tagList The new value for the TagList property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public StartWorkflowExecutionParameters withTagList(String... tagList) { for (String value : tagList) { getTagList().add(value); } return this; } /** * Sets the value of the TagList property for this object. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b> * <b>Length: </b>0 - 5 * * @param tagList The new value for the TagList property for this object. * * @return A reference to this updated object so that method calls can be chained * together. */ public StartWorkflowExecutionParameters withTagList(java.util.Collection<String> tagList) { java.util.List<String> tagListCopy = new java.util.ArrayList<String>(); if (tagList != null) { tagListCopy.addAll(tagList); } this.tagList = tagListCopy; return this; } public int getTaskPriority() { return taskPriority; } public void setTaskPriority(int taskPriority) { this.taskPriority = taskPriority; } public StartWorkflowExecutionParameters withTaskPriority(int taskPriority) { this.taskPriority = taskPriority; return this; } public String getLambdaRole() { return lambdaRole; } public void setLambdaRole(String lambdaRole) { this.lambdaRole = lambdaRole; } public StartWorkflowExecutionParameters withLambdaRole(String lambdaRole) { this.lambdaRole = lambdaRole; return this; } public StartWorkflowExecutionParameters createStartWorkflowExecutionParametersFromOptions(StartWorkflowOptions options, StartWorkflowOptions optionsOverride) { StartWorkflowExecutionParameters parameters = this.clone(); if (options != null) { Long executionStartToCloseTimeout = options.getExecutionStartToCloseTimeoutSeconds(); if (executionStartToCloseTimeout != null) { parameters.setExecutionStartToCloseTimeoutSeconds(executionStartToCloseTimeout); } Long taskStartToCloseTimeout = options.getTaskStartToCloseTimeoutSeconds(); if (taskStartToCloseTimeout != null) { parameters.setTaskStartToCloseTimeoutSeconds(taskStartToCloseTimeout); } java.util.Collection<String> tagList = options.getTagList(); if (tagList != null) { parameters.setTagList(tagList); } String taskList = options.getTaskList(); if (taskList != null && !taskList.isEmpty()) { parameters.setTaskList(taskList); } Integer taskPriority = options.getTaskPriority(); if (taskPriority != null) { parameters.setTaskPriority(taskPriority); } ChildPolicy childPolicy = options.getChildPolicy(); if (childPolicy != null) { parameters.setChildPolicy(childPolicy); } String lambdaRole = options.getLambdaRole(); if (lambdaRole != null && !lambdaRole.isEmpty()) { parameters.setLambdaRole(lambdaRole); } } if (optionsOverride != null) { Long executionStartToCloseTimeout = optionsOverride.getExecutionStartToCloseTimeoutSeconds(); if (executionStartToCloseTimeout != null) { parameters.setExecutionStartToCloseTimeoutSeconds(executionStartToCloseTimeout); } Long taskStartToCloseTimeout = optionsOverride.getTaskStartToCloseTimeoutSeconds(); if (taskStartToCloseTimeout != null) { parameters.setTaskStartToCloseTimeoutSeconds(taskStartToCloseTimeout); } java.util.Collection<String> tagList = optionsOverride.getTagList(); if (tagList != null) { parameters.setTagList(tagList); } String taskList = optionsOverride.getTaskList(); if (taskList != null && !taskList.isEmpty()) { parameters.setTaskList(taskList); } Integer taskPriority = optionsOverride.getTaskPriority(); if (taskPriority != null) { parameters.setTaskPriority(taskPriority); } ChildPolicy childPolicy = optionsOverride.getChildPolicy(); if (childPolicy != null) { parameters.setChildPolicy(childPolicy); } String lambdaRole = optionsOverride.getLambdaRole(); if (lambdaRole != null && !lambdaRole.isEmpty()) { parameters.setLambdaRole(lambdaRole); } } return parameters; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("WorkflowId: " + workflowId + ", "); sb.append("WorkflowType: " + workflowType + ", "); sb.append("TaskList: " + taskList + ", "); sb.append("Input: " + input + ", "); sb.append("StartToCloseTimeout: " + executionStartToCloseTimeoutSeconds + ", "); sb.append("TagList: " + tagList + ", "); sb.append("TaskPriority: " + taskPriority + ", "); sb.append("ChildPolicy: " + childPolicy + ", "); sb.append("LambdaRole: " + lambdaRole + ", "); sb.append("}"); return sb.toString(); } public StartWorkflowExecutionParameters clone() { StartWorkflowExecutionParameters result = new StartWorkflowExecutionParameters(); result.setInput(input); result.setExecutionStartToCloseTimeoutSeconds(executionStartToCloseTimeoutSeconds); result.setTaskStartToCloseTimeoutSeconds(taskStartToCloseTimeoutSeconds); result.setTagList(tagList); result.setTaskList(taskList); result.setWorkflowId(workflowId); result.setWorkflowType(workflowType); result.setTaskPriority(taskPriority); result.setChildPolicy(childPolicy); result.setLambdaRole(lambdaRole); return result; } }
3,619
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/generic/StartChildWorkflowReply.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.generic; import com.amazonaws.services.simpleworkflow.flow.core.Promise; public interface StartChildWorkflowReply { public String getWorkflowId(); public String getRunId(); public Promise<String> getResult(); }
3,620
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/worker/WorkflowContextImpl.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.worker; import java.util.List; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.WorkflowContext; import com.amazonaws.services.simpleworkflow.flow.common.FlowHelpers; import com.amazonaws.services.simpleworkflow.flow.generic.ContinueAsNewWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.model.ChildPolicy; import com.amazonaws.services.simpleworkflow.model.DecisionTask; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; import com.amazonaws.services.simpleworkflow.model.WorkflowExecutionStartedEventAttributes; import com.amazonaws.services.simpleworkflow.model.WorkflowType; class WorkflowContextImpl implements WorkflowContext { private final WorkflowClock clock; private final DecisionTask decisionTask; private boolean cancelRequested; private ContinueAsNewWorkflowExecutionParameters continueAsNewOnCompletion; private ComponentVersions componentVersions; /** * DecisionTaskPoller.next has an optimization to remove the history page * from the first decision task. This is to keep a handle on the started * event attributes in the first event for future access. */ private WorkflowExecutionStartedEventAttributes workflowStartedEventAttributes; public WorkflowContextImpl(DecisionTask decisionTask, WorkflowClock clock) { this.decisionTask = decisionTask; this.clock = clock; HistoryEvent firstHistoryEvent = decisionTask.getEvents().get(0); this.workflowStartedEventAttributes = firstHistoryEvent.getWorkflowExecutionStartedEventAttributes(); } @Override public WorkflowExecution getWorkflowExecution() { return decisionTask.getWorkflowExecution(); } @Override public WorkflowType getWorkflowType() { return decisionTask.getWorkflowType(); } @Override public boolean isCancelRequested() { return cancelRequested; } void setCancelRequested(boolean flag) { cancelRequested = flag; } @Override public ContinueAsNewWorkflowExecutionParameters getContinueAsNewOnCompletion() { return continueAsNewOnCompletion; } @Override public void setContinueAsNewOnCompletion(ContinueAsNewWorkflowExecutionParameters continueParameters) { this.continueAsNewOnCompletion = continueParameters; } @Override public WorkflowExecution getParentWorkflowExecution() { WorkflowExecutionStartedEventAttributes attributes = getWorkflowStartedEventAttributes(); return attributes.getParentWorkflowExecution(); } @Override public List<String> getTagList() { WorkflowExecutionStartedEventAttributes attributes = getWorkflowStartedEventAttributes(); return attributes.getTagList(); } @Override public ChildPolicy getChildPolicy() { WorkflowExecutionStartedEventAttributes attributes = getWorkflowStartedEventAttributes(); return ChildPolicy.fromValue(attributes.getChildPolicy()); } @Override public String getContinuedExecutionRunId() { WorkflowExecutionStartedEventAttributes attributes = getWorkflowStartedEventAttributes(); return attributes.getContinuedExecutionRunId(); } @Override public long getExecutionStartToCloseTimeout() { WorkflowExecutionStartedEventAttributes attributes = getWorkflowStartedEventAttributes(); String result = attributes.getExecutionStartToCloseTimeout(); return FlowHelpers.durationToSeconds(result); } @Override public String getTaskList() { WorkflowExecutionStartedEventAttributes attributes = getWorkflowStartedEventAttributes(); return attributes.getTaskList().getName(); } @Override public String getLambdaRole() { WorkflowExecutionStartedEventAttributes attributes = getWorkflowStartedEventAttributes(); return attributes.getLambdaRole(); } private WorkflowExecutionStartedEventAttributes getWorkflowStartedEventAttributes() { return workflowStartedEventAttributes; } @Override public int getTaskPriority() { WorkflowExecutionStartedEventAttributes attributes = getWorkflowStartedEventAttributes(); String result = attributes.getTaskPriority(); return FlowHelpers.taskPriorityToInt(result); } @Override public boolean isImplementationVersion(String component, int version) { return componentVersions.isVersion(component, version, clock.isReplaying()); } @Override public Integer getVersion(String component) { return componentVersions.getCurrentVersion(component); } void setComponentVersions(ComponentVersions componentVersions) { this.componentVersions = componentVersions; } }
3,621
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/worker/SignalDecisionStateMachine.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.worker; import com.amazonaws.services.simpleworkflow.model.Decision; import com.amazonaws.services.simpleworkflow.model.DecisionType; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.SignalExternalWorkflowExecutionDecisionAttributes; class SignalDecisionStateMachine extends DecisionStateMachineBase { private SignalExternalWorkflowExecutionDecisionAttributes attributes; private boolean canceled; public SignalDecisionStateMachine(DecisionId id, SignalExternalWorkflowExecutionDecisionAttributes attributes) { super(id); this.attributes = attributes; } /** * Used for unit testing */ SignalDecisionStateMachine(DecisionId id, SignalExternalWorkflowExecutionDecisionAttributes attributes, DecisionState state) { super(id, state); this.attributes = attributes; } @Override public Decision getDecision() { switch (state) { case CREATED: return createSignalExternalWorkflowExecutionDecision(); default: return null; } } @Override public boolean isDone() { return state == DecisionState.COMPLETED || canceled; } @Override public void handleDecisionTaskStartedEvent() { switch (state) { case CREATED: stateHistory.add("handleDecisionTaskStartedEvent"); state = DecisionState.DECISION_SENT; stateHistory.add(state.toString()); break; } } @Override public void cancel(Runnable immediateCancellationCallback) { stateHistory.add("cancel"); switch (state) { case CREATED: case INITIATED: state = DecisionState.COMPLETED; if (immediateCancellationCallback != null) { immediateCancellationCallback.run(); } break; case DECISION_SENT: state = DecisionState.CANCELED_BEFORE_INITIATED; if (immediateCancellationCallback != null) { immediateCancellationCallback.run(); } break; default: failStateTransition(); } canceled = true; stateHistory.add(state.toString()); } @Override public void handleInitiatedEvent(HistoryEvent event) { stateHistory.add("handleInitiatedEvent"); switch (state) { case DECISION_SENT: state = DecisionState.INITIATED; break; case CANCELED_BEFORE_INITIATED: // No state change break; default: failStateTransition(); } stateHistory.add(state.toString()); } @Override public void handleInitiationFailedEvent(HistoryEvent event) { throw new UnsupportedOperationException(); } @Override public void handleStartedEvent(HistoryEvent event) { throw new UnsupportedOperationException(); } @Override public void handleCompletionEvent() { stateHistory.add("handleCompletionEvent"); switch (state) { case DECISION_SENT: case INITIATED: case CANCELED_BEFORE_INITIATED: state = DecisionState.COMPLETED; break; case COMPLETED: // No state change break; default: failStateTransition(); } stateHistory.add(state.toString()); } @Override public void handleCancellationInitiatedEvent() { throw new UnsupportedOperationException(); } @Override public void handleCancellationFailureEvent(HistoryEvent event) { throw new UnsupportedOperationException(); } @Override public void handleCancellationEvent() { throw new UnsupportedOperationException(); } private Decision createSignalExternalWorkflowExecutionDecision() { Decision decision = new Decision(); decision.setSignalExternalWorkflowExecutionDecisionAttributes(attributes); decision.setDecisionType(DecisionType.SignalExternalWorkflowExecution.toString()); return decision; } }
3,622
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/worker/BlockCallerPolicy.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.worker; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; class BlockCallerPolicy implements RejectedExecutionHandler { private static final Log log = LogFactory.getLog(BlockCallerPolicy.class); @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { log.warn("Execution rejected. Blocking and adding to queue. Thread: " + Thread.currentThread().getName()); // block until there's room executor.getQueue().put(r); } catch (InterruptedException e) { throw new RejectedExecutionException("Unexpected InterruptedException", e); } } }
3,623
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/worker/LambdaFunctionClientImpl.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.worker; import java.util.HashMap; import java.util.Map; import com.amazonaws.services.simpleworkflow.flow.LambdaFunctionFailedException; import com.amazonaws.services.simpleworkflow.flow.LambdaFunctionTimedOutException; import com.amazonaws.services.simpleworkflow.flow.ScheduleLambdaFunctionFailedException; import com.amazonaws.services.simpleworkflow.flow.StartLambdaFunctionFailedException; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.flow.common.FlowHelpers; 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; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.LambdaFunctionCompletedEventAttributes; import com.amazonaws.services.simpleworkflow.model.LambdaFunctionFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.LambdaFunctionStartedEventAttributes; import com.amazonaws.services.simpleworkflow.model.LambdaFunctionTimedOutEventAttributes; import com.amazonaws.services.simpleworkflow.model.ScheduleLambdaFunctionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.ScheduleLambdaFunctionFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.StartLambdaFunctionFailedEventAttributes; public class LambdaFunctionClientImpl implements LambdaFunctionClient { private final class LambdaFunctionCancellationHandler implements ExternalTaskCancellationHandler { private final String lambdaId; private LambdaFunctionCancellationHandler(String lambdaId) { this.lambdaId = lambdaId; } @Override public void handleCancellation(Throwable cause) { // do not support cancellation } } private final DecisionsHelper decisions; private final Map<String, OpenRequestInfo<String, String>> scheduledLambdas = new HashMap<String, OpenRequestInfo<String, String>>(); public LambdaFunctionClientImpl(DecisionsHelper decisions) { this.decisions = decisions; } @Override public Promise<String> scheduleLambdaFunction(final String name, final String input) { return scheduleLambdaFunction(name, input, 0); } @Override public Promise<String> scheduleLambdaFunction(final String name, final Promise<String> input) { return scheduleLambdaFunction(name, input, 0); } @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 = decisions.getNextId(); return scheduleLambdaFunction(name, input, timeoutSeconds, functionId); } @Override public Promise<String> scheduleLambdaFunction(final String name, final String input, final long timeoutSeconds, final String functionId) { if (timeoutSeconds < 0) { throw new IllegalArgumentException("Negative timeoutSeconds: " + timeoutSeconds); } final OpenRequestInfo<String, String> context = new OpenRequestInfo<String, String>( name); final ScheduleLambdaFunctionDecisionAttributes attributes = new ScheduleLambdaFunctionDecisionAttributes(); attributes.setName(name); attributes.setInput(input); attributes.setId(functionId); if (timeoutSeconds == 0) { attributes .setStartToCloseTimeout(FlowHelpers .secondsToDuration(FlowConstants.DEFAULT_LAMBDA_FUNCTION_TIMEOUT)); } else { attributes.setStartToCloseTimeout(FlowHelpers .secondsToDuration(timeoutSeconds)); } String taskName = "functionId=" + attributes.getId() + ", timeouts=" + attributes.getStartToCloseTimeout(); new ExternalTask() { @Override protected ExternalTaskCancellationHandler doExecute( ExternalTaskCompletionHandle handle) throws Throwable { decisions.scheduleLambdaFunction(attributes); context.setCompletionHandle(handle); scheduledLambdas.put(functionId, context); return new LambdaFunctionCancellationHandler(functionId); } }.setName(taskName); context.setResultDescription("createTimer " + taskName); return context.getResult(); } void handleLambdaFunctionStarted( LambdaFunctionStartedEventAttributes attributes) { } void handleStartLambdaFunctionFailed(HistoryEvent event) { StartLambdaFunctionFailedEventAttributes startLambdaFunctionFailedAttributes = event .getStartLambdaFunctionFailedEventAttributes(); String functionId = decisions.getFunctionId(startLambdaFunctionFailedAttributes); OpenRequestInfo<String, String> scheduled = scheduledLambdas.remove(functionId); if (decisions.handleStartLambdaFunctionFailed(event)) { String cause = startLambdaFunctionFailedAttributes.getCause(); StartLambdaFunctionFailedException failure = new StartLambdaFunctionFailedException(event.getEventId(), scheduled.getUserContext(), functionId, cause); ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); completionHandle.fail(failure); } } void handleScheduleLambdaFunctionFailed(HistoryEvent event) { ScheduleLambdaFunctionFailedEventAttributes attributes = event .getScheduleLambdaFunctionFailedEventAttributes(); String functionId = attributes.getId(); OpenRequestInfo<String, String> scheduled = scheduledLambdas .remove(functionId); if (decisions.handleScheduleLambdaFunctionFailed(event)) { String cause = attributes.getCause(); ScheduleLambdaFunctionFailedException failure = new ScheduleLambdaFunctionFailedException( event.getEventId(), attributes.getName(), functionId, cause); ExternalTaskCompletionHandle completionHandle = scheduled .getCompletionHandle(); completionHandle.fail(failure); } } void handleLambdaFunctionCompleted(HistoryEvent event) { LambdaFunctionCompletedEventAttributes attributes = event .getLambdaFunctionCompletedEventAttributes(); String lambdaId = decisions.getFunctionId(attributes); if (decisions.handleLambdaFunctionClosed(lambdaId)) { OpenRequestInfo<String, String> scheduled = scheduledLambdas .remove(lambdaId); if (scheduled != null) { String result = attributes.getResult(); scheduled.getResult().set(result); ExternalTaskCompletionHandle completionHandle = scheduled .getCompletionHandle(); completionHandle.complete(); } } } void handleLambdaFunctionFailed(HistoryEvent event) { LambdaFunctionFailedEventAttributes attributes = event .getLambdaFunctionFailedEventAttributes(); String functionId = decisions.getFunctionId(attributes); if (decisions.handleLambdaFunctionClosed(functionId)) { OpenRequestInfo<String, String> scheduled = scheduledLambdas .remove(functionId); if (scheduled != null) { String detail = attributes.getDetails(); LambdaFunctionFailedException failure = new LambdaFunctionFailedException( event.getEventId(), scheduled.getUserContext(), functionId, detail); ExternalTaskCompletionHandle completionHandle = scheduled .getCompletionHandle(); completionHandle.fail(failure); } } } void handleLambdaFunctionTimedOut(HistoryEvent event) { LambdaFunctionTimedOutEventAttributes attributes = event .getLambdaFunctionTimedOutEventAttributes(); String functionId = decisions.getFunctionId(attributes); if (decisions.handleLambdaFunctionClosed(functionId)) { OpenRequestInfo<String, String> scheduled = scheduledLambdas .remove(functionId); if (scheduled != null) { String timeoutType = attributes.getTimeoutType(); LambdaFunctionTimedOutException failure = new LambdaFunctionTimedOutException( event.getEventId(), scheduled.getUserContext(), functionId, timeoutType); ExternalTaskCompletionHandle completionHandle = scheduled .getCompletionHandle(); completionHandle.fail(failure); } } } }
3,624
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/worker/WorkflowClockImpl.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.worker; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CancellationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.amazonaws.services.simpleworkflow.flow.StartTimerFailedException; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.common.FlowHelpers; 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.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.StartTimerDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.StartTimerFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.TimerCanceledEventAttributes; import com.amazonaws.services.simpleworkflow.model.TimerFiredEventAttributes; class WorkflowClockImpl implements WorkflowClock { private static final Log log = LogFactory.getLog(WorkflowClockImpl.class); private final class TimerCancellationHandler implements ExternalTaskCancellationHandler { private final String timerId; private TimerCancellationHandler(String timerId) { this.timerId = timerId; } @Override public void handleCancellation(Throwable cause) { decisions.cancelTimer(timerId, new Runnable() { @Override public void run() { OpenRequestInfo<?, ?> scheduled = scheduledTimers.remove(timerId); ExternalTaskCompletionHandle context = scheduled.getCompletionHandle(); context.complete(); } }); } } private final DecisionsHelper decisions; private final Map<String, OpenRequestInfo<?, ?>> scheduledTimers = new HashMap<String, OpenRequestInfo<?, ?>>(); private long replayCurrentTimeMilliseconds; private boolean replaying = true; WorkflowClockImpl(DecisionsHelper decisions) { this.decisions = decisions; } @Override public long currentTimeMillis() { return replayCurrentTimeMilliseconds; } void setReplayCurrentTimeMilliseconds(long replayCurrentTimeMilliseconds) { this.replayCurrentTimeMilliseconds = replayCurrentTimeMilliseconds; } @Override public boolean isReplaying() { return replaying; } void setReplaying(boolean replaying) { this.replaying = replaying; } @Override public Promise<Void> createTimer(long delaySeconds) { return createTimer(delaySeconds, null); } @Override public <T> Promise<T> createTimer(final long delaySeconds, final T userContext) { final String timerId = decisions.getNextId(); return createTimer(delaySeconds, userContext, timerId); } @Override public <T> Promise<T> createTimer(final long delaySeconds, final T userContext, final String timerId) { if (delaySeconds < 0) { throw new IllegalArgumentException("Negative delaySeconds: " + delaySeconds); } if (delaySeconds == 0) { return Promise.asPromise(userContext); } final OpenRequestInfo<T, Object> context = new OpenRequestInfo<T, Object>(userContext); final StartTimerDecisionAttributes timer = new StartTimerDecisionAttributes(); timer.setStartToFireTimeout(FlowHelpers.secondsToDuration(delaySeconds)); timer.setTimerId(timerId); String taskName = "timerId=" + timer.getTimerId() + ", delaySeconds=" + timer.getStartToFireTimeout(); new ExternalTask() { @Override protected ExternalTaskCancellationHandler doExecute(ExternalTaskCompletionHandle handle) throws Throwable { decisions.startTimer(timer, userContext); context.setCompletionHandle(handle); scheduledTimers.put(timerId, context); return new TimerCancellationHandler(timerId); } }.setName(taskName); context.setResultDescription("createTimer " + taskName); return context.getResult(); } @SuppressWarnings({ "rawtypes", "unchecked" }) void handleTimerFired(Long eventId, TimerFiredEventAttributes attributes) { String timerId = attributes.getTimerId(); if (decisions.handleTimerClosed(timerId)) { OpenRequestInfo scheduled = scheduledTimers.remove(timerId); if (scheduled != null) { ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); scheduled.getResult().set(scheduled.getUserContext()); completionHandle.complete(); } } else { log.debug("handleTimerFired not complete"); } } @SuppressWarnings({ "rawtypes" }) void handleStartTimerFailed(HistoryEvent event) { StartTimerFailedEventAttributes attributes = event.getStartTimerFailedEventAttributes(); String timerId = attributes.getTimerId(); if (decisions.handleStartTimerFailed(event)) { OpenRequestInfo scheduled = scheduledTimers.remove(timerId); if (scheduled != null) { ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); Object createTimerUserContext = scheduled.getUserContext(); String cause = attributes.getCause(); Throwable failure = new StartTimerFailedException(event.getEventId(), timerId, createTimerUserContext, cause); completionHandle.fail(failure); } } else { log.debug("handleStartTimerFailed not complete"); } } void handleTimerCanceled(HistoryEvent event) { TimerCanceledEventAttributes attributes = event.getTimerCanceledEventAttributes(); String timerId = attributes.getTimerId(); if (decisions.handleTimerCanceled(event)) { OpenRequestInfo<?, ?> scheduled = scheduledTimers.remove(timerId); if (scheduled != null) { ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); CancellationException exception = new CancellationException(); completionHandle.fail(exception); } } else { log.debug("handleTimerCanceled not complete"); } } }
3,625
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/worker/TaskPoller.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.worker; /** * This interface is for internal use only and may be changed or removed without prior notice. */ public interface TaskPoller<T> { T poll() throws InterruptedException; void execute(T task) throws Exception; void suspend(); void resume(); boolean isSuspended(); SuspendableSemaphore getPollingSemaphore(); }
3,626
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/worker/ActivityTaskPoller.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.worker; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.management.ManagementFactory; import java.util.concurrent.CancellationException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContext; import com.amazonaws.services.simpleworkflow.flow.ActivityFailureException; import com.amazonaws.services.simpleworkflow.flow.common.FlowValueConstraint; import com.amazonaws.services.simpleworkflow.flow.common.RequestTimeoutHelper; import com.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils; import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig; import com.amazonaws.services.simpleworkflow.flow.generic.ActivityImplementation; import com.amazonaws.services.simpleworkflow.flow.retry.SynchronousRetrier; import com.amazonaws.services.simpleworkflow.model.ActivityType; import com.amazonaws.services.simpleworkflow.model.PollForActivityTaskRequest; import com.amazonaws.services.simpleworkflow.model.RespondActivityTaskCanceledRequest; import com.amazonaws.services.simpleworkflow.model.RespondActivityTaskCompletedRequest; import com.amazonaws.services.simpleworkflow.model.RespondActivityTaskFailedRequest; import com.amazonaws.services.simpleworkflow.model.TaskList; import com.amazonaws.services.simpleworkflow.model.UnknownResourceException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.generic.ActivityImplementationFactory; import com.amazonaws.services.simpleworkflow.model.ActivityTask; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; /** * This class is for internal use only and may be changed or removed without prior notice. * */ public class ActivityTaskPoller implements TaskPoller<ActivityTask> { private static final Log log = LogFactory.getLog(ActivityTaskPoller.class); private SuspendableSemaphore pollSemaphore; private UncaughtExceptionHandler uncaughtExceptionHandler; private static final long SECOND = 1000; private AmazonSimpleWorkflow service; private String domain; private String taskListToPoll; private ActivityImplementationFactory activityImplementationFactory; private String identity; private boolean initialized; private boolean suspended; private final Lock lock = new ReentrantLock(); private final Condition suspentionCondition = lock.newCondition(); private SimpleWorkflowClientConfig config; public ActivityTaskPoller() { identity = ManagementFactory.getRuntimeMXBean().getName(); int length = Math.min(identity.length(), GenericWorker.MAX_IDENTITY_LENGTH); identity = identity.substring(0, length); } public ActivityTaskPoller(AmazonSimpleWorkflow service, String domain, String pollTaskList, ActivityImplementationFactory activityImplementationFactory) { this(service, domain, pollTaskList, activityImplementationFactory, null); } public ActivityTaskPoller(AmazonSimpleWorkflow service, String domain, String pollTaskList, ActivityImplementationFactory activityImplementationFactory, SimpleWorkflowClientConfig config) { this(); this.service = service; this.domain = domain; this.taskListToPoll = pollTaskList; this.activityImplementationFactory = activityImplementationFactory; this.config = config; } public ActivityTaskPoller(AmazonSimpleWorkflow service, String domain, String pollTaskList, ActivityImplementationFactory activityImplementationFactory, int executeThreadCount, SimpleWorkflowClientConfig config) { this(service, domain, pollTaskList, activityImplementationFactory, config); pollSemaphore = new SuspendableSemaphore(executeThreadCount); } public AmazonSimpleWorkflow getService() { return service; } public void setService(AmazonSimpleWorkflow service) { this.service = service; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getPollTaskList() { return taskListToPoll; } public void setTaskListToPoll(String taskList) { this.taskListToPoll = taskList; } public ActivityImplementationFactory getActivityImplementationFactory() { return activityImplementationFactory; } public void setActivityImplementationFactory(ActivityImplementationFactory activityImplementationFactory) { this.activityImplementationFactory = activityImplementationFactory; } public String getIdentity() { return identity; } public void setIdentity(String identity) { this.identity = identity; } public String getTaskListToPoll() { return taskListToPoll; } public UncaughtExceptionHandler getUncaughtExceptionHandler() { return uncaughtExceptionHandler; } public void setUncaughtExceptionHandler(UncaughtExceptionHandler uncaughtExceptionHandler) { this.uncaughtExceptionHandler = uncaughtExceptionHandler; } private Exception wrapFailure(final ActivityTask task, Throwable failure) { WorkflowExecution execution = task.getWorkflowExecution(); RuntimeException e2 = new RuntimeException( "Failure taskId=\"" + task.getStartedEventId() + "\" workflowExecutionRunId=\"" + execution.getRunId() + "\" workflowExecutionId=\"" + execution.getWorkflowId() + "\"", failure); return e2; } @Override public ActivityTask poll() throws InterruptedException { waitIfSuspended(); if (!initialized) { checkRequiredProperty(service, "service"); checkRequiredProperty(domain, "domain"); checkRequiredProperty(taskListToPoll, "taskListToPoll"); initialized = true; } PollForActivityTaskRequest pollRequest = new PollForActivityTaskRequest(); pollRequest.setDomain(domain); pollRequest.setIdentity(identity); pollRequest.setTaskList(new TaskList().withName(taskListToPoll)); if (log.isDebugEnabled()) { log.debug("poll request begin: " + pollRequest); } RequestTimeoutHelper.overridePollRequestTimeout(pollRequest, config); ActivityTask result = service.pollForActivityTask(pollRequest); if (result == null || result.getTaskToken() == null) { if (log.isDebugEnabled()) { log.debug("poll request returned no task"); } return null; } if (log.isTraceEnabled()) { log.trace("poll request returned " + result); } return result; } @Override public void execute(ActivityTask task) throws Exception { String output = null; ActivityType activityType = task.getActivityType(); ActivityExecutionContext context = new ActivityExecutionContextImpl(service, domain, task, config); ActivityTypeExecutionOptions executionOptions = null; try { ActivityImplementation activityImplementation = activityImplementationFactory.getActivityImplementation(activityType); if (activityImplementation == null) { Iterable<ActivityType> typesToRegister = activityImplementationFactory.getActivityTypesToRegister(); StringBuilder types = new StringBuilder(); types.append("["); for (ActivityType t : typesToRegister) { if (types.length() > 1) { types.append(", "); } types.append(t); } types.append("]"); throw new ActivityFailureException("Activity type \"" + activityType + "\" is not supported by the ActivityWorker. " + "Possible cause is activity type version change without changing task list name. " + "Activity types registered with the worker are: " + types.toString()); } executionOptions = activityImplementation.getExecutionOptions(); output = activityImplementation.execute(context); } catch (CancellationException e) { respondActivityTaskCanceledWithRetry(task.getTaskToken(), null, executionOptions); return; } catch (ActivityFailureException e) { if (log.isErrorEnabled()) { log.error("Failure processing activity task with taskId=" + task.getStartedEventId() + ", workflowGenerationId=" + task.getWorkflowExecution().getWorkflowId() + ", activity=" + activityType + ", activityInstanceId=" + task.getActivityId(), e); } respondActivityTaskFailedWithRetry(task.getTaskToken(), e.getReason(), e.getDetails(), executionOptions); return; } catch (Exception e) { if (log.isErrorEnabled()) { log.error("Failure processing activity task with taskId=" + task.getStartedEventId() + ", workflowGenerationId=" + task.getWorkflowExecution().getWorkflowId() + ", activity=" + activityType + ", activityInstanceId=" + task.getActivityId(), e); } String reason = e.getMessage(); StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String details = sw.toString(); if (details.length() > FlowValueConstraint.FAILURE_DETAILS.getMaxSize()) { log.warn("Length of details is over maximum input length of 32768. Actual details: " + details + "when processing activity task with taskId=" + task.getStartedEventId() + ", workflowGenerationId=" + task.getWorkflowExecution().getWorkflowId() + ", activity=" + activityType + ", activityInstanceId=" + task.getActivityId()); details = WorkflowExecutionUtils.truncateDetails(details); } respondActivityTaskFailedWithRetry(task.getTaskToken(), reason, details, executionOptions); return; } if (executionOptions == null || !executionOptions.isManualActivityCompletion()) { respondActivityTaskCompletedWithRetry(task.getTaskToken(), output, executionOptions); } } private void waitIfSuspended() throws InterruptedException { lock.lock(); try { while (suspended) { suspentionCondition.await(); } } finally { lock.unlock(); } } @Override public void suspend() { lock.lock(); try { suspended = true; } finally { lock.unlock(); } } @Override public void resume() { lock.lock(); try { suspended = false; suspentionCondition.signalAll(); } finally { lock.unlock(); } } @Override public boolean isSuspended() { lock.lock(); try { return suspended; } finally { lock.unlock(); } } @Override public SuspendableSemaphore getPollingSemaphore() { return pollSemaphore; } protected void checkRequiredProperty(Object value, String name) { if (value == null) { throw new IllegalStateException("required property " + name + " is not set"); } } protected void respondActivityTaskFailed(String taskToken, String reason, String details) { RespondActivityTaskFailedRequest failedResponse = new RespondActivityTaskFailedRequest(); failedResponse.setTaskToken(taskToken); failedResponse.setReason(WorkflowExecutionUtils.truncateReason(reason)); failedResponse.setDetails(details); RequestTimeoutHelper.overrideDataPlaneRequestTimeout(failedResponse, config); service.respondActivityTaskFailed(failedResponse); } protected void respondActivityTaskCanceledWithRetry(final String taskToken, final String details, ActivityTypeExecutionOptions executionOptions) { SynchronousRetrier retrier = null; if (executionOptions != null) { ActivityTypeCompletionRetryOptions completionRetryOptions = executionOptions.getCompletionRetryOptions(); retrier = createRetrier(completionRetryOptions); } if (retrier != null) { retrier.retry(new Runnable() { @Override public void run() { respondActivityTaskCanceled(taskToken, details); } }); } else { respondActivityTaskCanceled(taskToken, details); } } private SynchronousRetrier createRetrier(ActivityTypeCompletionRetryOptions activityTypeCompletionRetryOptions) { if (activityTypeCompletionRetryOptions == null) { return null; } ExponentialRetryParameters retryParameters = new ExponentialRetryParameters(); retryParameters.setBackoffCoefficient(activityTypeCompletionRetryOptions.getBackoffCoefficient()); retryParameters.setExpirationInterval(activityTypeCompletionRetryOptions.getRetryExpirationSeconds() * SECOND); retryParameters.setInitialInterval(activityTypeCompletionRetryOptions.getInitialRetryIntervalSeconds() * SECOND); retryParameters.setMaximumRetries(activityTypeCompletionRetryOptions.getMaximumAttempts() - 1); retryParameters.setMaximumRetryInterval(activityTypeCompletionRetryOptions.getMaximumRetryIntervalSeconds() * SECOND); retryParameters.setMinimumRetries(activityTypeCompletionRetryOptions.getMinimumAttempts() - 1); SynchronousRetrier retrier = new SynchronousRetrier(retryParameters, UnknownResourceException.class); return retrier; } protected void respondActivityTaskCanceled(String taskToken, String details) { RespondActivityTaskCanceledRequest canceledResponse = new RespondActivityTaskCanceledRequest(); canceledResponse.setTaskToken(taskToken); canceledResponse.setDetails(details); RequestTimeoutHelper.overrideDataPlaneRequestTimeout(canceledResponse, config); service.respondActivityTaskCanceled(canceledResponse); } protected void respondActivityTaskCompletedWithRetry(final String taskToken, final String output, ActivityTypeExecutionOptions executionOptions) { SynchronousRetrier retrier = null; if (executionOptions != null) { retrier = createRetrier(executionOptions.getCompletionRetryOptions()); } if (retrier != null) { retrier.retry(new Runnable() { @Override public void run() { respondActivityTaskCompleted(taskToken, output); } }); } else { respondActivityTaskCompleted(taskToken, output); } } protected void respondActivityTaskCompleted(String taskToken, String output) { RespondActivityTaskCompletedRequest completedResponse = new RespondActivityTaskCompletedRequest(); completedResponse.setTaskToken(taskToken); completedResponse.setResult(output); RequestTimeoutHelper.overrideDataPlaneRequestTimeout(completedResponse, config); service.respondActivityTaskCompleted(completedResponse); } protected void respondActivityTaskFailedWithRetry(final String taskToken, final String reason, final String details, ActivityTypeExecutionOptions executionOptions) { SynchronousRetrier retrier = null; if (executionOptions != null) { retrier = createRetrier(executionOptions.getFailureRetryOptions()); } if (retrier != null) { retrier.retry(new Runnable() { @Override public void run() { respondActivityTaskFailed(taskToken, reason, details); } }); } else { respondActivityTaskFailed(taskToken, reason, details); } } }
3,627
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/worker/AsyncDecisionTaskHandler.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.worker; import com.amazonaws.services.simpleworkflow.flow.ChildWorkflowIdHandler; import com.amazonaws.services.simpleworkflow.flow.DefaultChildWorkflowIdHandler; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.amazonaws.services.simpleworkflow.flow.core.AsyncTaskInfo; 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.generic.WorkflowTypeComponentImplementationVersion; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowTypeImplementationOptions; import com.amazonaws.services.simpleworkflow.model.Decision; import com.amazonaws.services.simpleworkflow.model.DecisionTask; import com.amazonaws.services.simpleworkflow.model.RespondDecisionTaskCompletedRequest; import com.amazonaws.services.simpleworkflow.model.WorkflowType; /** * This class is for internal use only and may be changed or removed without prior notice. * */ public class AsyncDecisionTaskHandler extends DecisionTaskHandler { static final String COMPONENT_VERSION_MARKER = "*component_version*"; static final String COMPONENT_VERSION_RECORD_SEPARATOR = "\n"; static final String COMPONENT_VERSION_SEPARATOR = "\t"; static final String COMPONENT_VERSION_SEPARATORS_PATTERN = COMPONENT_VERSION_RECORD_SEPARATOR + "|" + COMPONENT_VERSION_SEPARATOR; private static final Log log = LogFactory.getLog(AsyncDecisionTaskHandler.class); private static final Log asyncThreadDumpLog = LogFactory.getLog(AsyncDecisionTaskHandler.class.getName() + ".waitingTasksStacks"); private final WorkflowDefinitionFactoryFactory definitionFactoryFactory; private final ChildWorkflowIdHandler childWorkflowIdHandler; private final boolean skipFailedCheck; public AsyncDecisionTaskHandler(WorkflowDefinitionFactoryFactory definitionFactoryFactory) { this(definitionFactoryFactory, false); } public AsyncDecisionTaskHandler(WorkflowDefinitionFactoryFactory definitionFactoryFactory, ChildWorkflowIdHandler childWorkflowIdHandler) { this(definitionFactoryFactory, false, childWorkflowIdHandler); } public AsyncDecisionTaskHandler(WorkflowDefinitionFactoryFactory definitionFactoryFactory, boolean skipFailedCheck) { this(definitionFactoryFactory, skipFailedCheck, null); } public AsyncDecisionTaskHandler(WorkflowDefinitionFactoryFactory definitionFactoryFactory, boolean skipFailedCheck, ChildWorkflowIdHandler childWorkflowIdHandler) { this.definitionFactoryFactory = definitionFactoryFactory; this.skipFailedCheck = skipFailedCheck; this.childWorkflowIdHandler = childWorkflowIdHandler != null ? childWorkflowIdHandler : new DefaultChildWorkflowIdHandler(); } @Override public RespondDecisionTaskCompletedRequest handleDecisionTask(Iterator<DecisionTask> decisionTaskIterator) throws Exception { HistoryHelper historyHelper = new HistoryHelper(decisionTaskIterator); AsyncDecider decider = createDecider(historyHelper); decider.decide(); DecisionsHelper decisionsHelper = decider.getDecisionsHelper(); Collection<Decision> decisions = decisionsHelper.getDecisions(); DecisionTask decisionTask = historyHelper.getDecisionTask(); if (log.isDebugEnabled()) { log.debug("WorkflowTask taskId=" + decisionTask.getStartedEventId() + ", taskToken=" + decisionTask.getTaskToken() + " completed with " + decisions.size() + " new decisions"); } if (decisions.size() == 0 && asyncThreadDumpLog.isTraceEnabled()) { asyncThreadDumpLog.trace("Empty decision list with the following waiting tasks:\n" + decider.getAsynchronousThreadDumpAsString()); } RespondDecisionTaskCompletedRequest completedRequest = new RespondDecisionTaskCompletedRequest(); completedRequest.setTaskToken(decisionTask.getTaskToken()); completedRequest.setDecisions(decisions); String contextData = decisionsHelper.getWorkflowContextDataToReturn(); ComponentVersions componentVersions = historyHelper.getComponentVersions(); Map<String, Integer> versionsToSave = componentVersions.getVersionsToSave(); String executionContext = getExecutionContext(contextData, versionsToSave); if (historyHelper.getWorkflowContextData() == null || !historyHelper.getWorkflowContextData().equals(executionContext)) { completedRequest.setExecutionContext(executionContext); } return completedRequest; } private String getExecutionContext(String contextData, Map<String, Integer> componentVersions) { int versionsSize = componentVersions.size(); if (versionsSize == 0 && contextData == null) { return null; } StringBuilder executionContext = new StringBuilder(); if (versionsSize > 0) { executionContext.append(COMPONENT_VERSION_MARKER); executionContext.append(COMPONENT_VERSION_SEPARATOR); executionContext.append(versionsSize); executionContext.append(COMPONENT_VERSION_RECORD_SEPARATOR); for (Entry<String, Integer> version : componentVersions.entrySet()) { executionContext.append(version.getKey()); executionContext.append(COMPONENT_VERSION_SEPARATOR); executionContext.append(version.getValue()); executionContext.append(COMPONENT_VERSION_RECORD_SEPARATOR); } } executionContext.append(contextData); return executionContext.toString(); } @Override public WorkflowDefinition loadWorkflowThroughReplay(Iterator<DecisionTask> decisionTaskIterator) throws Exception { HistoryHelper historyHelper = new HistoryHelper(decisionTaskIterator); AsyncDecider decider = createDecider(historyHelper); decider.decide(); DecisionsHelper decisionsHelper = decider.getDecisionsHelper(); if(!skipFailedCheck) { if (decisionsHelper.isWorkflowFailed()) { throw new IllegalStateException("Cannot load failed workflow", decisionsHelper.getWorkflowFailureCause()); } } return decider.getWorkflowDefinition(); } @Override public List<AsyncTaskInfo> getAsynchronousThreadDump(Iterator<DecisionTask> decisionTaskIterator) throws Exception { HistoryHelper historyHelper = new HistoryHelper(decisionTaskIterator); AsyncDecider decider = createDecider(historyHelper); decider.decide(); return decider.getAsynchronousThreadDump(); } @Override public String getAsynchronousThreadDumpAsString(Iterator<DecisionTask> decisionTaskIterator) throws Exception { HistoryHelper historyHelper = new HistoryHelper(decisionTaskIterator); AsyncDecider decider = createDecider(historyHelper); decider.decide(); return decider.getAsynchronousThreadDumpAsString(); } private AsyncDecider createDecider(HistoryHelper historyHelper) throws Exception { DecisionTask decisionTask = historyHelper.getDecisionTask(); WorkflowType workflowType = decisionTask.getWorkflowType(); if (log.isDebugEnabled()) { log.debug("WorkflowTask received: taskId=" + decisionTask.getStartedEventId() + ", taskToken=" + decisionTask.getTaskToken() + ", workflowExecution=" + decisionTask.getWorkflowExecution()); } WorkflowDefinitionFactory workflowDefinitionFactory = definitionFactoryFactory.getWorkflowDefinitionFactory(workflowType); if (workflowDefinitionFactory == null) { log.error("Received decision task for workflow type not configured with a worker: workflowType=" + decisionTask.getWorkflowType() + ", taskToken=" + decisionTask.getTaskToken() + ", workflowExecution=" + decisionTask.getWorkflowExecution()); Iterable<WorkflowType> typesToRegister = definitionFactoryFactory.getWorkflowTypesToRegister(); StringBuilder types = new StringBuilder(); types.append("["); for (WorkflowType t : typesToRegister) { if (types.length() > 1) { types.append(", "); } types.append(t); } types.append("]"); throw new IncompatibleWorkflowDefinition("Workflow type \"" + workflowType + "\" is not supported by the WorkflowWorker. " + "Possible cause is workflow type version change without changing task list name. " + "Workflow types registered by the worker are: " + types.toString()); } DecisionsHelper decisionsHelper = new DecisionsHelper(decisionTask, childWorkflowIdHandler); WorkflowTypeImplementationOptions workflowImplementationOptions = workflowDefinitionFactory.getWorkflowImplementationOptions(); if (workflowImplementationOptions != null) { List<WorkflowTypeComponentImplementationVersion> implementationComponentVersions = workflowImplementationOptions.getImplementationComponentVersions(); historyHelper.getComponentVersions().setWorkflowImplementationComponentVersions(implementationComponentVersions); } return new AsyncDecider(workflowDefinitionFactory, historyHelper, decisionsHelper); } }
3,628
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/worker/BackoffThrottler.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.worker; import java.util.concurrent.atomic.AtomicLong; /** * Used to throttle code execution in presence of failures using exponential * backoff logic. The formula used to calculate the next sleep interval is: * * <pre> * min(pow(backoffCoefficient, failureCount - 1) * initialSleep, maxSleep); * </pre> * <p> * Example usage: * * <pre> * BackoffThrottler throttler = new BackoffThrottler(1000, 60000, 2); * while(!stopped) { * try { * throttler.throttle(); * // some code that can fail and should be throttled * ... * throttler.success(); * } * catch (Exception e) { * throttler.failure(); * } * } * </pre> * * @author fateev */ public class BackoffThrottler { protected final long initialSleep; protected final long maxSleep; protected final double backoffCoefficient; protected final AtomicLong failureCount = new AtomicLong(); /** * Construct an instance of the throttler. * * @param initialSleep * time to sleep on the first failure * @param maxSleep * maximum time to sleep independently of number of failures * @param backoffCoefficient * coefficient used to calculate the next time to sleep. */ public BackoffThrottler(long initialSleep, long maxSleep, double backoffCoefficient) { this.initialSleep = initialSleep; this.maxSleep = maxSleep; this.backoffCoefficient = backoffCoefficient; } protected long calculateSleepTime() { double sleepMillis = (Math.pow(backoffCoefficient, failureCount.get() - 1)) * initialSleep; return Math.min((long) sleepMillis, maxSleep); } /** * Sleep if there were failures since the last success call. * * @throws InterruptedException */ public void throttle() throws InterruptedException { if (failureCount.get() > 0) { Thread.sleep(calculateSleepTime()); } } /** * Resent failure count to 0. */ public void success() { failureCount.set(0); } /** * Increment failure count. */ public void failure() { failureCount.incrementAndGet(); } }
3,629
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/worker/DecisionsHelper.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.worker; import com.amazonaws.services.simpleworkflow.flow.ChildWorkflowIdHandler; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.amazonaws.services.simpleworkflow.flow.WorkflowException; import com.amazonaws.services.simpleworkflow.flow.common.FlowHelpers; import com.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils; import com.amazonaws.services.simpleworkflow.flow.generic.ContinueAsNewWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.model.ActivityTaskCancelRequestedEventAttributes; import com.amazonaws.services.simpleworkflow.model.ActivityTaskCanceledEventAttributes; import com.amazonaws.services.simpleworkflow.model.ActivityTaskCompletedEventAttributes; import com.amazonaws.services.simpleworkflow.model.ActivityTaskFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.ActivityTaskScheduledEventAttributes; import com.amazonaws.services.simpleworkflow.model.ActivityTaskTimedOutEventAttributes; import com.amazonaws.services.simpleworkflow.model.CancelTimerFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.CancelWorkflowExecutionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.ChildPolicy; import com.amazonaws.services.simpleworkflow.model.ChildWorkflowExecutionStartedEventAttributes; import com.amazonaws.services.simpleworkflow.model.CompleteWorkflowExecutionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.ContinueAsNewWorkflowExecutionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.Decision; import com.amazonaws.services.simpleworkflow.model.DecisionTask; import com.amazonaws.services.simpleworkflow.model.DecisionTaskCompletedEventAttributes; import com.amazonaws.services.simpleworkflow.model.DecisionType; import com.amazonaws.services.simpleworkflow.model.FailWorkflowExecutionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.LambdaFunctionCompletedEventAttributes; import com.amazonaws.services.simpleworkflow.model.LambdaFunctionFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.LambdaFunctionScheduledEventAttributes; import com.amazonaws.services.simpleworkflow.model.LambdaFunctionTimedOutEventAttributes; import com.amazonaws.services.simpleworkflow.model.RequestCancelActivityTaskFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.RequestCancelExternalWorkflowExecutionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.RequestCancelExternalWorkflowExecutionFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.RequestCancelExternalWorkflowExecutionInitiatedEventAttributes; import com.amazonaws.services.simpleworkflow.model.ScheduleActivityTaskDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.ScheduleActivityTaskFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.ScheduleLambdaFunctionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.ScheduleLambdaFunctionFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.SignalExternalWorkflowExecutionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.SignalExternalWorkflowExecutionInitiatedEventAttributes; import com.amazonaws.services.simpleworkflow.model.StartChildWorkflowExecutionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.StartChildWorkflowExecutionFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.StartChildWorkflowExecutionInitiatedEventAttributes; import com.amazonaws.services.simpleworkflow.model.StartLambdaFunctionFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.StartTimerDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.StartTimerFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.TaskList; import com.amazonaws.services.simpleworkflow.model.TimerCanceledEventAttributes; import com.amazonaws.services.simpleworkflow.model.TimerStartedEventAttributes; class DecisionsHelper { static final int MAXIMUM_DECISIONS_PER_COMPLETION = 100; static final String FORCE_IMMEDIATE_DECISION_TIMER = "FORCE_IMMEDIATE_DECISION"; private final DecisionTask task; private final ChildWorkflowIdHandler childWorkflowIdHandler; private long idCounter; private final Map<Long, String> activitySchedulingEventIdToActivityId = new HashMap<Long, String>(); private final Map<Long, String> signalInitiatedEventIdToSignalId = new HashMap<Long, String>(); private final Map<Long, String> lambdaSchedulingEventIdToLambdaId = new HashMap<Long, String>(); private final Map<String, String> childWorkflowRequestedToActualWorkflowId = new HashMap<String, String>(); /** * Use access-order to ensure that decisions are emitted in order of their * creation */ private final Map<DecisionId, DecisionStateMachine> decisions = new LinkedHashMap<DecisionId, DecisionStateMachine>(100, 0.75f, true); private Throwable workflowFailureCause; private String workflowContextData; private String workflowContextFromLastDecisionCompletion; DecisionsHelper(DecisionTask task, ChildWorkflowIdHandler childWorkflowIdHandler) { this.task = task; this.childWorkflowIdHandler = childWorkflowIdHandler; } void scheduleLambdaFunction(ScheduleLambdaFunctionDecisionAttributes schedule) { DecisionId decisionId = new DecisionId(DecisionTarget.LAMBDA_FUNCTION, schedule.getId()); addDecision(decisionId, new LambdaFunctionDecisionStateMachine(decisionId, schedule)); } /** * @return * @return true if cancellation already happened as schedule event was found * in the new decisions list */ boolean requestCancelLambdaFunction(String lambdaId, Runnable immediateCancellationCallback) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.LAMBDA_FUNCTION, lambdaId)); decision.cancel(immediateCancellationCallback); return decision.isDone(); } boolean handleLambdaFunctionClosed(String lambdaId) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.LAMBDA_FUNCTION, lambdaId)); decision.handleCompletionEvent(); return decision.isDone(); } boolean handleLambdaFunctionScheduled(HistoryEvent event) { LambdaFunctionScheduledEventAttributes attributes = event.getLambdaFunctionScheduledEventAttributes(); String functionId = attributes.getId(); lambdaSchedulingEventIdToLambdaId.put(event.getEventId(), functionId); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.LAMBDA_FUNCTION, functionId), event); decision.handleInitiatedEvent(event); return decision.isDone(); } public boolean handleScheduleLambdaFunctionFailed(HistoryEvent event) { ScheduleLambdaFunctionFailedEventAttributes attributes = event.getScheduleLambdaFunctionFailedEventAttributes(); String functionId = attributes.getId(); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.LAMBDA_FUNCTION, functionId), event); decision.handleInitiationFailedEvent(event); return decision.isDone(); } public boolean handleStartLambdaFunctionFailed(HistoryEvent event) { StartLambdaFunctionFailedEventAttributes attributes = event.getStartLambdaFunctionFailedEventAttributes(); String functionId = getFunctionId(attributes); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.LAMBDA_FUNCTION, functionId), event); decision.handleInitiationFailedEvent(event); return decision.isDone(); } void scheduleActivityTask(ScheduleActivityTaskDecisionAttributes schedule) { DecisionId decisionId = new DecisionId(DecisionTarget.ACTIVITY, schedule.getActivityId()); addDecision(decisionId, new ActivityDecisionStateMachine(decisionId, schedule)); } /** * @return * @return true if cancellation already happened as schedule event was found * in the new decisions list */ boolean requestCancelActivityTask(String activityId, Runnable immediateCancellationCallback) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.ACTIVITY, activityId)); decision.cancel(immediateCancellationCallback); return decision.isDone(); } boolean handleActivityTaskClosed(String activityId) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.ACTIVITY, activityId)); decision.handleCompletionEvent(); return decision.isDone(); } boolean handleActivityTaskScheduled(HistoryEvent event) { ActivityTaskScheduledEventAttributes attributes = event.getActivityTaskScheduledEventAttributes(); String activityId = attributes.getActivityId(); activitySchedulingEventIdToActivityId.put(event.getEventId(), activityId); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.ACTIVITY, activityId), event); decision.handleInitiatedEvent(event); return decision.isDone(); } public boolean handleScheduleActivityTaskFailed(HistoryEvent event) { ScheduleActivityTaskFailedEventAttributes attributes = event.getScheduleActivityTaskFailedEventAttributes(); String activityId = attributes.getActivityId(); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.ACTIVITY, activityId), event); decision.handleInitiationFailedEvent(event); return decision.isDone(); } boolean handleActivityTaskCancelRequested(HistoryEvent event) { ActivityTaskCancelRequestedEventAttributes attributes = event.getActivityTaskCancelRequestedEventAttributes(); String activityId = attributes.getActivityId(); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.ACTIVITY, activityId), event); decision.handleCancellationInitiatedEvent(); return decision.isDone(); } public boolean handleActivityTaskCanceled(HistoryEvent event) { ActivityTaskCanceledEventAttributes attributes = event.getActivityTaskCanceledEventAttributes(); String activityId = getActivityId(attributes); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.ACTIVITY, activityId), event); decision.handleCancellationEvent(); return decision.isDone(); } boolean handleRequestCancelActivityTaskFailed(HistoryEvent event) { RequestCancelActivityTaskFailedEventAttributes attributes = event.getRequestCancelActivityTaskFailedEventAttributes(); String activityId = attributes.getActivityId(); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.ACTIVITY, activityId), event); decision.handleCancellationFailureEvent(event); return decision.isDone(); } void startChildWorkflowExecution(StartChildWorkflowExecutionDecisionAttributes schedule) { DecisionId decisionId = new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, schedule.getWorkflowId()); addDecision(decisionId, new ChildWorkflowDecisionStateMachine(decisionId, schedule)); } void handleStartChildWorkflowExecutionInitiated(HistoryEvent event) { StartChildWorkflowExecutionInitiatedEventAttributes attributes = event.getStartChildWorkflowExecutionInitiatedEventAttributes(); String actualWorkflowId = attributes.getWorkflowId(); String requestedWorkflowId = childWorkflowIdHandler.extractRequestedWorkflowId(actualWorkflowId); DecisionId originalDecisionId = new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, requestedWorkflowId); DecisionStateMachine decision = getDecision(originalDecisionId, event); if (!actualWorkflowId.equals(requestedWorkflowId)) { childWorkflowRequestedToActualWorkflowId.put(requestedWorkflowId, actualWorkflowId); decisions.remove(originalDecisionId); addDecision(new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, actualWorkflowId), decision); } decision.handleInitiatedEvent(event); } public boolean handleStartChildWorkflowExecutionFailed(HistoryEvent event) { StartChildWorkflowExecutionFailedEventAttributes attributes = event.getStartChildWorkflowExecutionFailedEventAttributes(); String actualWorkflowId = attributes.getWorkflowId(); String requestedWorkflowId = childWorkflowIdHandler.extractRequestedWorkflowId(actualWorkflowId); DecisionStateMachine decision; if (!actualWorkflowId.equals(requestedWorkflowId)) { childWorkflowRequestedToActualWorkflowId.put(requestedWorkflowId, actualWorkflowId); DecisionId originalDecisionId = new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, requestedWorkflowId); if (decisions.containsKey(originalDecisionId)) { // Canceled before initiated decision = decisions.remove(originalDecisionId); addDecision(new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, actualWorkflowId), decision); } else { decision = getDecision(new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, actualWorkflowId), event); } } else { decision = getDecision(new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, actualWorkflowId), event); } decision.handleInitiationFailedEvent(event); return decision.isDone(); } public void handleChildWorkflowExecutionStarted(HistoryEvent event) { ChildWorkflowExecutionStartedEventAttributes attributes = event.getChildWorkflowExecutionStartedEventAttributes(); String workflowId = attributes.getWorkflowExecution().getWorkflowId(); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, workflowId), event); decision.handleStartedEvent(event); } boolean handleChildWorkflowExecutionClosed(String workflowId) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, workflowId)); decision.handleCompletionEvent(); return decision.isDone(); } public void handleChildWorkflowExecutionCancelRequested(HistoryEvent event) { } public boolean handleChildWorkflowExecutionCanceled(String workflowId) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, workflowId)); decision.handleCancellationEvent(); return decision.isDone(); } /** * @return true if cancellation already happened as schedule event was found * in the new decisions list */ boolean requestCancelExternalWorkflowExecution(RequestCancelExternalWorkflowExecutionDecisionAttributes request, Runnable immediateCancellationCallback) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, request.getWorkflowId())); decision.cancel(immediateCancellationCallback); return decision.isDone(); } void handleRequestCancelExternalWorkflowExecutionInitiated(HistoryEvent event) { RequestCancelExternalWorkflowExecutionInitiatedEventAttributes attributes = event.getRequestCancelExternalWorkflowExecutionInitiatedEventAttributes(); String workflowId = attributes.getWorkflowId(); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, workflowId), event); decision.handleCancellationInitiatedEvent(); } void handleRequestCancelExternalWorkflowExecutionFailed(HistoryEvent event) { RequestCancelExternalWorkflowExecutionFailedEventAttributes attributes = event.getRequestCancelExternalWorkflowExecutionFailedEventAttributes(); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, attributes.getWorkflowId()), event); decision.handleCancellationFailureEvent(event); } void signalExternalWorkflowExecution(SignalExternalWorkflowExecutionDecisionAttributes signal) { DecisionId decisionId = new DecisionId(DecisionTarget.SIGNAL, signal.getControl()); addDecision(decisionId, new SignalDecisionStateMachine(decisionId, signal)); } void cancelSignalExternalWorkflowExecution(String signalId, Runnable immediateCancellationCallback) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.SIGNAL, signalId)); decision.cancel(immediateCancellationCallback); } void handleSignalExternalWorkflowExecutionInitiated(HistoryEvent event) { SignalExternalWorkflowExecutionInitiatedEventAttributes attributes = event.getSignalExternalWorkflowExecutionInitiatedEventAttributes(); String signalId = attributes.getControl(); signalInitiatedEventIdToSignalId.put(event.getEventId(), signalId); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.SIGNAL, signalId), event); decision.handleInitiatedEvent(event); } public boolean handleSignalExternalWorkflowExecutionFailed(String signalId) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.SIGNAL, signalId)); decision.handleCompletionEvent(); return decision.isDone(); } public boolean handleExternalWorkflowExecutionSignaled(String signalId) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.SIGNAL, signalId)); decision.handleCompletionEvent(); return decision.isDone(); } void startTimer(StartTimerDecisionAttributes request, Object createTimerUserContext) { String timerId = request.getTimerId(); DecisionId decisionId = new DecisionId(DecisionTarget.TIMER, timerId); addDecision(decisionId, new TimerDecisionStateMachine(decisionId, request)); } boolean cancelTimer(String timerId, Runnable immediateCancellationCallback) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.TIMER, timerId)); decision.cancel(immediateCancellationCallback); return decision.isDone(); } boolean handleTimerClosed(String timerId) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.TIMER, timerId)); decision.handleCompletionEvent(); return decision.isDone(); } boolean handleTimerStarted(HistoryEvent event) { TimerStartedEventAttributes attributes = event.getTimerStartedEventAttributes(); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.TIMER, attributes.getTimerId()), event); decision.handleInitiatedEvent(event); return decision.isDone(); } public boolean handleStartTimerFailed(HistoryEvent event) { StartTimerFailedEventAttributes attributes = event.getStartTimerFailedEventAttributes(); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.TIMER, attributes.getTimerId()), event); decision.handleInitiationFailedEvent(event); return decision.isDone(); } boolean handleTimerCanceled(HistoryEvent event) { TimerCanceledEventAttributes attributes = event.getTimerCanceledEventAttributes(); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.TIMER, attributes.getTimerId()), event); decision.handleCancellationEvent(); return decision.isDone(); } boolean handleCancelTimerFailed(HistoryEvent event) { CancelTimerFailedEventAttributes attributes = event.getCancelTimerFailedEventAttributes(); DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.TIMER, attributes.getTimerId()), event); decision.handleCancellationFailureEvent(event); return decision.isDone(); } void completeWorkflowExecution(String output) { Decision decision = new Decision(); CompleteWorkflowExecutionDecisionAttributes complete = new CompleteWorkflowExecutionDecisionAttributes(); complete.setResult(output); decision.setCompleteWorkflowExecutionDecisionAttributes(complete); decision.setDecisionType(DecisionType.CompleteWorkflowExecution.toString()); DecisionId decisionId = new DecisionId(DecisionTarget.SELF, null); addDecision(decisionId, new CompleteWorkflowStateMachine(decisionId, decision)); } void continueAsNewWorkflowExecution(ContinueAsNewWorkflowExecutionParameters continueParameters) { ContinueAsNewWorkflowExecutionDecisionAttributes attributes = new ContinueAsNewWorkflowExecutionDecisionAttributes(); attributes.setWorkflowTypeVersion(continueParameters.getWorkflowTypeVersion()); ChildPolicy childPolicy = continueParameters.getChildPolicy(); if (childPolicy != null) { attributes.setChildPolicy(childPolicy); } attributes.setInput(continueParameters.getInput()); attributes.setExecutionStartToCloseTimeout(FlowHelpers.secondsToDuration(continueParameters.getExecutionStartToCloseTimeoutSeconds())); attributes.setTaskStartToCloseTimeout(FlowHelpers.secondsToDuration(continueParameters.getTaskStartToCloseTimeoutSeconds())); attributes.setTaskPriority(FlowHelpers.taskPriorityToString(continueParameters.getTaskPriority())); List<String> tagList = continueParameters.getTagList(); if (tagList != null) { attributes.setTagList(tagList); } String taskList = continueParameters.getTaskList(); if (taskList != null && !taskList.isEmpty()) { attributes.setTaskList(new TaskList().withName(taskList)); } attributes.setLambdaRole(continueParameters.getLambdaRole()); Decision decision = new Decision(); decision.setDecisionType(DecisionType.ContinueAsNewWorkflowExecution.toString()); decision.setContinueAsNewWorkflowExecutionDecisionAttributes(attributes); DecisionId decisionId = new DecisionId(DecisionTarget.SELF, null); addDecision(decisionId, new CompleteWorkflowStateMachine(decisionId, decision)); } void failWorkflowExecution(Throwable e) { Decision decision = new Decision(); FailWorkflowExecutionDecisionAttributes fail = createFailWorkflowInstanceAttributes(e); decision.setFailWorkflowExecutionDecisionAttributes(fail); decision.setDecisionType(DecisionType.FailWorkflowExecution.toString()); DecisionId decisionId = new DecisionId(DecisionTarget.SELF, null); addDecision(decisionId, new CompleteWorkflowStateMachine(decisionId, decision)); workflowFailureCause = e; } void failWorkflowDueToUnexpectedError(Throwable e) { // To make sure that failure goes through do not make any other decisions decisions.clear(); this.failWorkflowExecution(e); } void handleCompleteWorkflowExecutionFailed(HistoryEvent event) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.SELF, null), event); decision.handleInitiationFailedEvent(event); } void handleFailWorkflowExecutionFailed(HistoryEvent event) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.SELF, null), event); decision.handleInitiationFailedEvent(event); } void handleCancelWorkflowExecutionFailed(HistoryEvent event) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.SELF, null), event); decision.handleInitiationFailedEvent(event); } void handleContinueAsNewWorkflowExecutionFailed(HistoryEvent event) { DecisionStateMachine decision = getDecision(new DecisionId(DecisionTarget.SELF, null), event); decision.handleInitiationFailedEvent(event); } /** * @return <code>false</code> means that cancel failed, <code>true</code> * that CancelWorkflowExecution was created. */ void cancelWorkflowExecution() { Decision decision = new Decision(); CancelWorkflowExecutionDecisionAttributes cancel = new CancelWorkflowExecutionDecisionAttributes(); cancel.setDetails(null); decision.setCancelWorkflowExecutionDecisionAttributes(cancel); decision.setDecisionType(DecisionType.CancelWorkflowExecution.toString()); DecisionId decisionId = new DecisionId(DecisionTarget.SELF, null); addDecision(decisionId, new CompleteWorkflowStateMachine(decisionId, decision)); } List<Decision> getDecisions() { List<Decision> result = new ArrayList<Decision>(MAXIMUM_DECISIONS_PER_COMPLETION + 1); for (DecisionStateMachine decisionStateMachine : decisions.values()) { Decision decision = decisionStateMachine.getDecision(); if (decision != null) { result.add(decision); } } // Include FORCE_IMMEDIATE_DECISION timer only if there are more then 100 events int size = result.size(); if (size > MAXIMUM_DECISIONS_PER_COMPLETION && !isCompletionEvent(result.get(MAXIMUM_DECISIONS_PER_COMPLETION - 2))) { result = result.subList(0, MAXIMUM_DECISIONS_PER_COMPLETION - 1); StartTimerDecisionAttributes attributes = new StartTimerDecisionAttributes(); attributes.setStartToFireTimeout("0"); attributes.setTimerId(FORCE_IMMEDIATE_DECISION_TIMER); Decision d = new Decision(); d.setStartTimerDecisionAttributes(attributes); d.setDecisionType(DecisionType.StartTimer.toString()); result.add(d); } return result; } private boolean isCompletionEvent(Decision decision) { DecisionType type = DecisionType.fromValue(decision.getDecisionType()); switch (type) { case CancelWorkflowExecution: case CompleteWorkflowExecution: case FailWorkflowExecution: case ContinueAsNewWorkflowExecution: return true; default: return false; } } public void handleDecisionTaskStartedEvent() { int count = 0; Iterator<DecisionStateMachine> iterator = decisions.values().iterator(); DecisionStateMachine next = null; DecisionStateMachine decisionStateMachine = getNextDecision(iterator); while (decisionStateMachine != null) { next = getNextDecision(iterator); if (++count == MAXIMUM_DECISIONS_PER_COMPLETION && next != null && !isCompletionEvent(next.getDecision())) { break; } decisionStateMachine.handleDecisionTaskStartedEvent(); decisionStateMachine = next; } if (next != null && count < MAXIMUM_DECISIONS_PER_COMPLETION) { next.handleDecisionTaskStartedEvent(); } } private DecisionStateMachine getNextDecision(Iterator<DecisionStateMachine> iterator) { DecisionStateMachine result = null; while (result == null && iterator.hasNext()) { result = iterator.next(); if (result.getDecision() == null) { result = null; } } return result; } @Override public String toString() { return WorkflowExecutionUtils.prettyPrintDecisions(getDecisions()); } boolean isWorkflowFailed() { return workflowFailureCause != null; } public Throwable getWorkflowFailureCause() { return workflowFailureCause; } String getWorkflowContextData() { return workflowContextData; } void setWorkflowContextData(String workflowState) { this.workflowContextData = workflowState; } /** * @return new workflow state or null if it didn't change since the last * decision completion */ String getWorkflowContextDataToReturn() { if (workflowContextFromLastDecisionCompletion == null || !workflowContextFromLastDecisionCompletion.equals(workflowContextData)) { return workflowContextData; } return null; } void handleDecisionCompletion(DecisionTaskCompletedEventAttributes decisionTaskCompletedEventAttributes) { workflowContextFromLastDecisionCompletion = decisionTaskCompletedEventAttributes.getExecutionContext(); } DecisionTask getTask() { return task; } String getActualChildWorkflowId(String requestedWorkflowId) { String result = childWorkflowRequestedToActualWorkflowId.get(requestedWorkflowId); return result == null ? requestedWorkflowId : result; } String getActivityId(ActivityTaskCanceledEventAttributes attributes) { Long sourceId = attributes.getScheduledEventId(); return activitySchedulingEventIdToActivityId.get(sourceId); } String getActivityId(ActivityTaskCompletedEventAttributes attributes) { Long sourceId = attributes.getScheduledEventId(); return activitySchedulingEventIdToActivityId.get(sourceId); } String getActivityId(ActivityTaskFailedEventAttributes attributes) { Long sourceId = attributes.getScheduledEventId(); return activitySchedulingEventIdToActivityId.get(sourceId); } String getActivityId(ActivityTaskTimedOutEventAttributes attributes) { Long sourceId = attributes.getScheduledEventId(); return activitySchedulingEventIdToActivityId.get(sourceId); } String getFunctionId(LambdaFunctionCompletedEventAttributes attributes) { Long sourceId = attributes.getScheduledEventId(); return lambdaSchedulingEventIdToLambdaId.get(sourceId); } String getFunctionId(LambdaFunctionFailedEventAttributes attributes) { Long sourceId = attributes.getScheduledEventId(); return lambdaSchedulingEventIdToLambdaId.get(sourceId); } String getFunctionId(LambdaFunctionTimedOutEventAttributes attributes) { Long sourceId = attributes.getScheduledEventId(); return lambdaSchedulingEventIdToLambdaId.get(sourceId); } String getFunctionId(StartLambdaFunctionFailedEventAttributes attributes) { Long sourceId = attributes.getScheduledEventId(); return lambdaSchedulingEventIdToLambdaId.get(sourceId); } String getSignalIdFromExternalWorkflowExecutionSignaled(long initiatedEventId) { return signalInitiatedEventIdToSignalId.get(initiatedEventId); } private FailWorkflowExecutionDecisionAttributes createFailWorkflowInstanceAttributes(Throwable failure) { String reason; String details; if (failure instanceof WorkflowException) { WorkflowException f = (WorkflowException) failure; reason = f.getReason(); details = f.getDetails(); } else { reason = failure.getMessage(); StringWriter sw = new StringWriter(); failure.printStackTrace(new PrintWriter(sw)); details = sw.toString(); } FailWorkflowExecutionDecisionAttributes result = new FailWorkflowExecutionDecisionAttributes(); result.setReason(WorkflowExecutionUtils.truncateReason(reason)); result.setDetails(WorkflowExecutionUtils.truncateDetails(details)); return result; } void addDecision(DecisionId decisionId, DecisionStateMachine decision) { decisions.put(decisionId, decision); } private DecisionStateMachine getDecision(DecisionId decisionId) { return getDecision(decisionId, null); } private DecisionStateMachine getDecision(DecisionId decisionId, HistoryEvent event) { DecisionStateMachine result = decisions.get(decisionId); if (result == null) { throw new IncompatibleWorkflowDefinition("Unknown " + decisionId + ". The possible causes are " + "nondeterministic workflow definition code or incompatible change in the workflow definition. " + (event != null ? "HistoryEvent: " + event.toString() + ". " : "") + "Keys in the decisions map: " + decisions.keySet()); } return result; } public ChildWorkflowIdHandler getChildWorkflowIdHandler() { return childWorkflowIdHandler; } public String getNextId() { return String.valueOf(++idCounter); } }
3,630
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/worker/TimerDecisionStateMachine.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.worker; import com.amazonaws.services.simpleworkflow.model.CancelTimerDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.Decision; import com.amazonaws.services.simpleworkflow.model.DecisionType; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.StartTimerDecisionAttributes; /** * Timer doesn't have separate initiation decision as it is started immediately. * But from the state machine point of view it is modeled the same as activity * with no TimerStarted event used as initiation event. * * @author fateev */ class TimerDecisionStateMachine extends DecisionStateMachineBase { private StartTimerDecisionAttributes attributes; private boolean canceled; public TimerDecisionStateMachine(DecisionId id, StartTimerDecisionAttributes attributes) { super(id); this.attributes = attributes; } /** * Used for unit testing */ TimerDecisionStateMachine(DecisionId id, StartTimerDecisionAttributes attributes, DecisionState state) { super(id, state); this.attributes = attributes; } @Override public Decision getDecision() { switch (state) { case CREATED: return createStartTimerDecision(); case CANCELED_AFTER_INITIATED: return createCancelTimerDecision(); default: return null; } } @Override public void handleDecisionTaskStartedEvent() { switch (state) { case CANCELED_AFTER_INITIATED: stateHistory.add("handleDecisionTaskStartedEvent"); state = DecisionState.CANCELLATION_DECISION_SENT; stateHistory.add(state.toString()); break; default: super.handleDecisionTaskStartedEvent(); } } @Override public void handleCancellationFailureEvent(HistoryEvent event) { switch (state) { case CANCELLATION_DECISION_SENT: stateHistory.add("handleCancellationFailureEvent"); state = DecisionState.INITIATED; stateHistory.add(state.toString()); break; default: super.handleCancellationFailureEvent(event); } } @Override public void cancel(Runnable immediateCancellationCallback) { canceled = true; immediateCancellationCallback.run(); super.cancel(null); } /** * As timer is canceled immediately there is no need for waiting after * cancellation decision was sent. */ @Override public boolean isDone() { return state == DecisionState.COMPLETED || canceled; } private Decision createCancelTimerDecision() { CancelTimerDecisionAttributes tryCancel = new CancelTimerDecisionAttributes(); tryCancel.setTimerId(attributes.getTimerId()); Decision decision = new Decision(); decision.setCancelTimerDecisionAttributes(tryCancel); decision.setDecisionType(DecisionType.CancelTimer.toString()); return decision; } private Decision createStartTimerDecision() { Decision decision = new Decision(); decision.setStartTimerDecisionAttributes(attributes); decision.setDecisionType(DecisionType.StartTimer.toString()); return decision; } }
3,631
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/worker/LambdaFunctionClient.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.worker; import com.amazonaws.services.simpleworkflow.flow.core.Promise; public interface LambdaFunctionClient { Promise<String> scheduleLambdaFunction(String name, String input); Promise<String> scheduleLambdaFunction(String name, String input, long timeoutSeconds); Promise<String> scheduleLambdaFunction(String name, String input, long timeoutSeconds, String functionId); Promise<String> scheduleLambdaFunction(String name, Promise<String> input); Promise<String> scheduleLambdaFunction(String name, Promise<String> input, long timeoutSeconds); }
3,632
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/worker/ActivityTypeCompletionRetryOptions.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.worker; import com.amazonaws.services.simpleworkflow.flow.annotations.ActivityCompletionRetryOptions; /** * See {@link ActivityCompletionRetryOptions} for default values. */ public class ActivityTypeCompletionRetryOptions { @ActivityCompletionRetryOptions public static final void dummy() { } private long initialRetryIntervalSeconds; private long maximumRetryIntervalSeconds; private long retryExpirationSeconds; private double backoffCoefficient; private int maximumAttempts; private int minimumAttempts; public ActivityTypeCompletionRetryOptions() { try { ActivityCompletionRetryOptions defaults = this.getClass().getMethod("dummy").getAnnotation( ActivityCompletionRetryOptions.class); initialRetryIntervalSeconds = defaults.initialRetryIntervalSeconds(); maximumRetryIntervalSeconds = defaults.maximumRetryIntervalSeconds(); retryExpirationSeconds = defaults.retryExpirationSeconds(); backoffCoefficient = defaults.backoffCoefficient(); maximumAttempts = defaults.maximumAttempts(); minimumAttempts = defaults.minimumAttempts(); } catch (Exception e) { throw new Error("Unexpected", e); } } public long getInitialRetryIntervalSeconds() { return initialRetryIntervalSeconds; } public void setInitialRetryIntervalSeconds(long initialRetryIntervalSeconds) { this.initialRetryIntervalSeconds = initialRetryIntervalSeconds; } public long getMaximumRetryIntervalSeconds() { return maximumRetryIntervalSeconds; } public void setMaximumRetryIntervalSeconds(long maximumRetryIntervalSeconds) { this.maximumRetryIntervalSeconds = maximumRetryIntervalSeconds; } public long getRetryExpirationSeconds() { return retryExpirationSeconds; } public void setRetryExpirationSeconds(long retryExpirationSeconds) { this.retryExpirationSeconds = retryExpirationSeconds; } public double getBackoffCoefficient() { return backoffCoefficient; } public void setBackoffCoefficient(double backoffCoefficient) { this.backoffCoefficient = backoffCoefficient; } public int getMaximumAttempts() { return maximumAttempts; } public void setMaximumAttempts(int maximumAttempts) { this.maximumAttempts = maximumAttempts; } public int getMinimumAttempts() { return minimumAttempts; } public void setMinimumAttempts(int minimumAttempts) { this.minimumAttempts = minimumAttempts; } }
3,633
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/worker/OpenRequestInfo.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.worker; import com.amazonaws.services.simpleworkflow.flow.core.ExternalTaskCompletionHandle; import com.amazonaws.services.simpleworkflow.flow.core.Settable; class OpenRequestInfo<T, C> { ExternalTaskCompletionHandle completionHandle; final Settable<T> result = new Settable<T>(); final C userContext; OpenRequestInfo() { userContext = null; } OpenRequestInfo(C userContext) { this.userContext = userContext; } ExternalTaskCompletionHandle getCompletionHandle() { return completionHandle; } void setCompletionHandle(ExternalTaskCompletionHandle context) { this.completionHandle = context; } Settable<T> getResult() { return result; } C getUserContext() { return userContext; } public void setResultDescription(String description) { result.setDescription(description); } }
3,634
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/worker/ActivityDecisionStateMachine.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.worker; import com.amazonaws.services.simpleworkflow.model.Decision; import com.amazonaws.services.simpleworkflow.model.DecisionType; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.RequestCancelActivityTaskDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.ScheduleActivityTaskDecisionAttributes; class ActivityDecisionStateMachine extends DecisionStateMachineBase { private ScheduleActivityTaskDecisionAttributes scheduleAttributes; public ActivityDecisionStateMachine(DecisionId id, ScheduleActivityTaskDecisionAttributes scheduleAttributes) { super(id); this.scheduleAttributes = scheduleAttributes; } /** * Used for unit testing */ ActivityDecisionStateMachine(DecisionId id, ScheduleActivityTaskDecisionAttributes scheduleAttributes, DecisionState state) { super(id, state); this.scheduleAttributes = scheduleAttributes; } @Override public Decision getDecision() { switch (state) { case CREATED: return createScheduleActivityTaskDecision(); case CANCELED_AFTER_INITIATED: return createRequestCancelActivityTaskDecision(); default: return null; } } @Override public void handleDecisionTaskStartedEvent() { switch (state) { case CANCELED_AFTER_INITIATED: stateHistory.add("handleDecisionTaskStartedEvent"); state = DecisionState.CANCELLATION_DECISION_SENT; stateHistory.add(state.toString()); break; default: super.handleDecisionTaskStartedEvent(); } } @Override public void handleCancellationFailureEvent(HistoryEvent event) { switch (state) { case CANCELLATION_DECISION_SENT: stateHistory.add("handleCancellationFailureEvent"); state = DecisionState.INITIATED; stateHistory.add(state.toString()); break; default: super.handleCancellationFailureEvent(event); } } private Decision createRequestCancelActivityTaskDecision() { RequestCancelActivityTaskDecisionAttributes tryCancel = new RequestCancelActivityTaskDecisionAttributes(); tryCancel.setActivityId(scheduleAttributes.getActivityId()); Decision decision = new Decision(); decision.setRequestCancelActivityTaskDecisionAttributes(tryCancel); decision.setDecisionType(DecisionType.RequestCancelActivityTask.toString()); return decision; } private Decision createScheduleActivityTaskDecision() { Decision decision = new Decision(); decision.setScheduleActivityTaskDecisionAttributes(scheduleAttributes); decision.setDecisionType(DecisionType.ScheduleActivityTask.toString()); return decision; } }
3,635
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/worker/IncompatibleWorkflowDefinition.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.worker; /** * Used to report that given history cannot be replayed using current workflow * implementation. Extends Error to ensure that current decision fails without * affecting workflow execution. */ @SuppressWarnings("serial") public class IncompatibleWorkflowDefinition extends Error { public IncompatibleWorkflowDefinition() { super(); } public IncompatibleWorkflowDefinition(String message, Throwable ex) { super(message, ex); } public IncompatibleWorkflowDefinition(String message) { super(message); } public IncompatibleWorkflowDefinition(Throwable ex) { super(ex); } }
3,636
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/worker/HistoryHelper.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.worker; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Scanner; import lombok.Getter; import lombok.RequiredArgsConstructor; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils; import com.amazonaws.services.simpleworkflow.model.DecisionTask; import com.amazonaws.services.simpleworkflow.model.EventType; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; class HistoryHelper { private static final Log historyLog = LogFactory.getLog(HistoryHelper.class.getName() + ".history"); @RequiredArgsConstructor @Getter private class SingleDecisionData { private final List<HistoryEvent> decisionEvents; private final long replayCurrentTimeMilliseconds; private final String workflowContextData; } class SingleDecisionEventsIterator implements Iterator<SingleDecisionData> { private final EventsIterator events; @Getter private final ComponentVersions componentVersions = new ComponentVersions(); private String workflowContextData; private SingleDecisionData current; private SingleDecisionData next; public SingleDecisionEventsIterator(Iterator<DecisionTask> decisionTasks) { events = new EventsIterator(decisionTasks); fillNext(); current = next; fillNext(); } @Override public boolean hasNext() { return current != null; } @Override public SingleDecisionData next() { SingleDecisionData result = current; current = next; fillNext(); return result; } /** * Load events for the next decision. This method has to deal with the * following edge cases to support correct replay: * * <li>DecisionTaskTimedOut. The events for the next decision are the * ones from the currently processed decision DecisionTaskStarted event * to the next DecisionTaskStarted that is not followed by * DecisionTaskTimedOut. * * <li>Events that were added to a history during a decision. These * events appear between DecisionTaskStarted and DecisionTaskCompleted * events. They should be processed after all events that correspond to * decisions that follow DecisionTaskCompletedEvent. */ private void fillNext() { boolean decisionTaskTimedOut = false; List<HistoryEvent> decisionStartToCompletionEvents = new ArrayList<HistoryEvent>(); List<HistoryEvent> decisionCompletionToStartEvents = new ArrayList<HistoryEvent>(); boolean concurrentToDecision = true; int lastDecisionIndex = -1; long nextReplayCurrentTimeMilliseconds = -1; while (events.hasNext()) { HistoryEvent event = events.next(); EventType eventType = EventType.fromValue(event.getEventType()); if (eventType == EventType.DecisionTaskCompleted) { String executionContext = event.getDecisionTaskCompletedEventAttributes().getExecutionContext(); updateWorkflowContextDataAndComponentVersions(executionContext); concurrentToDecision = false; } else if (eventType == EventType.DecisionTaskStarted) { nextReplayCurrentTimeMilliseconds = event.getEventTimestamp().getTime(); if (decisionTaskTimedOut) { current.getDecisionEvents().addAll(decisionStartToCompletionEvents); decisionStartToCompletionEvents = new ArrayList<HistoryEvent>(); decisionTaskTimedOut = false; } else { break; } } else if (eventType.equals(EventType.DecisionTaskTimedOut)) { decisionTaskTimedOut = true; } else if (eventType == EventType.DecisionTaskScheduled) { // skip } else if (eventType == EventType.MarkerRecorded) { // ignore } else if (eventType == EventType.RecordMarkerFailed) { // ignore } else { if (concurrentToDecision) { decisionStartToCompletionEvents.add(event); } else { if (isDecisionEvent(eventType)) { lastDecisionIndex = decisionCompletionToStartEvents.size(); } decisionCompletionToStartEvents.add(event); } } } List<HistoryEvent> nextEvents = reorderEvents(decisionStartToCompletionEvents, decisionCompletionToStartEvents, lastDecisionIndex); next = new SingleDecisionData(nextEvents, nextReplayCurrentTimeMilliseconds, workflowContextData); } public DecisionTask getDecisionTask() { return events.getDecisionTask(); } @Override public void remove() { throw new UnsupportedOperationException(); } private boolean isDecisionEvent(EventType eventType) { switch (eventType) { case ActivityTaskScheduled: case ScheduleActivityTaskFailed: case ActivityTaskCancelRequested: case RequestCancelActivityTaskFailed: case MarkerRecorded: case RecordMarkerFailed: case WorkflowExecutionCompleted: case CompleteWorkflowExecutionFailed: case WorkflowExecutionFailed: case FailWorkflowExecutionFailed: case WorkflowExecutionCanceled: case CancelWorkflowExecutionFailed: case WorkflowExecutionContinuedAsNew: case ContinueAsNewWorkflowExecutionFailed: case TimerStarted: case StartTimerFailed: case TimerCanceled: case CancelTimerFailed: case SignalExternalWorkflowExecutionInitiated: case SignalExternalWorkflowExecutionFailed: case RequestCancelExternalWorkflowExecutionInitiated: case RequestCancelExternalWorkflowExecutionFailed: case StartChildWorkflowExecutionInitiated: case StartChildWorkflowExecutionFailed: return true; default: return false; } } /** * Reorder events to correspond to the order in which decider sees them. * The difference is that events that were added during decision task * execution should be processed after events that correspond to the * decisions. Otherwise the replay is going to break. */ private List<HistoryEvent> reorderEvents(List<HistoryEvent> decisionStartToCompletionEvents, List<HistoryEvent> decisionCompletionToStartEvents, int lastDecisionIndex) { List<HistoryEvent> reordered; int size = decisionStartToCompletionEvents.size() + decisionStartToCompletionEvents.size(); reordered = new ArrayList<HistoryEvent>(size); // First are events that correspond to the previous task decisions if (lastDecisionIndex >= 0) { reordered.addAll(decisionCompletionToStartEvents.subList(0, lastDecisionIndex + 1)); } // Second are events that were added during previous task execution reordered.addAll(decisionStartToCompletionEvents); // The last are events that were added after previous task completion if (decisionCompletionToStartEvents.size() > lastDecisionIndex + 1) { reordered.addAll(decisionCompletionToStartEvents.subList(lastDecisionIndex + 1, decisionCompletionToStartEvents.size())); } return reordered; } // Should be in sync with GenericWorkflowClientExternalImpl.getWorkflowState private void updateWorkflowContextDataAndComponentVersions(String executionContext) { if (executionContext != null && executionContext.startsWith(AsyncDecisionTaskHandler.COMPONENT_VERSION_MARKER)) { Scanner scanner = new Scanner(executionContext); scanner.useDelimiter(AsyncDecisionTaskHandler.COMPONENT_VERSION_SEPARATORS_PATTERN); scanner.next(); int size = scanner.nextInt(); for (int i = 0; i < size; i++) { String componentName = scanner.next(); int version = scanner.nextInt(); if (componentName == null) { throw new IncompatibleWorkflowDefinition("null component name in line " + i + " in the execution context: " + executionContext); } componentVersions.setVersionFromHistory(componentName, version); } workflowContextData = scanner.next(".*"); } else { workflowContextData = executionContext; } } } class EventsIterator implements Iterator<HistoryEvent> { private final Iterator<DecisionTask> decisionTasks; @Getter private DecisionTask decisionTask; @Getter private List<HistoryEvent> events; private int index; public EventsIterator(Iterator<DecisionTask> decisionTasks) { this.decisionTasks = decisionTasks; if (decisionTasks.hasNext()) { decisionTask = decisionTasks.next(); events = decisionTask.getEvents(); if (historyLog.isTraceEnabled()) { historyLog.trace(WorkflowExecutionUtils.prettyPrintHistory(events, true)); } } else { decisionTask = null; } } @Override public boolean hasNext() { return decisionTask != null && (index < events.size() || decisionTasks.hasNext()); } @Override public HistoryEvent next() { if (index == events.size()) { decisionTask = decisionTasks.next(); events = decisionTask.getEvents(); if (historyLog.isTraceEnabled()) { historyLog.trace(WorkflowExecutionUtils.prettyPrintHistory(events, true)); } index = 0; } return events.get(index++); } @Override public void remove() { throw new UnsupportedOperationException(); } } private final SingleDecisionEventsIterator singleDecisionEventsIterator; private SingleDecisionData currentDecisionData; public HistoryHelper(Iterator<DecisionTask> decisionTasks) { this.singleDecisionEventsIterator = new SingleDecisionEventsIterator(decisionTasks); } public List<HistoryEvent> getSingleDecisionEvents() { if (!singleDecisionEventsIterator.hasNext()) { currentDecisionData = null; return null; } currentDecisionData = singleDecisionEventsIterator.next(); return currentDecisionData.getDecisionEvents(); } public DecisionTask getDecisionTask() { return singleDecisionEventsIterator.getDecisionTask(); } public String getWorkflowContextData() { if (currentDecisionData == null) { throw new IllegalStateException(); } return currentDecisionData.getWorkflowContextData(); } public long getReplayCurrentTimeMilliseconds() { if (currentDecisionData == null) { throw new IllegalStateException(); } return currentDecisionData.getReplayCurrentTimeMilliseconds(); } public ComponentVersions getComponentVersions() { return singleDecisionEventsIterator.getComponentVersions(); } public long getLastNonReplayEventId() { Long result = getDecisionTask().getPreviousStartedEventId(); if (result == null) { return 0; } return result; } }
3,637
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/worker/ActivityExecutionContextImpl.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.worker; import java.util.concurrent.CancellationException; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContext; import com.amazonaws.services.simpleworkflow.flow.common.RequestTimeoutHelper; import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig; import com.amazonaws.services.simpleworkflow.model.ActivityTask; import com.amazonaws.services.simpleworkflow.model.ActivityTaskStatus; import com.amazonaws.services.simpleworkflow.model.RecordActivityTaskHeartbeatRequest; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; /** * Base implementation of an {@link ActivityExecutionContext}. * * @see ActivityExecutionContext * * @author fateev, suskin * */ class ActivityExecutionContextImpl extends ActivityExecutionContext { private final AmazonSimpleWorkflow service; private final String domain; private final ActivityTask task; private SimpleWorkflowClientConfig config; /** * Create an ActivityExecutionContextImpl with the given attributes. * * @param service * The {@link AmazonSimpleWorkflow} this * ActivityExecutionContextImpl will send service calls to. * @param task * The {@link ActivityTask} this ActivityExecutionContextImpl * will be used for. * * @see ActivityExecutionContext */ public ActivityExecutionContextImpl(AmazonSimpleWorkflow service, String domain, ActivityTask task) { this(service, domain, task, null); } /** * Create an ActivityExecutionContextImpl with the given attributes. * * @param service * The {@link AmazonSimpleWorkflow} this * ActivityExecutionContextImpl will send service calls to. * @param task * The {@link ActivityTask} this ActivityExecutionContextImpl * will be used for. * * @see ActivityExecutionContext */ public ActivityExecutionContextImpl(AmazonSimpleWorkflow service, String domain, ActivityTask task, SimpleWorkflowClientConfig config) { this.domain = domain; this.service = service; this.task = task; this.config = config; } /** * @throws CancellationException * @see ActivityExecutionContext#recordActivityHeartbeat(String) */ @Override public void recordActivityHeartbeat(String details) throws CancellationException { //TODO: call service with the specified minimal interval (through @ActivityExecutionOptions) // allowing more frequent calls of this method. RecordActivityTaskHeartbeatRequest r = new RecordActivityTaskHeartbeatRequest(); r.setTaskToken(task.getTaskToken()); r.setDetails(details); ActivityTaskStatus status; RequestTimeoutHelper.overrideDataPlaneRequestTimeout(r, config); status = service.recordActivityTaskHeartbeat(r); if (status.isCancelRequested()) { throw new CancellationException(); } } /** * @see ActivityExecutionContext#getTask() */ @Override public ActivityTask getTask() { return task; } /** * @see ActivityExecutionContext#getService() */ @Override public AmazonSimpleWorkflow getService() { return service; } @Override public String getTaskToken() { return task.getTaskToken(); } @Override public WorkflowExecution getWorkflowExecution() { return task.getWorkflowExecution(); } @Override public String getDomain() { return domain; } }
3,638
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/worker/CompleteWorkflowStateMachine.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.worker; import com.amazonaws.services.simpleworkflow.model.Decision; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; public class CompleteWorkflowStateMachine implements DecisionStateMachine { private Decision decision; private final DecisionId id; public CompleteWorkflowStateMachine(DecisionId id, Decision decision) { this.id = id; this.decision = decision; } public DecisionId getId() { return id; } @Override public Decision getDecision() { return decision; } @Override public void handleInitiationFailedEvent(HistoryEvent event) { decision = null; } @Override public void cancel(Runnable immediateCancellationCallback) { throw new UnsupportedOperationException(); } @Override public void handleStartedEvent(HistoryEvent event) { throw new UnsupportedOperationException(); } @Override public void handleCancellationEvent() { throw new UnsupportedOperationException(); } @Override public void handleCancellationFailureEvent(HistoryEvent event) { throw new UnsupportedOperationException(); } @Override public void handleCompletionEvent() { throw new UnsupportedOperationException(); } @Override public void handleInitiatedEvent(HistoryEvent event) { throw new UnsupportedOperationException(); } @Override public DecisionState getState() { return DecisionState.CREATED; } @Override public void handleCancellationInitiatedEvent() { throw new UnsupportedOperationException(); } @Override public boolean isDone() { return decision != null; } @Override public void handleDecisionTaskStartedEvent() { } @Override public String toString() { return "CompleteWorkflowStateMachine [decision=" + decision + ", id=" + id + "]"; } }
3,639
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/worker/GenericWorker.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.worker; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.WorkerBase; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.flow.common.RequestTimeoutHelper; import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig; import com.amazonaws.services.simpleworkflow.model.DomainAlreadyExistsException; import com.amazonaws.services.simpleworkflow.model.RegisterDomainRequest; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.management.ManagementFactory; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; public abstract class GenericWorker<T> implements WorkerBase { @RequiredArgsConstructor class ExecutorThreadFactory implements ThreadFactory { private final AtomicInteger threadIndex = new AtomicInteger(); private final String threadPrefix; @Override public Thread newThread(Runnable r) { Thread result = new Thread(r); result.setName(threadPrefix + (threadIndex.incrementAndGet())); result.setUncaughtExceptionHandler(uncaughtExceptionHandler); return result; } } @RequiredArgsConstructor private class PollingTask implements Runnable { private final TaskPoller<T> poller; @Override public void run() { try { while(true) { log.debug("poll task begin"); if (pollingExecutor.isShutdown() || workerExecutor.isShutdown()) { return; } final int availableWorkers = workerExecutor.getMaximumPoolSize() - workerExecutor.getActiveCount(); if (availableWorkers < 1) { log.debug("no available workers"); return; } pollBackoffThrottler.throttle(); if (pollingExecutor.isShutdown() || workerExecutor.isShutdown()) { return; } if (pollRateThrottler != null) { pollRateThrottler.throttle(); } if (pollingExecutor.isShutdown() || workerExecutor.isShutdown()) { return; } boolean semaphoreNeedsRelease = false; SuspendableSemaphore pollingSemaphore = poller.getPollingSemaphore(); try { if (pollingSemaphore != null) { pollingSemaphore.acquire(); } semaphoreNeedsRelease = true; T task = poller.poll(); if (task == null) { log.debug("no work returned"); return; } semaphoreNeedsRelease = false; try { workerExecutor.execute(new ExecuteTask(poller, task, pollingSemaphore)); log.debug("poll task end"); } catch (Exception e) { semaphoreNeedsRelease = true; throw e; } catch (Error e) { semaphoreNeedsRelease = true; throw e; } } finally { if (pollingSemaphore != null && semaphoreNeedsRelease) { pollingSemaphore.release(); } } } } catch (final Throwable e) { pollBackoffThrottler.failure(); if (!(e.getCause() instanceof InterruptedException)) { uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), e); } } } } @RequiredArgsConstructor private class ExecuteTask implements Runnable { private final TaskPoller<T> poller; private final T task; private final SuspendableSemaphore pollingSemaphore; @Override public void run() { try { log.debug("execute task begin"); poller.execute(task); pollBackoffThrottler.success(); log.debug("execute task end"); } catch (Throwable e) { pollBackoffThrottler.failure(); if (!(e.getCause() instanceof InterruptedException)) { uncaughtExceptionHandler.uncaughtException(Thread.currentThread(), e); } } finally { if (pollingSemaphore != null) { pollingSemaphore.release(); } } } } private static final Log log = LogFactory.getLog(GenericWorker.class); protected static final int MAX_IDENTITY_LENGTH = 256; @Getter @Setter protected AmazonSimpleWorkflow service; @Getter @Setter protected String domain; @Getter protected boolean registerDomain; @Getter @Setter protected long domainRetentionPeriodInDays = FlowConstants.NONE; @Getter @Setter private String taskListToPoll; @Getter @Setter private int maximumPollRateIntervalMilliseconds = 1000; @Getter @Setter private double maximumPollRatePerSecond; @Getter private double pollBackoffCoefficient = 2; @Getter private long pollBackoffInitialInterval = 100; @Getter private long pollBackoffMaximumInterval = 60000; @Getter @Setter private boolean disableTypeRegistrationOnStart; @Getter private boolean disableServiceShutdownOnStop; @Getter @Setter private boolean allowCoreThreadTimeOut; private boolean suspended; private final AtomicBoolean startRequested = new AtomicBoolean(); private final AtomicBoolean shutdownRequested = new AtomicBoolean(); private ScheduledExecutorService pollingExecutor; private ThreadPoolExecutor workerExecutor; @Getter @Setter private String identity = ManagementFactory.getRuntimeMXBean().getName(); @Getter private int pollThreadCount = 1; @Getter protected int executeThreadCount = 100; private BackoffThrottler pollBackoffThrottler; private Throttler pollRateThrottler; @Getter @Setter protected UncaughtExceptionHandler uncaughtExceptionHandler = new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { log.error("Failure in thread " + t.getName(), e); } }; private TaskPoller<T> poller; @Getter @Setter private SimpleWorkflowClientConfig clientConfig; public GenericWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll) { this(service, domain, taskListToPoll, null); } public GenericWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll, SimpleWorkflowClientConfig clientConfig) { this(); this.service = service; this.domain = domain; this.taskListToPoll = taskListToPoll; this.clientConfig = clientConfig; } public GenericWorker() { identity = ManagementFactory.getRuntimeMXBean().getName(); int length = Math.min(identity.length(), GenericWorker.MAX_IDENTITY_LENGTH); identity = identity.substring(0, length); } @Override public void start() { if (log.isInfoEnabled()) { log.info("start: " + this); } if (shutdownRequested.get()) { throw new IllegalStateException("Shutdown Requested. Not restartable."); } if (!startRequested.compareAndSet(false, true)) { return; } checkRequiredProperty(service, "service"); checkRequiredProperty(domain, "domain"); checkRequiredProperty(taskListToPoll, "taskListToPoll"); checkRequiredProperties(); if (registerDomain) { registerDomain(); } if (!disableTypeRegistrationOnStart) { registerTypesToPoll(); } if (maximumPollRatePerSecond > 0.0) { pollRateThrottler = new Throttler("pollRateThrottler " + taskListToPoll, maximumPollRatePerSecond, maximumPollRateIntervalMilliseconds); } poller = createPoller(); if (suspended) { poller.suspend(); } pollBackoffThrottler = new BackoffThrottler(pollBackoffInitialInterval, pollBackoffMaximumInterval, pollBackoffCoefficient); workerExecutor = new ThreadPoolExecutor(executeThreadCount, executeThreadCount, 1, TimeUnit.MINUTES, new SynchronousQueue<>(), new BlockCallerPolicy()); workerExecutor.allowCoreThreadTimeOut(allowCoreThreadTimeOut); ExecutorThreadFactory pollExecutorThreadFactory = getExecutorThreadFactory("Worker"); workerExecutor.setThreadFactory(pollExecutorThreadFactory); pollingExecutor = new ScheduledThreadPoolExecutor(pollThreadCount, getExecutorThreadFactory("Poller")); for (int i = 0; i < pollThreadCount; i++) { pollingExecutor.scheduleWithFixedDelay(new PollingTask(poller), 0, 1, TimeUnit.NANOSECONDS); } } private ExecutorThreadFactory getExecutorThreadFactory(final String type) { return new ExecutorThreadFactory(getPollThreadNamePrefix() + " " + type); } protected abstract String getPollThreadNamePrefix(); protected abstract TaskPoller<T> createPoller(); protected abstract void checkRequiredProperties(); private void registerDomain() { if (domainRetentionPeriodInDays == FlowConstants.NONE) { throw new IllegalStateException("required property domainRetentionPeriodInDays is not set"); } try { RegisterDomainRequest request = new RegisterDomainRequest().withName(domain).withWorkflowExecutionRetentionPeriodInDays( String.valueOf(domainRetentionPeriodInDays)); RequestTimeoutHelper.overrideControlPlaneRequestTimeout(request, clientConfig); service.registerDomain(request); } catch (DomainAlreadyExistsException e) { if (log.isTraceEnabled()) { log.trace("Domain is already registered: " + domain); } } } protected void checkRequiredProperty(Object value, String name) { if (value == null) { throw new IllegalStateException("required property " + name + " is not set"); } } protected void checkStarted() { if (isStarted()) { throw new IllegalStateException("started"); } } private boolean isStarted() { return startRequested.get(); } @Override public void shutdown() { if (log.isInfoEnabled()) { log.info("shutdown"); } if (!shutdownRequested.compareAndSet(false, true)) { return; } if (!isStarted()) { return; } if (!disableServiceShutdownOnStop) { service.shutdown(); } pollingExecutor.shutdown(); workerExecutor.shutdown(); } @Override public void shutdownNow() { if (log.isInfoEnabled()) { log.info("shutdownNow"); } if (!shutdownRequested.compareAndSet(false, true)) { return; } if (!isStarted()) { return; } if (!disableServiceShutdownOnStop) { service.shutdown(); } pollingExecutor.shutdownNow(); workerExecutor.shutdownNow(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long start = System.currentTimeMillis(); boolean terminated = pollingExecutor.awaitTermination(timeout, unit); long elapsed = System.currentTimeMillis() - start; long left = TimeUnit.MILLISECONDS.convert(timeout, unit) - elapsed; terminated &= workerExecutor.awaitTermination(left, TimeUnit.MILLISECONDS); return terminated; } /** * The graceful shutdown will wait for existing polls and tasks to complete * unless the timeout is not enough. It does not shutdown the SWF client. */ @Override public boolean gracefulShutdown(long timeout, TimeUnit unit) throws InterruptedException { setDisableServiceShutdownOnStop(true); return shutdownAndAwaitTermination(timeout, unit); } /** * This method will also shutdown SWF client unless you {@link #setDisableServiceShutdownOnStop(boolean)} to <code>true</code>. */ @Override public boolean shutdownAndAwaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long timeoutMilliseconds = TimeUnit.MILLISECONDS.convert(timeout, unit); long start = System.currentTimeMillis(); if (shutdownRequested.compareAndSet(false, true)) { if (!isStarted()) { return true; } if (!disableServiceShutdownOnStop) { service.shutdown(); } pollingExecutor.shutdown(); pollingExecutor.awaitTermination(timeout, unit); workerExecutor.shutdown(); long elapsed = System.currentTimeMillis() - start; long left = timeoutMilliseconds - elapsed; workerExecutor.awaitTermination(left, unit); } long elapsed = System.currentTimeMillis() - start; long left = timeoutMilliseconds - elapsed; return awaitTermination(left, TimeUnit.MILLISECONDS); } @Override public boolean isRunning() { return isStarted() && !pollingExecutor.isTerminated() && !workerExecutor.isTerminated(); } @Override public void suspendPolling() { if (log.isInfoEnabled()) { log.info("suspendPolling"); } suspended = true; if (poller != null) { poller.suspend(); } } @Override public void resumePolling() { if (log.isInfoEnabled()) { log.info("resumePolling"); } suspended = false; if (poller != null) { poller.resume(); } } @Override public boolean isPollingSuspended() { if (poller != null) { return poller.isSuspended(); } return suspended; } @Override public void setPollingSuspended(boolean flag) { if (flag) { suspendPolling(); } else { resumePolling(); } } /** * Should domain be registered on startup. Default is <code>false</code>. * When enabled {@link #setDomainRetentionPeriodInDays(long)} property is * required. */ @Override public void setRegisterDomain(boolean registerDomain) { this.registerDomain = registerDomain; } @Override public void setPollBackoffInitialInterval(long backoffInitialInterval) { if (backoffInitialInterval < 0) { throw new IllegalArgumentException("expected value should be positive or 0: " + backoffInitialInterval); } this.pollBackoffInitialInterval = backoffInitialInterval; } @Override public void setPollBackoffMaximumInterval(long backoffMaximumInterval) { if (backoffMaximumInterval <= 0) { throw new IllegalArgumentException("expected value should be positive: " + backoffMaximumInterval); } this.pollBackoffMaximumInterval = backoffMaximumInterval; } /** * By default when @{link {@link #shutdown()} or @{link * {@link #shutdownNow()} is called the worker calls * {@link AmazonSimpleWorkflow#shutdown()} on the service instance it is * configured with before shutting down internal thread pools. Otherwise * threads that are waiting on a poll request might block shutdown for the * duration of a poll. This flag allows disabling this behavior. * * @param disableServiceShutdownOnStop * <code>true</code> means do not call * {@link AmazonSimpleWorkflow#shutdown()} */ @Override public void setDisableServiceShutdownOnStop(boolean disableServiceShutdownOnStop) { this.disableServiceShutdownOnStop = disableServiceShutdownOnStop; } @Override public void setPollBackoffCoefficient(double backoffCoefficient) { if (backoffCoefficient < 1.0) { throw new IllegalArgumentException("expected value should be bigger or equal to 1.0: " + backoffCoefficient); } this.pollBackoffCoefficient = backoffCoefficient; } @Override public void setPollThreadCount(int threadCount) { checkStarted(); this.pollThreadCount = threadCount; /* It is actually not very useful to have poll thread count larger than execute thread count. Since execute thread count is a new concept introduced since Flow-3.7, to make the major version upgrade more friendly, try to bring the execute thread count to match poll thread count if client does not the set execute thread count explicitly. */ if (this.executeThreadCount < threadCount) { this.executeThreadCount = threadCount; } } @Override public void setExecuteThreadCount(int threadCount) { checkStarted(); this.executeThreadCount = threadCount; } @Override public String toString() { return this.getClass().getSimpleName() + "[service=" + service + ", domain=" + domain + ", taskListToPoll=" + taskListToPoll + ", identity=" + identity + ", backoffInitialInterval=" + pollBackoffInitialInterval + ", backoffMaximumInterval=" + pollBackoffMaximumInterval + ", backoffCoefficient=" + pollBackoffCoefficient + "]"; } protected static ExponentialRetryParameters getRegisterTypeThrottledRetryParameters() { ExponentialRetryParameters retryParameters = new ExponentialRetryParameters(); retryParameters.setBackoffCoefficient(2.0); retryParameters.setExpirationInterval(TimeUnit.MINUTES.toMillis(10)); // Use a large base retry interval since this is built on top of SDK retry. retryParameters.setInitialInterval(TimeUnit.SECONDS.toMillis(3)); retryParameters.setMaximumRetries(29); retryParameters.setMaximumRetryInterval(TimeUnit.SECONDS.toMillis(20)); retryParameters.setMinimumRetries(1); return retryParameters; } }
3,640
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/worker/GenericWorkflowClientExternalImpl.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.worker; import java.util.HashMap; import java.util.Map; import java.util.Scanner; import java.util.UUID; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.common.FlowHelpers; import com.amazonaws.services.simpleworkflow.flow.common.RequestTimeoutHelper; import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig; import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClientExternal; import com.amazonaws.services.simpleworkflow.flow.generic.SignalExternalWorkflowParameters; import com.amazonaws.services.simpleworkflow.flow.generic.StartWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.flow.generic.TerminateWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.model.DescribeWorkflowExecutionRequest; import com.amazonaws.services.simpleworkflow.model.RequestCancelWorkflowExecutionRequest; import com.amazonaws.services.simpleworkflow.model.Run; import com.amazonaws.services.simpleworkflow.model.SignalWorkflowExecutionRequest; import com.amazonaws.services.simpleworkflow.model.StartWorkflowExecutionRequest; import com.amazonaws.services.simpleworkflow.model.TaskList; import com.amazonaws.services.simpleworkflow.model.TerminateWorkflowExecutionRequest; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; import com.amazonaws.services.simpleworkflow.model.WorkflowExecutionDetail; public class GenericWorkflowClientExternalImpl implements GenericWorkflowClientExternal { private final String domain; private final AmazonSimpleWorkflow service; private SimpleWorkflowClientConfig config; public GenericWorkflowClientExternalImpl(AmazonSimpleWorkflow service, String domain) { this(service, domain, null); } public GenericWorkflowClientExternalImpl(AmazonSimpleWorkflow service, String domain, SimpleWorkflowClientConfig config) { this.service = service; this.domain = domain; this.config = config; } @Override public WorkflowExecution startWorkflow(StartWorkflowExecutionParameters startParameters) { StartWorkflowExecutionRequest request = new StartWorkflowExecutionRequest(); request.setDomain(domain); request.setInput(startParameters.getInput()); request.setExecutionStartToCloseTimeout(FlowHelpers.secondsToDuration(startParameters.getExecutionStartToCloseTimeout())); request.setTaskStartToCloseTimeout(FlowHelpers.secondsToDuration(startParameters.getTaskStartToCloseTimeoutSeconds())); request.setTagList(startParameters.getTagList()); String taskList = startParameters.getTaskList(); if (taskList != null && !taskList.isEmpty()) { request.setTaskList(new TaskList().withName(taskList)); } request.setWorkflowId(startParameters.getWorkflowId()); request.setWorkflowType(startParameters.getWorkflowType()); request.setTaskPriority(FlowHelpers.taskPriorityToString(startParameters.getTaskPriority())); if(startParameters.getChildPolicy() != null) { request.setChildPolicy(startParameters.getChildPolicy()); } request.setLambdaRole(startParameters.getLambdaRole()); RequestTimeoutHelper.overrideDataPlaneRequestTimeout(request, config); Run result = service.startWorkflowExecution(request); WorkflowExecution execution = new WorkflowExecution().withRunId(result.getRunId()).withWorkflowId(request.getWorkflowId()); return execution; } @Override public void signalWorkflowExecution(SignalExternalWorkflowParameters signalParameters) { SignalWorkflowExecutionRequest request = new SignalWorkflowExecutionRequest(); request.setDomain(domain); request.setInput(signalParameters.getInput()); request.setSignalName(signalParameters.getSignalName()); request.setRunId(signalParameters.getRunId()); request.setWorkflowId(signalParameters.getWorkflowId()); RequestTimeoutHelper.overrideDataPlaneRequestTimeout(request, config); service.signalWorkflowExecution(request); } @Override public void requestCancelWorkflowExecution(WorkflowExecution execution) { RequestCancelWorkflowExecutionRequest request = new RequestCancelWorkflowExecutionRequest(); request.setDomain(domain); request.setRunId(execution.getRunId()); request.setWorkflowId(execution.getWorkflowId()); RequestTimeoutHelper.overrideDataPlaneRequestTimeout(request, config); service.requestCancelWorkflowExecution(request); } @Override public String generateUniqueId() { String workflowId = UUID.randomUUID().toString(); return workflowId; } @Override public String getWorkflowState(WorkflowExecution execution) { String executionContext = getLatestWorkflowExecutionContext(execution); String result; // Should be in sync with HistoryHelper.updateWorkflowContextDataAndComponentVersions if (executionContext != null && executionContext.startsWith(AsyncDecisionTaskHandler.COMPONENT_VERSION_MARKER)) { Scanner scanner = new Scanner(executionContext); scanner.useDelimiter(AsyncDecisionTaskHandler.COMPONENT_VERSION_SEPARATORS_PATTERN); scanner.next(); int size = scanner.nextInt(); for (int i = 0; i < size; i++) { // component name scanner.next(); // version scanner.nextInt(); } result = scanner.next(".*"); } else { result = executionContext; } return result; } @Override public Map<String, Integer> getImplementationVersions(WorkflowExecution execution) { String executionContext = getLatestWorkflowExecutionContext(execution); Map<String, Integer> result = new HashMap<String, Integer>(); // Should be in sync with HistoryHelper.updateWorkflowContextDataAndComponentVersions if (executionContext.startsWith(AsyncDecisionTaskHandler.COMPONENT_VERSION_MARKER)) { Scanner scanner = new Scanner(executionContext); scanner.useDelimiter(AsyncDecisionTaskHandler.COMPONENT_VERSION_SEPARATORS_PATTERN); scanner.next(); int size = scanner.nextInt(); for (int i = 0; i < size; i++) { String componentName = scanner.next(); int version = scanner.nextInt(); result.put(componentName, version); } } return result; } private String getLatestWorkflowExecutionContext(WorkflowExecution execution) { DescribeWorkflowExecutionRequest request = new DescribeWorkflowExecutionRequest(); request.setDomain(domain); request.setExecution(execution); RequestTimeoutHelper.overrideDataPlaneRequestTimeout(request, config); WorkflowExecutionDetail details = service.describeWorkflowExecution(request); String executionContext = details.getLatestExecutionContext(); return executionContext; } @Override public void terminateWorkflowExecution(TerminateWorkflowExecutionParameters terminateParameters) { TerminateWorkflowExecutionRequest request = new TerminateWorkflowExecutionRequest(); WorkflowExecution workflowExecution = terminateParameters.getWorkflowExecution(); request.setWorkflowId(workflowExecution.getWorkflowId()); request.setRunId(workflowExecution.getRunId()); request.setDomain(domain); request.setDetails(terminateParameters.getDetails()); request.setReason(terminateParameters.getReason()); request.setChildPolicy(terminateParameters.getChildPolicy()); RequestTimeoutHelper.overrideDataPlaneRequestTimeout(request, config); service.terminateWorkflowExecution(request); } }
3,641
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/worker/AsyncDecider.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.worker; import java.util.List; import java.util.concurrent.CancellationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.amazonaws.AmazonServiceException; import com.amazonaws.AmazonServiceException.ErrorType; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.WorkflowException; import com.amazonaws.services.simpleworkflow.flow.core.AsyncScope; import com.amazonaws.services.simpleworkflow.flow.core.AsyncTaskInfo; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Task; import com.amazonaws.services.simpleworkflow.flow.generic.ContinueAsNewWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinition; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactory; import com.amazonaws.services.simpleworkflow.model.DecisionTask; import com.amazonaws.services.simpleworkflow.model.EventType; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.StartTimerFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.TimerFiredEventAttributes; import com.amazonaws.services.simpleworkflow.model.TimerStartedEventAttributes; import com.amazonaws.services.simpleworkflow.model.WorkflowExecutionSignaledEventAttributes; import com.amazonaws.services.simpleworkflow.model.WorkflowExecutionStartedEventAttributes; class AsyncDecider { private static abstract class WorkflowAsyncScope extends AsyncScope { public WorkflowAsyncScope() { super(false, true); } public abstract Promise<String> getOutput(); } private final class WorkflowExecuteAsyncScope extends WorkflowAsyncScope { private final WorkflowExecutionStartedEventAttributes attributes; private Promise<String> output; public WorkflowExecuteAsyncScope(HistoryEvent event) { assert event.getEventType().equals(EventType.WorkflowExecutionStarted.toString()); this.attributes = event.getWorkflowExecutionStartedEventAttributes(); } @Override protected void doAsync() throws Throwable { output = definition.execute(attributes.getInput()); } @Override public Promise<String> getOutput() { return output; } } private final class UnhandledSignalAsyncScope extends WorkflowAsyncScope { private final Promise<String> output; private Throwable failure; private boolean cancellation; public UnhandledSignalAsyncScope(Promise<String> output, Throwable failure, boolean cancellation) { this.output = output; this.failure = failure; this.cancellation = cancellation; } @Override protected void doAsync() throws Throwable { } @Override public Promise<String> getOutput() { return output; } @Override public boolean isCancelRequested() { return super.isCancelRequested() || cancellation; } @Override public Throwable getFailure() { Throwable result = super.getFailure(); if (failure != null) { result = failure; } return result; } @Override public boolean eventLoop() throws Throwable { boolean completed = super.eventLoop(); if (completed && failure != null) { throw failure; } return completed; } } private static final Log log = LogFactory.getLog(AsyncDecider.class); private final WorkflowDefinitionFactory workflowDefinitionFactory; private WorkflowDefinition definition; private final HistoryHelper historyHelper; private final DecisionsHelper decisionsHelper; private final GenericActivityClientImpl activityClient; private final GenericWorkflowClientImpl workflowClient; private final LambdaFunctionClientImpl lambdaFunctionClient; private final WorkflowClockImpl workflowClock; private final DecisionContext context; private WorkflowAsyncScope workflowAsyncScope; private boolean cancelRequested; private WorkflowContextImpl workflowContext; private boolean unhandledDecision; private boolean completed; private Throwable failure; public AsyncDecider(WorkflowDefinitionFactory workflowDefinitionFactory, HistoryHelper historyHelper, DecisionsHelper decisionsHelper) throws Exception { this.workflowDefinitionFactory = workflowDefinitionFactory; this.historyHelper = historyHelper; this.decisionsHelper = decisionsHelper; this.activityClient = new GenericActivityClientImpl(decisionsHelper); DecisionTask decisionTask = historyHelper.getDecisionTask(); this.workflowClock = new WorkflowClockImpl(decisionsHelper); workflowContext = new WorkflowContextImpl(decisionTask, workflowClock); workflowContext.setComponentVersions(historyHelper.getComponentVersions()); this.workflowClient = new GenericWorkflowClientImpl(decisionsHelper, workflowContext); this.lambdaFunctionClient = new LambdaFunctionClientImpl(decisionsHelper); context = new DecisionContextImpl(activityClient, workflowClient, workflowClock, workflowContext, lambdaFunctionClient); } public boolean isCancelRequested() { return cancelRequested; } private void handleWorkflowExecutionStarted(HistoryEvent event) { workflowAsyncScope = new WorkflowExecuteAsyncScope(event); } private void processEvent(HistoryEvent event, EventType eventType) throws Throwable { switch (eventType) { case ActivityTaskCanceled: activityClient.handleActivityTaskCanceled(event); break; case ActivityTaskCompleted: activityClient.handleActivityTaskCompleted(event); break; case ActivityTaskFailed: activityClient.handleActivityTaskFailed(event); break; case ActivityTaskStarted: activityClient.handleActivityTaskStarted(event.getActivityTaskStartedEventAttributes()); break; case ActivityTaskTimedOut: activityClient.handleActivityTaskTimedOut(event); break; case ExternalWorkflowExecutionCancelRequested: workflowClient.handleChildWorkflowExecutionCancelRequested(event); break; case ChildWorkflowExecutionCanceled: workflowClient.handleChildWorkflowExecutionCanceled(event); break; case ChildWorkflowExecutionCompleted: workflowClient.handleChildWorkflowExecutionCompleted(event); break; case ChildWorkflowExecutionFailed: workflowClient.handleChildWorkflowExecutionFailed(event); break; case ChildWorkflowExecutionStarted: workflowClient.handleChildWorkflowExecutionStarted(event); break; case ChildWorkflowExecutionTerminated: workflowClient.handleChildWorkflowExecutionTerminated(event); break; case ChildWorkflowExecutionTimedOut: workflowClient.handleChildWorkflowExecutionTimedOut(event); break; case DecisionTaskCompleted: handleDecisionTaskCompleted(event); break; case DecisionTaskScheduled: // NOOP break; case DecisionTaskStarted: handleDecisionTaskStarted(event); break; case DecisionTaskTimedOut: // Handled in the processEvent(event) break; case ExternalWorkflowExecutionSignaled: workflowClient.handleExternalWorkflowExecutionSignaled(event); break; case ScheduleActivityTaskFailed: activityClient.handleScheduleActivityTaskFailed(event); break; case SignalExternalWorkflowExecutionFailed: workflowClient.handleSignalExternalWorkflowExecutionFailed(event); break; case StartChildWorkflowExecutionFailed: workflowClient.handleStartChildWorkflowExecutionFailed(event); break; case StartTimerFailed: handleStartTimerFailed(event); break; case TimerFired: handleTimerFired(event); break; case WorkflowExecutionCancelRequested: handleWorkflowExecutionCancelRequested(event); break; case WorkflowExecutionSignaled: handleWorkflowExecutionSignaled(event); break; case WorkflowExecutionStarted: handleWorkflowExecutionStarted(event); break; case WorkflowExecutionTerminated: // NOOP break; case WorkflowExecutionTimedOut: // NOOP break; case ActivityTaskScheduled: decisionsHelper.handleActivityTaskScheduled(event); break; case ActivityTaskCancelRequested: decisionsHelper.handleActivityTaskCancelRequested(event); break; case RequestCancelActivityTaskFailed: decisionsHelper.handleRequestCancelActivityTaskFailed(event); break; case MarkerRecorded: break; case RecordMarkerFailed: break; case WorkflowExecutionCompleted: break; case CompleteWorkflowExecutionFailed: unhandledDecision = true; decisionsHelper.handleCompleteWorkflowExecutionFailed(event); break; case WorkflowExecutionFailed: break; case FailWorkflowExecutionFailed: unhandledDecision = true; decisionsHelper.handleFailWorkflowExecutionFailed(event); break; case WorkflowExecutionCanceled: break; case CancelWorkflowExecutionFailed: unhandledDecision = true; decisionsHelper.handleCancelWorkflowExecutionFailed(event); break; case WorkflowExecutionContinuedAsNew: break; case ContinueAsNewWorkflowExecutionFailed: unhandledDecision = true; decisionsHelper.handleContinueAsNewWorkflowExecutionFailed(event); break; case TimerStarted: handleTimerStarted(event); break; case TimerCanceled: workflowClock.handleTimerCanceled(event); break; case LambdaFunctionScheduled: decisionsHelper.handleLambdaFunctionScheduled(event); break; case LambdaFunctionStarted: lambdaFunctionClient.handleLambdaFunctionStarted(event.getLambdaFunctionStartedEventAttributes()); break; case LambdaFunctionCompleted: lambdaFunctionClient.handleLambdaFunctionCompleted(event); break; case LambdaFunctionFailed: lambdaFunctionClient.handleLambdaFunctionFailed(event); break; case LambdaFunctionTimedOut: lambdaFunctionClient.handleLambdaFunctionTimedOut(event); break; case StartLambdaFunctionFailed: lambdaFunctionClient.handleStartLambdaFunctionFailed(event); break; case ScheduleLambdaFunctionFailed: lambdaFunctionClient.handleScheduleLambdaFunctionFailed(event); break; case SignalExternalWorkflowExecutionInitiated: decisionsHelper.handleSignalExternalWorkflowExecutionInitiated(event); break; case RequestCancelExternalWorkflowExecutionInitiated: decisionsHelper.handleRequestCancelExternalWorkflowExecutionInitiated(event); break; case RequestCancelExternalWorkflowExecutionFailed: decisionsHelper.handleRequestCancelExternalWorkflowExecutionFailed(event); break; case StartChildWorkflowExecutionInitiated: workflowClient.handleChildWorkflowExecutionInitiated(event); break; case CancelTimerFailed: decisionsHelper.handleCancelTimerFailed(event); } } private void eventLoop(HistoryEvent event) throws Throwable { if (completed) { return; } try { completed = workflowAsyncScope.eventLoop(); } catch (CancellationException e) { if (!cancelRequested) { failure = e; } completed = true; } catch (Error e) { throw e; } catch (Throwable e) { failure = e; completed = true; } } private void completeWorkflowIfCompleted() { if (completed && !unhandledDecision) { if (failure != null) { decisionsHelper.failWorkflowExecution(failure); } else if (cancelRequested) { decisionsHelper.cancelWorkflowExecution(); } else { ContinueAsNewWorkflowExecutionParameters continueAsNewOnCompletion = workflowContext.getContinueAsNewOnCompletion(); if (continueAsNewOnCompletion != null) { decisionsHelper.continueAsNewWorkflowExecution(continueAsNewOnCompletion); } else { Promise<String> output = workflowAsyncScope.getOutput(); if (output != null && output.isReady()) { String workflowOutput = output.get(); decisionsHelper.completeWorkflowExecution(workflowOutput); } else { decisionsHelper.completeWorkflowExecution(null); } } } } } private void handleDecisionTaskStarted(HistoryEvent event) throws Throwable { } private void handleWorkflowExecutionCancelRequested(HistoryEvent event) throws Throwable { workflowContext.setCancelRequested(true); workflowAsyncScope.cancel(new CancellationException()); cancelRequested = true; } private void handleStartTimerFailed(HistoryEvent event) { StartTimerFailedEventAttributes attributes = event.getStartTimerFailedEventAttributes(); String timerId = attributes.getTimerId(); if (timerId.equals(DecisionsHelper.FORCE_IMMEDIATE_DECISION_TIMER)) { return; } workflowClock.handleStartTimerFailed(event); } private void handleTimerFired(HistoryEvent event) throws Throwable { TimerFiredEventAttributes attributes = event.getTimerFiredEventAttributes(); String timerId = attributes.getTimerId(); if (timerId.equals(DecisionsHelper.FORCE_IMMEDIATE_DECISION_TIMER)) { return; } workflowClock.handleTimerFired(event.getEventId(), attributes); } private void handleTimerStarted(HistoryEvent event) { TimerStartedEventAttributes attributes = event.getTimerStartedEventAttributes(); String timerId = attributes.getTimerId(); if (timerId.equals(DecisionsHelper.FORCE_IMMEDIATE_DECISION_TIMER)) { return; } decisionsHelper.handleTimerStarted(event); } private void handleWorkflowExecutionSignaled(HistoryEvent event) throws Throwable { assert (event.getEventType().equals(EventType.WorkflowExecutionSignaled.toString())); final WorkflowExecutionSignaledEventAttributes signalAttributes = event.getWorkflowExecutionSignaledEventAttributes(); if (completed) { workflowAsyncScope = new UnhandledSignalAsyncScope(workflowAsyncScope.getOutput(), workflowAsyncScope.getFailure(), workflowAsyncScope.isCancelRequested()); completed = false; } // This task is attached to the root context of the workflowAsyncScope new Task(workflowAsyncScope) { @Override protected void doExecute() throws Throwable { definition.signalRecieved(signalAttributes.getSignalName(), signalAttributes.getInput()); } }; } private void handleDecisionTaskCompleted(HistoryEvent event) { decisionsHelper.handleDecisionCompletion(event.getDecisionTaskCompletedEventAttributes()); } public void decide() throws Exception { try { try { definition = workflowDefinitionFactory.getWorkflowDefinition(context); } catch (Exception e) { throw new Error("Failed to get workflow definition for " + context, e); } if (definition == null) { throw new IllegalStateException("Null workflow definition returned for: " + context.getWorkflowContext().getWorkflowType()); } decideImpl(); } catch (AmazonServiceException e) { // We don't want to fail workflow on service exceptions like 500 or throttling // Throwing from here drops decision task which is OK as it is rescheduled after its StartToClose timeout. if (e.getErrorType() == ErrorType.Client && !"ThrottlingException".equals(e.getErrorCode())) { if (log.isErrorEnabled()) { log.error("Failing workflow " + workflowContext.getWorkflowExecution(), e); } decisionsHelper.failWorkflowDueToUnexpectedError(e); } else { throw e; } } catch (Error e) { // Do not fail workflow on Error. Fail the decision. throw e; } catch (Throwable e) { if (log.isErrorEnabled()) { log.error("Failing workflow " + workflowContext.getWorkflowExecution(), e); } decisionsHelper.failWorkflowDueToUnexpectedError(e); } finally { try { if (definition != null) { decisionsHelper.setWorkflowContextData(definition.getWorkflowState()); } } catch (WorkflowException e) { decisionsHelper.setWorkflowContextData(e.getDetails()); } catch (Throwable e) { decisionsHelper.setWorkflowContextData(e.getMessage()); } if (definition != null) { workflowDefinitionFactory.deleteWorkflowDefinition(definition); } } } private void decideImpl() throws Exception, Throwable { List<HistoryEvent> singleDecisionEvents = historyHelper.getSingleDecisionEvents(); while(singleDecisionEvents != null && singleDecisionEvents.size() > 0) { decisionsHelper.handleDecisionTaskStartedEvent(); for (HistoryEvent event : singleDecisionEvents) { Long lastNonReplayedEventId = historyHelper.getLastNonReplayEventId(); if (event.getEventId() >= lastNonReplayedEventId) { workflowClock.setReplaying(false); } long replayCurrentTimeMilliseconds = historyHelper.getReplayCurrentTimeMilliseconds(); workflowClock.setReplayCurrentTimeMilliseconds(replayCurrentTimeMilliseconds); EventType eventType = EventType.valueOf(event.getEventType()); processEvent(event, eventType); eventLoop(event); } completeWorkflowIfCompleted(); singleDecisionEvents = historyHelper.getSingleDecisionEvents(); } if (unhandledDecision) { unhandledDecision = false; completeWorkflowIfCompleted(); } } public List<AsyncTaskInfo> getAsynchronousThreadDump() { checkAsynchronousThreadDumpState(); return workflowAsyncScope.getAsynchronousThreadDump(); } public String getAsynchronousThreadDumpAsString() { checkAsynchronousThreadDumpState(); return workflowAsyncScope.getAsynchronousThreadDumpAsString(); } private void checkAsynchronousThreadDumpState() { if (workflowAsyncScope == null) { throw new IllegalStateException("workflow hasn't started yet"); } if (decisionsHelper.isWorkflowFailed()) { throw new IllegalStateException("Cannot get AsynchronousThreadDump of a failed workflow", decisionsHelper.getWorkflowFailureCause()); } } public DecisionsHelper getDecisionsHelper() { return decisionsHelper; } public WorkflowDefinition getWorkflowDefinition() { return definition; } }
3,642
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/worker/GenericWorkflowWorker.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.worker; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.ChildWorkflowIdHandler; import com.amazonaws.services.simpleworkflow.flow.DefaultChildWorkflowIdHandler; import com.amazonaws.services.simpleworkflow.flow.WorkflowTypeRegistrationOptions; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.flow.common.FlowHelpers; import com.amazonaws.services.simpleworkflow.flow.common.RequestTimeoutHelper; import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactory; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactoryFactory; import com.amazonaws.services.simpleworkflow.flow.retry.ThrottlingRetrier; import com.amazonaws.services.simpleworkflow.model.RegisterWorkflowTypeRequest; import com.amazonaws.services.simpleworkflow.model.TaskList; import com.amazonaws.services.simpleworkflow.model.TypeAlreadyExistsException; import com.amazonaws.services.simpleworkflow.model.WorkflowType; import lombok.Getter; import lombok.Setter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class GenericWorkflowWorker extends GenericWorker<DecisionTaskPoller.DecisionTaskIterator> { private static final Log log = LogFactory.getLog(GenericWorkflowWorker.class); private static final String THREAD_NAME_PREFIX = "SWF Decider "; @Getter @Setter private WorkflowDefinitionFactoryFactory workflowDefinitionFactoryFactory; @Setter private ChildWorkflowIdHandler childWorkflowIdHandler = new DefaultChildWorkflowIdHandler(); public GenericWorkflowWorker() { super(); } public GenericWorkflowWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll) { super(service, domain, taskListToPoll, null); } public GenericWorkflowWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll, SimpleWorkflowClientConfig config) { super(service, domain, taskListToPoll, config); } protected DecisionTaskPoller createWorkflowPoller() { return new DecisionTaskPoller(); } @Override protected TaskPoller<DecisionTaskPoller.DecisionTaskIterator> createPoller() { DecisionTaskPoller result = new DecisionTaskPoller(); result.setDecisionTaskHandler(new AsyncDecisionTaskHandler(workflowDefinitionFactoryFactory, childWorkflowIdHandler)); result.setDomain(getDomain()); result.setIdentity(getIdentity()); result.setService(getService()); result.setTaskListToPoll(getTaskListToPoll()); return result; } @Override public void registerTypesToPoll() { registerWorkflowTypes(service, domain, getTaskListToPoll(), workflowDefinitionFactoryFactory); } public static void registerWorkflowTypes(AmazonSimpleWorkflow service, String domain, String defaultTaskList, WorkflowDefinitionFactoryFactory workflowDefinitionFactoryFactory) { registerWorkflowTypes(service, domain, defaultTaskList, workflowDefinitionFactoryFactory, null); } public static void registerWorkflowTypes(AmazonSimpleWorkflow service, String domain, String defaultTaskList, WorkflowDefinitionFactoryFactory workflowDefinitionFactoryFactory, SimpleWorkflowClientConfig config) { for (WorkflowType typeToRegister : workflowDefinitionFactoryFactory.getWorkflowTypesToRegister()) { WorkflowDefinitionFactory workflowDefinitionFactory = workflowDefinitionFactoryFactory.getWorkflowDefinitionFactory(typeToRegister); WorkflowTypeRegistrationOptions registrationOptions = workflowDefinitionFactory.getWorkflowRegistrationOptions(); if (registrationOptions != null) { WorkflowType workflowType = workflowDefinitionFactory.getWorkflowType(); try { registerWorkflowType(service, domain, workflowType, registrationOptions, defaultTaskList, config); } catch (TypeAlreadyExistsException ex) { if (log.isTraceEnabled()) { log.trace("Workflow Type already registered: " + workflowType); } } } } } public static void registerWorkflowType(AmazonSimpleWorkflow service, String domain, WorkflowType workflowType, WorkflowTypeRegistrationOptions registrationOptions, String defaultTaskList) { registerWorkflowType(service, domain, workflowType, registrationOptions, defaultTaskList, null); } public static void registerWorkflowType(AmazonSimpleWorkflow service, String domain, WorkflowType workflowType, WorkflowTypeRegistrationOptions registrationOptions, String defaultTaskList, SimpleWorkflowClientConfig config) { RegisterWorkflowTypeRequest registerWorkflow = buildRegisterWorkflowTypeRequest(domain, workflowType, registrationOptions, defaultTaskList); RequestTimeoutHelper.overrideControlPlaneRequestTimeout(registerWorkflow, config); registerWorkflowTypeWithRetry(service, registerWorkflow); } private static RegisterWorkflowTypeRequest buildRegisterWorkflowTypeRequest(String domain, WorkflowType workflowType, WorkflowTypeRegistrationOptions registrationOptions, String defaultTaskList) { RegisterWorkflowTypeRequest registerWorkflow = new RegisterWorkflowTypeRequest(); registerWorkflow.setDomain(domain); registerWorkflow.setName(workflowType.getName()); registerWorkflow.setVersion(workflowType.getVersion()); String taskList = registrationOptions.getDefaultTaskList(); if (taskList == null) { taskList = defaultTaskList; } else if (taskList.equals(FlowConstants.NO_DEFAULT_TASK_LIST)) { taskList = null; } if (taskList != null && !taskList.isEmpty()) { registerWorkflow.setDefaultTaskList(new TaskList().withName(taskList)); } registerWorkflow.setDefaultChildPolicy(registrationOptions.getDefaultChildPolicy().toString()); registerWorkflow.setDefaultTaskStartToCloseTimeout(FlowHelpers.secondsToDuration(registrationOptions.getDefaultTaskStartToCloseTimeoutSeconds())); registerWorkflow.setDefaultExecutionStartToCloseTimeout(FlowHelpers.secondsToDuration(registrationOptions.getDefaultExecutionStartToCloseTimeoutSeconds())); registerWorkflow.setDefaultTaskPriority(FlowHelpers.taskPriorityToString(registrationOptions.getDefaultTaskPriority())); registerWorkflow.setDefaultLambdaRole(registrationOptions.getDefaultLambdaRole()); String description = registrationOptions.getDescription(); if (description != null) { registerWorkflow.setDescription(description); } return registerWorkflow; } private static void registerWorkflowTypeWithRetry(AmazonSimpleWorkflow service, RegisterWorkflowTypeRequest registerWorkflowTypeRequest) { ThrottlingRetrier retrier = new ThrottlingRetrier(getRegisterTypeThrottledRetryParameters()); retrier.retry(() -> service.registerWorkflowType(registerWorkflowTypeRequest)); } @Override protected void checkRequiredProperties() { checkRequiredProperty(workflowDefinitionFactoryFactory, "workflowDefinitionFactoryFactory"); } @Override public String toString() { return this.getClass().getSimpleName() + "[super=" + super.toString() + ", workflowDefinitionFactoryFactory=" + workflowDefinitionFactoryFactory + "]"; } @Override protected String getPollThreadNamePrefix() { return THREAD_NAME_PREFIX + getTaskListToPoll() + " "; } }
3,643
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/worker/BackoffThrottlerWithJitter.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.worker; import java.util.Random; /** * This class is for internal use only and may be changed or removed without prior notice. * */ public class BackoffThrottlerWithJitter extends BackoffThrottler { private final Random rand = new Random(); public BackoffThrottlerWithJitter(long initialSleep, long maxSleep, double backoffCoefficient) { super(initialSleep, maxSleep, backoffCoefficient); } @Override protected long calculateSleepTime() { int delay = (int) (2 * initialSleep * Math.pow(backoffCoefficient, failureCount.get() - 1)); return Math.min(2 * maxSleep, rand.nextInt(delay)); } }
3,644
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/worker/DecisionTaskHandler.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.worker; import java.util.Iterator; import java.util.List; import com.amazonaws.services.simpleworkflow.flow.core.AsyncTaskInfo; import com.amazonaws.services.simpleworkflow.model.DecisionTask; import com.amazonaws.services.simpleworkflow.model.RespondDecisionTaskCompletedRequest; /** * This class is for internal use only and may be changed or removed without prior notice. * * Base class for workflow task handlers. * * @author fateev, suskin * */ public abstract class DecisionTaskHandler { /** * The implementation should be called when a polling SWF Decider receives a * new WorkflowTask. * * @param decisionTaskIterator * The decision task to handle. The reason for more then one task * being received is pagination of the history. All tasks in the * iterator contain the same information but different pages of * the history. The tasks are loaded lazily when * {@link Iterator#next()} is called. It is expected that the * method implementation aborts decision by rethrowing any * exception from {@link Iterator#next()}. */ public abstract RespondDecisionTaskCompletedRequest handleDecisionTask(Iterator<DecisionTask> decisionTaskIterator) throws Exception; public abstract List<AsyncTaskInfo> getAsynchronousThreadDump(Iterator<DecisionTask> decisionTaskIterator) throws Exception; public abstract String getAsynchronousThreadDumpAsString(Iterator<DecisionTask> decisionTaskIterator) throws Exception; public abstract Object loadWorkflowThroughReplay(Iterator<DecisionTask> decisionTaskIterator) throws Exception; }
3,645
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/worker/LambdaFunctionDecisionStateMachine.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.worker; import com.amazonaws.services.simpleworkflow.model.Decision; import com.amazonaws.services.simpleworkflow.model.DecisionType; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.ScheduleLambdaFunctionDecisionAttributes; class LambdaFunctionDecisionStateMachine extends DecisionStateMachineBase { private ScheduleLambdaFunctionDecisionAttributes scheduleAttributes; LambdaFunctionDecisionStateMachine(DecisionId id, ScheduleLambdaFunctionDecisionAttributes scheduleAttributes) { super(id); this.scheduleAttributes = scheduleAttributes; } LambdaFunctionDecisionStateMachine(DecisionId id, ScheduleLambdaFunctionDecisionAttributes scheduleAttributes, DecisionState state) { super(id, state); this.scheduleAttributes = scheduleAttributes; } @Override public Decision getDecision() { switch (state) { case CREATED: return createScheduleLambdaFunctionDecision(); default: return null; } } @Override public void handleDecisionTaskStartedEvent() { switch (state) { case CANCELED_AFTER_INITIATED: stateHistory.add("handleDecisionTaskStartedEvent"); state = DecisionState.CANCELLATION_DECISION_SENT; stateHistory.add(state.toString()); break; default: super.handleDecisionTaskStartedEvent(); } } @Override public void handleCancellationFailureEvent(HistoryEvent event) { switch (state) { case CANCELLATION_DECISION_SENT: stateHistory.add("handleCancellationFailureEvent"); state = DecisionState.INITIATED; stateHistory.add(state.toString()); break; default: super.handleCancellationFailureEvent(event); } } private Decision createScheduleLambdaFunctionDecision() { Decision decision = new Decision(); decision.setScheduleLambdaFunctionDecisionAttributes(scheduleAttributes); decision.setDecisionType(DecisionType.ScheduleLambdaFunction.toString()); return decision; } }
3,646
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/worker/GenericActivityClientImpl.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.worker; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CancellationException; import com.amazonaws.services.simpleworkflow.flow.ActivityTaskFailedException; import com.amazonaws.services.simpleworkflow.flow.ActivityTaskTimedOutException; import com.amazonaws.services.simpleworkflow.flow.ScheduleActivityTaskFailedException; import com.amazonaws.services.simpleworkflow.flow.common.FlowHelpers; 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; import com.amazonaws.services.simpleworkflow.flow.generic.ExecuteActivityParameters; import com.amazonaws.services.simpleworkflow.flow.generic.GenericActivityClient; import com.amazonaws.services.simpleworkflow.model.ActivityTaskCanceledEventAttributes; import com.amazonaws.services.simpleworkflow.model.ActivityTaskCompletedEventAttributes; import com.amazonaws.services.simpleworkflow.model.ActivityTaskFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.ActivityTaskStartedEventAttributes; import com.amazonaws.services.simpleworkflow.model.ActivityTaskTimedOutEventAttributes; import com.amazonaws.services.simpleworkflow.model.ActivityType; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.ScheduleActivityTaskDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.ScheduleActivityTaskFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.TaskList; class GenericActivityClientImpl implements GenericActivityClient { private final class ActivityCancellationHandler implements ExternalTaskCancellationHandler { private final String activityId; private final ExternalTaskCompletionHandle handle; private ActivityCancellationHandler(String activityId, ExternalTaskCompletionHandle handle) { this.activityId = activityId; this.handle = handle; } @Override public void handleCancellation(Throwable cause) { decisions.requestCancelActivityTask(activityId, new Runnable() { @Override public void run() { OpenRequestInfo<String, ActivityType> scheduled = scheduledActivities.remove(activityId); if (scheduled == null) { throw new IllegalArgumentException("Activity \"" + activityId + "\" wasn't scheduled"); } handle.complete(); } }); } } private final DecisionsHelper decisions; private final Map<String, OpenRequestInfo<String, ActivityType>> scheduledActivities = new HashMap<String, OpenRequestInfo<String, ActivityType>>(); public GenericActivityClientImpl(DecisionsHelper decisions) { this.decisions = decisions; } @Override public Promise<String> scheduleActivityTask(final ExecuteActivityParameters parameters) { final OpenRequestInfo<String, ActivityType> context = new OpenRequestInfo<String, ActivityType>( parameters.getActivityType()); final ScheduleActivityTaskDecisionAttributes attributes = new ScheduleActivityTaskDecisionAttributes(); attributes.setActivityType(parameters.getActivityType()); attributes.setInput(parameters.getInput()); attributes.setHeartbeatTimeout(FlowHelpers.secondsToDuration(parameters.getHeartbeatTimeoutSeconds())); attributes.setScheduleToCloseTimeout(FlowHelpers.secondsToDuration(parameters.getScheduleToCloseTimeoutSeconds())); attributes.setScheduleToStartTimeout(FlowHelpers.secondsToDuration(parameters.getScheduleToStartTimeoutSeconds())); attributes.setStartToCloseTimeout(FlowHelpers.secondsToDuration(parameters.getStartToCloseTimeoutSeconds())); attributes.setTaskPriority(FlowHelpers.taskPriorityToString(parameters.getTaskPriority())); String activityId = parameters.getActivityId(); if (activityId == null) { activityId = String.valueOf(decisions.getNextId()); } attributes.setActivityId(activityId); attributes.setControl(parameters.getControl()); String taskList = parameters.getTaskList(); if (taskList != null && !taskList.isEmpty()) { attributes.setTaskList(new TaskList().withName(taskList)); } String taskName = "activityId=" + activityId + ", activityType=" + attributes.getActivityType(); new ExternalTask() { @Override protected ExternalTaskCancellationHandler doExecute(final ExternalTaskCompletionHandle handle) throws Throwable { decisions.scheduleActivityTask(attributes); context.setCompletionHandle(handle); scheduledActivities.put(attributes.getActivityId(), context); return new ActivityCancellationHandler(attributes.getActivityId(), handle); } }.setName(taskName); context.setResultDescription("scheduleActivityTask " + taskName); return context.getResult(); } @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; } @Override public Promise<String> scheduleActivityTask(String activity, String version, String input) { ExecuteActivityParameters parameters = new ExecuteActivityParameters(); parameters.setActivityType(new ActivityType().withName(activity).withVersion(version)); parameters.setInput(input); return scheduleActivityTask(parameters); } void handleActivityTaskStarted(ActivityTaskStartedEventAttributes attributes) { } void handleActivityTaskCanceled(HistoryEvent event) { ActivityTaskCanceledEventAttributes attributes = event.getActivityTaskCanceledEventAttributes(); String activityId = decisions.getActivityId(attributes); if (decisions.handleActivityTaskCanceled(event)) { CancellationException e = new CancellationException(); OpenRequestInfo<String, ActivityType> scheduled = scheduledActivities.remove(activityId); if (scheduled != null) { ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); // It is OK to fail with subclass of CancellationException when cancellation requested. // It allows passing information about cancellation (details in this case) to the surrounding doCatch block completionHandle.fail(e); } } } void handleScheduleActivityTaskFailed(HistoryEvent event) { ScheduleActivityTaskFailedEventAttributes attributes = event.getScheduleActivityTaskFailedEventAttributes(); String activityId = attributes.getActivityId(); OpenRequestInfo<String, ActivityType> scheduled = scheduledActivities.remove(activityId); if (decisions.handleScheduleActivityTaskFailed(event)) { String cause = attributes.getCause(); ScheduleActivityTaskFailedException failure = new ScheduleActivityTaskFailedException(event.getEventId(), attributes.getActivityType(), activityId, cause); ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); completionHandle.fail(failure); } } void handleActivityTaskCompleted(HistoryEvent event) { ActivityTaskCompletedEventAttributes attributes = event.getActivityTaskCompletedEventAttributes(); String activityId = decisions.getActivityId(attributes); if (decisions.handleActivityTaskClosed(activityId)) { OpenRequestInfo<String, ActivityType> scheduled = scheduledActivities.remove(activityId); if (scheduled != null) { String result = attributes.getResult(); scheduled.getResult().set(result); ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); completionHandle.complete(); } } } void handleActivityTaskFailed(HistoryEvent event) { ActivityTaskFailedEventAttributes attributes = event.getActivityTaskFailedEventAttributes(); String activityId = decisions.getActivityId(attributes); if (decisions.handleActivityTaskClosed(activityId)) { OpenRequestInfo<String, ActivityType> scheduled = scheduledActivities.remove(activityId); if (scheduled != null) { String reason = attributes.getReason(); String details = attributes.getDetails(); ActivityTaskFailedException failure = new ActivityTaskFailedException(event.getEventId(), scheduled.getUserContext(), activityId, reason, details); ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); completionHandle.fail(failure); } } } void handleActivityTaskTimedOut(HistoryEvent event) { ActivityTaskTimedOutEventAttributes attributes = event.getActivityTaskTimedOutEventAttributes(); String activityId = decisions.getActivityId(attributes); if (decisions.handleActivityTaskClosed(activityId)) { OpenRequestInfo<String, ActivityType> scheduled = scheduledActivities.remove(activityId); if (scheduled != null) { String timeoutType = attributes.getTimeoutType(); String details = attributes.getDetails(); ActivityTaskTimedOutException failure = new ActivityTaskTimedOutException(event.getEventId(), scheduled.getUserContext(), activityId, timeoutType, details); ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); completionHandle.fail(failure); } } } }
3,647
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/worker/DecisionTarget.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.worker; enum DecisionTarget { ACTIVITY, LAMBDA_FUNCTION, EXTERNAL_WORKFLOW, SIGNAL, TIMER, SELF }
3,648
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/worker/ComponentVersion.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.worker; /** * @author fateev */ class ComponentVersion { private final String componentName; private int maximumSupportedImplementationVersion; private int minimumSupportedImplementationVersion; private int maximumAllowedImplementationVersion = Integer.MAX_VALUE; /** * Actual current version */ private int currentVersion; private Integer versionFromHistory; private Integer maxSkippedVersion; public ComponentVersion(String componentName) { this.componentName = componentName; } void setVersionFromHistory(int version) { if (versionFromHistory != null && version < versionFromHistory) { throw new IncompatibleWorkflowDefinition("Version from history cannot decrease from " + versionFromHistory + " to " + version + " for \"" + componentName + "\" component"); } currentVersion = version; versionFromHistory = version; } public String getComponentName() { return componentName; } public int getMaximumSupportedImplementationVersion() { return maximumSupportedImplementationVersion; } public void setMaximumSupportedImplementationVersion(int maximumSupportedImplementationVersion) { if (versionFromHistory != null && maximumSupportedImplementationVersion < versionFromHistory) { throw new IncompatibleWorkflowDefinition("Maximum supported implementation version=" + maximumSupportedImplementationVersion + " is below one found in the history " + versionFromHistory + " for \"" + componentName + "\" component."); } this.maximumSupportedImplementationVersion = maximumSupportedImplementationVersion; } public int getMinimumSupportedImplementationVersion() { return minimumSupportedImplementationVersion; } public void setMinimumSupportedImplementationVersion(int minimumSupportedImplementationVersion) { this.minimumSupportedImplementationVersion = minimumSupportedImplementationVersion; if (versionFromHistory != null && versionFromHistory < minimumSupportedImplementationVersion) { throw new IncompatibleWorkflowDefinition("Minimum supported implementation version=" + minimumSupportedImplementationVersion + " is larger than one found in the history " + versionFromHistory + " for \"" + componentName + "\" component."); } if (maximumAllowedImplementationVersion < minimumSupportedImplementationVersion) { throw new IncompatibleWorkflowDefinition("Minimum supported implementation version=" + minimumSupportedImplementationVersion + " is larger than maximumAllowedImplementationVersion=" + maximumAllowedImplementationVersion + " for \"" + componentName + "\" component."); } if (minimumSupportedImplementationVersion > currentVersion) { currentVersion = minimumSupportedImplementationVersion; } } public int getMaximumAllowedImplementationVersion() { return maximumAllowedImplementationVersion; } public void setMaximumAllowedImplementationVersion(int maximumAllowedImplementationVersion) { this.maximumAllowedImplementationVersion = maximumAllowedImplementationVersion; } public int getCurrentVersion() { return currentVersion; } public boolean isVersion(int version, boolean replaying) { if (maximumSupportedImplementationVersion < version) { throw new IncompatibleWorkflowDefinition("version=" + version + " is larger than maximumSupportedImplementationVersion=" + maximumSupportedImplementationVersion + " for \"" + componentName + "\" component."); } if (minimumSupportedImplementationVersion > version) { throw new IncompatibleWorkflowDefinition("version=" + version + " is smaller than minimumSupportedImplementationVersion=" + minimumSupportedImplementationVersion + " for \"" + componentName + "\" component."); } if (maxSkippedVersion != null && maxSkippedVersion <= version) { return false; } if (currentVersion >= version) { return true; } else if (replaying) { if (version == minimumSupportedImplementationVersion) { currentVersion = version; return true; } if (maxSkippedVersion == null || maxSkippedVersion < version) { maxSkippedVersion = version; } return false; } else { if (maximumAllowedImplementationVersion < version) { return false; } currentVersion = version; return true; } } }
3,649
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/worker/DecisionStateMachineBase.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.worker; import java.util.ArrayList; import java.util.List; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; abstract class DecisionStateMachineBase implements DecisionStateMachine { protected DecisionState state = DecisionState.CREATED; protected List<String> stateHistory = new ArrayList<String>(); protected DecisionId id; public DecisionStateMachineBase(DecisionId id) { this.id = id; stateHistory.add(state.toString()); } /** * Used for unit testing. */ protected DecisionStateMachineBase(DecisionId id, DecisionState state) { this.id = id; this.state = state; stateHistory.add(state.toString()); } public DecisionState getState() { return state; } public DecisionId getId() { return id; } @Override public boolean isDone() { return state == DecisionState.COMPLETED || state == DecisionState.COMPLETED_AFTER_CANCELLATION_DECISION_SENT; } @Override public void handleDecisionTaskStartedEvent() { switch (state) { case CREATED: stateHistory.add("handleDecisionTaskStartedEvent"); state = DecisionState.DECISION_SENT; stateHistory.add(state.toString()); break; } } @Override public void cancel(Runnable immediateCancellationCallback) { stateHistory.add("cancel"); switch (state) { case CREATED: state = DecisionState.COMPLETED; if (immediateCancellationCallback != null) { immediateCancellationCallback.run(); } break; case DECISION_SENT: state = DecisionState.CANCELED_BEFORE_INITIATED; break; case INITIATED: state = DecisionState.CANCELED_AFTER_INITIATED; break; default: failStateTransition(); } stateHistory.add(state.toString()); } @Override public void handleInitiatedEvent(HistoryEvent event) { stateHistory.add("handleInitiatedEvent"); switch (state) { case DECISION_SENT: state = DecisionState.INITIATED; break; case CANCELED_BEFORE_INITIATED: state = DecisionState.CANCELED_AFTER_INITIATED; break; case COMPLETED: state = DecisionState.COMPLETED; break; default: failStateTransition(); } stateHistory.add(state.toString()); } @Override public void handleInitiationFailedEvent(HistoryEvent event) { stateHistory.add("handleInitiationFailedEvent"); switch (state) { case INITIATED: case DECISION_SENT: case CANCELED_BEFORE_INITIATED: state = DecisionState.COMPLETED; break; default: failStateTransition(); } stateHistory.add(state.toString()); } @Override public void handleStartedEvent(HistoryEvent event) { stateHistory.add("handleStartedEvent"); } @Override public void handleCompletionEvent() { stateHistory.add("handleCompletionEvent"); switch (state) { case CANCELED_AFTER_INITIATED: case INITIATED: state = DecisionState.COMPLETED; break; case CANCELLATION_DECISION_SENT: state = DecisionState.COMPLETED_AFTER_CANCELLATION_DECISION_SENT; break; default: failStateTransition(); } stateHistory.add(state.toString()); } @Override public void handleCancellationInitiatedEvent() { stateHistory.add("handleCancellationInitiatedEvent"); switch (state) { case CANCELLATION_DECISION_SENT: // No state change break; default: failStateTransition(); } stateHistory.add(state.toString()); } @Override public void handleCancellationFailureEvent(HistoryEvent event) { stateHistory.add("handleCancellationFailureEvent"); switch (state) { case COMPLETED_AFTER_CANCELLATION_DECISION_SENT: state = DecisionState.COMPLETED; break; default: failStateTransition(); } stateHistory.add(state.toString()); } @Override public void handleCancellationEvent() { stateHistory.add("handleCancellationEvent"); switch (state) { case CANCELLATION_DECISION_SENT: state = DecisionState.COMPLETED; break; default: failStateTransition(); } stateHistory.add(state.toString()); } @Override public String toString() { return "DecisionStateMachineBase [id=" + id + ", state=" + state + ", isDone()=" + isDone() + ", stateHistory=" + stateHistory + "]"; } protected void failStateTransition() { throw new IllegalStateException("id=" + id + ", transitions=" + stateHistory); } }
3,650
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/worker/Throttler.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.worker; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class Throttler { private static final Log log = LogFactory.getLog(Throttler.class); /** * Human readable name of the resource being throttled. * Used for logging only. */ private final String name_; /** * Used as a circular buffer */ private CircularLongBuffer checkPointTimes_; /** * Used as an index to a circular buffer */ private long index_; /** * Interval used to measure the rate. Shorter interval allows less spikey * rates. */ private long rateInterval_; private long rateIntervalMilliseconds_; private long overslept_; /** * Construct throttler. * @param name Human readable name of the resource being throttled. Used for logging only. * @param maxRatePerSecond maximum rate allowed * @param rateIntervalMilliseconds rate measurement interval. Interval should be at least * 1000 / maxRatePerSecond. */ public Throttler(String name, double maxRatePerSecond, long rateIntervalMilliseconds) { if (null == name) { throw new IllegalArgumentException("null name"); } name_ = name; if (maxRatePerSecond <= 0) { throw new IllegalArgumentException("0 or negative maxRatePerSecond"); } if (rateIntervalMilliseconds <= 0) { throw new IllegalArgumentException("0 or negative rateIntervalMilliseconds"); } synchronized(this) { rateIntervalMilliseconds_ = rateIntervalMilliseconds; setMaxRatePerSecond(maxRatePerSecond); } } public synchronized void setMaxRatePerSecond(double maxRatePerSecond) { int maxMessagesPerRateInterval = (int) (maxRatePerSecond * rateIntervalMilliseconds_ / 1000); if (maxMessagesPerRateInterval == 0) { maxMessagesPerRateInterval = 1; rateInterval_ = (long) (1.0 / maxRatePerSecond * 1000.0); } else { rateInterval_ = rateIntervalMilliseconds_; } if (checkPointTimes_ != null) { int oldSize = checkPointTimes_.size(); checkPointTimes_ = checkPointTimes_.copy(index_ - maxMessagesPerRateInterval, maxMessagesPerRateInterval); index_ = Math.min(checkPointTimes_.size(), oldSize); } else { checkPointTimes_ = new CircularLongBuffer(maxMessagesPerRateInterval); index_ = 0; } log.debug("new rate=" + maxRatePerSecond + " (msg/sec)"); } public synchronized void throttle(int count) throws InterruptedException { for(int i=0; i<count; ++i) { throttle(); } } /** * When called on each request sleeps if called faster then configured average rate. * @throws InterruptedException when interrupted */ public synchronized void throttle() throws InterruptedException { long now = System.currentTimeMillis(); long checkPoint = checkPointTimes_.get(index_); if (checkPoint > 0) { long elapsed = now - checkPoint; // if the time for this window is less than the minimum per window if (elapsed >= 0 && elapsed < rateInterval_) { long sleepInterval = rateInterval_ - elapsed - overslept_; overslept_ = 0; if (sleepInterval > 0) { if (log.isTraceEnabled()) { log.debug("Throttling " + name_ + ": called " + checkPointTimes_.size() + " times in last " + elapsed + " milliseconds. Going to sleep for " + sleepInterval + " milliseconds."); } long t = System.currentTimeMillis(); Thread.sleep(sleepInterval); overslept_ = System.currentTimeMillis() - t - sleepInterval; } } } checkPointTimes_.set(index_++, System.currentTimeMillis()); } }
3,651
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/worker/CurrentActivityExecutionContext.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.worker; import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContext; import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContextProviderImpl; /** * Thread local store of the context object passed to an activity * implementation. Avoid using this class directly. Use * {@link ActivityExecutionContextProviderImpl} instead. * * @author fateev */ public class CurrentActivityExecutionContext { private final static ThreadLocal<ActivityExecutionContext> CURRENT = new ThreadLocal<ActivityExecutionContext>(); /** * This is used by activity implementation to get access to the current * ActivityExecutionContext */ public static ActivityExecutionContext get() { ActivityExecutionContext result = CURRENT.get(); if (result == null) { throw new IllegalStateException("ActivityExecutionContext can be used only inside of acitivty implementation methods"); } return result; }; public static boolean isSet() { return CURRENT.get() != null; } public static void set(ActivityExecutionContext context) { if (context == null) { throw new IllegalArgumentException("null context"); } CURRENT.set(context); } public static void unset() { CURRENT.set(null); } private CurrentActivityExecutionContext() { } }
3,652
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/worker/ComponentVersions.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.worker; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Pattern; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowTypeComponentImplementationVersion; /** * @author fateev * */ class ComponentVersions { private final Map<String, ComponentVersion> versions = new HashMap<String, ComponentVersion>(); void setVersionFromHistory(String component, int version) { ComponentVersion cv = getComponentVersion(component); cv.setVersionFromHistory(version); } public Map<String, Integer> getVersionsToSave() { Map<String, Integer> result = new HashMap<String, Integer>(); for (Entry<String, ComponentVersion> pair : versions.entrySet()) { ComponentVersion version = pair.getValue(); int currentVersion = version.getCurrentVersion(); if (currentVersion > 0) { result.put(pair.getKey(), currentVersion); } } return result; } private ComponentVersion getComponentVersion(String component) { ComponentVersion cv = versions.get(component); if (cv == null) { cv = new ComponentVersion(component); versions.put(component, cv); } return cv; } public boolean isVersion(String component, int version, boolean replaying) { if (component.contains(AsyncDecisionTaskHandler.COMPONENT_VERSION_SEPARATOR)) { throw new IncompatibleWorkflowDefinition("component name cannot contain character with code=" + Pattern.quote(AsyncDecisionTaskHandler.COMPONENT_VERSION_SEPARATOR)); } ComponentVersion cv = versions.get(component); if (cv == null) { cv = new ComponentVersion(component); versions.put(component, cv); if (cv.isVersion(version, replaying)) { return true; } return false; } else { return cv.isVersion(version, replaying); } } /** * @param component * @return */ public Integer getCurrentVersion(String component) { ComponentVersion cv = versions.get(component); if (cv == null) { return null; } return cv.getCurrentVersion(); } public void setWorkflowImplementationComponentVersions(List<WorkflowTypeComponentImplementationVersion> versions) { for (WorkflowTypeComponentImplementationVersion version : versions) { String componentName = version.getComponentName(); ComponentVersion componentVersion = getComponentVersion(componentName); componentVersion.setMaximumAllowedImplementationVersion(version.getMaximumAllowed()); componentVersion.setMaximumSupportedImplementationVersion(version.getMaximumSupported()); componentVersion.setMinimumSupportedImplementationVersion(version.getMinimumSupported()); } } public List<WorkflowTypeComponentImplementationVersion> getWorkflowImplementationComponentVersions() { List<WorkflowTypeComponentImplementationVersion> result = new ArrayList<WorkflowTypeComponentImplementationVersion>(); for (ComponentVersion version : versions.values()) { String componentName = version.getComponentName(); int minimumSupportedImplementationVersion = version.getMaximumSupportedImplementationVersion(); int maximumSupportedImplementationVersion = version.getMaximumSupportedImplementationVersion(); int maximumAllowedImplementationVersion = version.getMaximumAllowedImplementationVersion(); WorkflowTypeComponentImplementationVersion iv = new WorkflowTypeComponentImplementationVersion(componentName, minimumSupportedImplementationVersion, maximumSupportedImplementationVersion, maximumAllowedImplementationVersion); result.add(iv); } return result; } }
3,653
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/worker/DecisionState.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.worker; enum DecisionState { CREATED, DECISION_SENT, CANCELED_BEFORE_INITIATED, INITIATED, STARTED, CANCELED_AFTER_INITIATED, CANCELED_AFTER_STARTED, CANCELLATION_DECISION_SENT, COMPLETED_AFTER_CANCELLATION_DECISION_SENT, COMPLETED }
3,654
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/worker/ChildWorkflowDecisionStateMachine.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.worker; import com.amazonaws.services.simpleworkflow.model.Decision; import com.amazonaws.services.simpleworkflow.model.DecisionType; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.RequestCancelExternalWorkflowExecutionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.StartChildWorkflowExecutionDecisionAttributes; class ChildWorkflowDecisionStateMachine extends DecisionStateMachineBase { private final StartChildWorkflowExecutionDecisionAttributes startAttributes; private String workflowId; public ChildWorkflowDecisionStateMachine(DecisionId id, StartChildWorkflowExecutionDecisionAttributes startAttributes) { super(id); this.startAttributes = startAttributes; this.workflowId = startAttributes.getWorkflowId(); } /** * Used for unit testing */ ChildWorkflowDecisionStateMachine(DecisionId id, StartChildWorkflowExecutionDecisionAttributes startAttributes, DecisionState state) { super(id, state); this.startAttributes = startAttributes; this.workflowId = startAttributes.getWorkflowId(); } @Override public Decision getDecision() { switch (state) { case CREATED: return createStartChildWorkflowExecutionDecision(); case CANCELED_AFTER_STARTED: return createRequestCancelExternalWorkflowExecutionDecision(); default: return null; } } @Override public void handleDecisionTaskStartedEvent() { switch (state) { case CANCELED_AFTER_STARTED: state = DecisionState.CANCELLATION_DECISION_SENT; break; default: super.handleDecisionTaskStartedEvent(); } } @Override public void handleInitiatedEvent(HistoryEvent event) { String actualWorkflowId = event.getStartChildWorkflowExecutionInitiatedEventAttributes().getWorkflowId(); if (!workflowId.equals(actualWorkflowId)) { workflowId = actualWorkflowId; id = new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, actualWorkflowId); } super.handleInitiatedEvent(event); } @Override public void handleInitiationFailedEvent(HistoryEvent event) { String actualWorkflowId = event.getStartChildWorkflowExecutionFailedEventAttributes().getWorkflowId(); if (!workflowId.equals(actualWorkflowId)) { workflowId = actualWorkflowId; id = new DecisionId(DecisionTarget.EXTERNAL_WORKFLOW, actualWorkflowId); } super.handleInitiationFailedEvent(event); } @Override public void handleStartedEvent(HistoryEvent event) { stateHistory.add("handleStartedEvent"); switch (state) { case INITIATED: state = DecisionState.STARTED; break; case CANCELED_AFTER_INITIATED: state = DecisionState.CANCELED_AFTER_STARTED; break; } stateHistory.add(state.toString()); } @Override public void handleCancellationFailureEvent(HistoryEvent event) { switch (state) { case CANCELLATION_DECISION_SENT: stateHistory.add("handleCancellationFailureEvent"); state = DecisionState.STARTED; stateHistory.add(state.toString()); break; default: super.handleCancellationFailureEvent(event); } } @Override public void cancel(Runnable immediateCancellationCallback) { switch (state) { case STARTED: stateHistory.add("cancel"); state = DecisionState.CANCELED_AFTER_STARTED; stateHistory.add(state.toString()); break; default: super.cancel(immediateCancellationCallback); } } @Override public void handleCancellationEvent() { switch (state) { case STARTED: stateHistory.add("handleCancellationEvent"); state = DecisionState.COMPLETED; stateHistory.add(state.toString()); break; default: super.handleCancellationEvent(); } } @Override public void handleCompletionEvent() { switch (state) { case STARTED: case COMPLETED: case CANCELED_AFTER_STARTED: stateHistory.add("handleCompletionEvent"); state = DecisionState.COMPLETED; stateHistory.add(state.toString()); break; default: super.handleCompletionEvent(); } } private Decision createRequestCancelExternalWorkflowExecutionDecision() { RequestCancelExternalWorkflowExecutionDecisionAttributes tryCancel = new RequestCancelExternalWorkflowExecutionDecisionAttributes(); tryCancel.setWorkflowId(workflowId); Decision decision = new Decision(); decision.setRequestCancelExternalWorkflowExecutionDecisionAttributes(tryCancel); decision.setDecisionType(DecisionType.RequestCancelExternalWorkflowExecution.toString()); return decision; } private Decision createStartChildWorkflowExecutionDecision() { Decision decision = new Decision(); decision.setStartChildWorkflowExecutionDecisionAttributes(startAttributes); decision.setDecisionType(DecisionType.StartChildWorkflowExecution.toString()); return decision; } }
3,655
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/worker/DecisionTaskPoller.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.worker; import java.lang.management.ManagementFactory; import java.time.Duration; import java.util.Iterator; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.amazonaws.services.simpleworkflow.flow.common.RequestTimeoutHelper; import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils; import com.amazonaws.services.simpleworkflow.model.DecisionTask; import com.amazonaws.services.simpleworkflow.model.PollForDecisionTaskRequest; import com.amazonaws.services.simpleworkflow.model.RespondDecisionTaskCompletedRequest; import com.amazonaws.services.simpleworkflow.model.TaskList; /** * This class is for internal use only and may be changed or removed without prior notice. * */ public class DecisionTaskPoller implements TaskPoller<DecisionTaskPoller.DecisionTaskIterator> { private static final Log log = LogFactory.getLog(DecisionTaskPoller.class); private static final Log decisionsLog = LogFactory.getLog(DecisionTaskPoller.class.getName() + ".decisions"); protected class DecisionTaskIterator implements Iterator<DecisionTask> { private final DecisionTask firstDecisionTask; private DecisionTask next; final long startedTime; int pages; public DecisionTaskIterator() { startedTime = System.nanoTime(); pages = 1; next = firstDecisionTask = poll(null); } @Override public boolean hasNext() { return next != null; } @Override public DecisionTask next() { if (!hasNext()) { throw new IllegalStateException("hasNext() == false"); } DecisionTask result = next; if (next.getNextPageToken() == null) { next = null; if (log.isDebugEnabled()) { final long iteratorCompletionTime = System.nanoTime(); log.debug(String.format("Finished paginating request. NumPages [%d]. Duration: [%dms]. Domain: [%s]. TaskList [%s].", pages, Duration.ofNanos(iteratorCompletionTime - startedTime).toMillis(), domain, taskListToPoll)); } } else { try { next = poll(next.getNextPageToken()); pages++; } catch (Exception e) { // Error is used as it fails a decision instead of affecting workflow code throw new Error("Failure getting next page of history events.", e); } // Just to not keep around the history page if (firstDecisionTask != result) { firstDecisionTask.setEvents(null); } } return result; } @Override public void remove() { throw new UnsupportedOperationException(); } public DecisionTask getFirstDecisionTask() { return firstDecisionTask; } } private AmazonSimpleWorkflow service; private String domain; private String taskListToPoll; private String identity; private boolean validated; private DecisionTaskHandler decisionTaskHandler; private boolean suspended; private final Lock lock = new ReentrantLock(); private final Condition suspentionCondition = lock.newCondition(); private SimpleWorkflowClientConfig config; public DecisionTaskPoller() { identity = ManagementFactory.getRuntimeMXBean().getName(); } public DecisionTaskPoller(AmazonSimpleWorkflow service, String domain, String taskListToPoll, DecisionTaskHandler decisionTaskHandler) { this(service, domain, taskListToPoll, decisionTaskHandler, null); } public DecisionTaskPoller(AmazonSimpleWorkflow service, String domain, String taskListToPoll, DecisionTaskHandler decisionTaskHandler, SimpleWorkflowClientConfig config) { this.service = service; this.domain = domain; this.taskListToPoll = taskListToPoll; this.decisionTaskHandler = decisionTaskHandler; identity = ManagementFactory.getRuntimeMXBean().getName(); this.config = config; } public String getIdentity() { return identity; } public void setIdentity(String identity) { validated = false; this.identity = identity; } public AmazonSimpleWorkflow getService() { return service; } public String getDomain() { return domain; } public DecisionTaskHandler getDecisionTaskHandler() { return decisionTaskHandler; } public void setDecisionTaskHandler(DecisionTaskHandler decisionTaskHandler) { validated = false; this.decisionTaskHandler = decisionTaskHandler; } public void setService(AmazonSimpleWorkflow service) { validated = false; this.service = service; } public void setDomain(String domain) { this.domain = domain; } public String getTaskListToPoll() { return taskListToPoll; } public void setTaskListToPoll(String pollTaskList) { this.taskListToPoll = pollTaskList; } public void setSimpleWorkflowClientConfig(SimpleWorkflowClientConfig config) { this.config = config; } public SimpleWorkflowClientConfig getSimpleWorkflowClientConfig() { return config; } /** * Poll for a task using {@link #getPollTimeoutInSeconds()} * * @param nextResultToken * * @return null if poll timed out * @throws DeciderExecutorConfigurationException */ private DecisionTask poll(String nextResultToken) { validate(); PollForDecisionTaskRequest pollRequest = new PollForDecisionTaskRequest(); pollRequest.setDomain(domain); pollRequest.setIdentity(identity); pollRequest.setNextPageToken(nextResultToken); pollRequest.setTaskList(new TaskList().withName(taskListToPoll)); if (log.isDebugEnabled()) { log.debug("poll request begin: " + pollRequest); } RequestTimeoutHelper.overridePollRequestTimeout(pollRequest, config); DecisionTask result = service.pollForDecisionTask(pollRequest); if (log.isDebugEnabled()) { log.debug("poll request returned decision task: workflowType=" + result.getWorkflowType() + ", workflowExecution=" + result.getWorkflowExecution() + ", startedEventId=" + result.getStartedEventId() + ", previousStartedEventId=" + result.getPreviousStartedEventId()); } if (result == null || result.getTaskToken() == null) { return null; } return result; } @Override public DecisionTaskIterator poll() throws InterruptedException { waitIfSuspended(); DecisionTaskIterator tasks = new DecisionTaskIterator(); if (!tasks.hasNext()) { return null; } return tasks; } @Override public void execute(final DecisionTaskIterator tasks) throws Exception { RespondDecisionTaskCompletedRequest taskCompletedRequest = null; try { taskCompletedRequest = decisionTaskHandler.handleDecisionTask(tasks); if (decisionsLog.isTraceEnabled()) { decisionsLog.trace(WorkflowExecutionUtils.prettyPrintDecisions(taskCompletedRequest.getDecisions())); } RequestTimeoutHelper.overrideDataPlaneRequestTimeout(taskCompletedRequest, config); service.respondDecisionTaskCompleted(taskCompletedRequest); } catch (Error e) { DecisionTask firstTask = tasks.getFirstDecisionTask(); if (firstTask != null) { if (log.isWarnEnabled()) { log.warn("DecisionTask failure: taskId= " + firstTask.getStartedEventId() + ", workflowExecution=" + firstTask.getWorkflowExecution(), e); } } throw e; } catch (Exception e) { DecisionTask firstTask = tasks.getFirstDecisionTask(); if (firstTask != null) { if (log.isWarnEnabled()) { log.warn("DecisionTask failure: taskId= " + firstTask.getStartedEventId() + ", workflowExecution=" + firstTask.getWorkflowExecution(), e); } if (log.isDebugEnabled() && firstTask.getEvents() != null) { log.debug("Failed taskId=" + firstTask.getStartedEventId() + " history: " + WorkflowExecutionUtils.prettyPrintHistory(firstTask.getEvents(), true)); } } if (taskCompletedRequest != null && decisionsLog.isWarnEnabled()) { decisionsLog.warn("Failed taskId=" + firstTask.getStartedEventId() + " decisions=" + WorkflowExecutionUtils.prettyPrintDecisions(taskCompletedRequest.getDecisions())); } throw e; } } private void waitIfSuspended() throws InterruptedException { lock.lock(); try { while (suspended) { suspentionCondition.await(); } } finally { lock.unlock(); } } /** * @param seconds * @return */ private void validate() throws IllegalStateException { if (validated) { return; } checkFieldSet("decisionTaskHandler", decisionTaskHandler); checkFieldSet("service", service); checkFieldSet("identity", identity); validated = true; } private void checkFieldSet(String fieldName, Object fieldValue) throws IllegalStateException { if (fieldValue == null) { throw new IllegalStateException("Required field " + fieldName + " is not set"); } } protected void checkFieldNotNegative(String fieldName, long fieldValue) throws IllegalStateException { if (fieldValue < 0) { throw new IllegalStateException("Field " + fieldName + " is negative"); } } @Override public void suspend() { lock.lock(); try { suspended = true; } finally { lock.unlock(); } } @Override public void resume() { lock.lock(); try { suspended = false; suspentionCondition.signalAll(); } finally { lock.unlock(); } } @Override public boolean isSuspended() { lock.lock(); try { return suspended; } finally { lock.unlock(); } } @Override public SuspendableSemaphore getPollingSemaphore() { // No polling semaphore for DecisionTaskPoller return null; } }
3,656
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/worker/GenericWorkflowClientImpl.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.worker; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import com.amazonaws.services.simpleworkflow.flow.ChildWorkflowFailedException; import com.amazonaws.services.simpleworkflow.flow.ChildWorkflowTerminatedException; import com.amazonaws.services.simpleworkflow.flow.ChildWorkflowTimedOutException; import com.amazonaws.services.simpleworkflow.flow.SignalExternalWorkflowException; import com.amazonaws.services.simpleworkflow.flow.StartChildWorkflowFailedException; import com.amazonaws.services.simpleworkflow.flow.WorkflowContext; import com.amazonaws.services.simpleworkflow.flow.common.FlowHelpers; 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.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.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.model.ChildPolicy; import com.amazonaws.services.simpleworkflow.model.ChildWorkflowExecutionCanceledEventAttributes; import com.amazonaws.services.simpleworkflow.model.ChildWorkflowExecutionCompletedEventAttributes; import com.amazonaws.services.simpleworkflow.model.ChildWorkflowExecutionFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.ChildWorkflowExecutionStartedEventAttributes; import com.amazonaws.services.simpleworkflow.model.ChildWorkflowExecutionTerminatedEventAttributes; import com.amazonaws.services.simpleworkflow.model.ChildWorkflowExecutionTimedOutEventAttributes; import com.amazonaws.services.simpleworkflow.model.ExternalWorkflowExecutionSignaledEventAttributes; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.RequestCancelExternalWorkflowExecutionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.SignalExternalWorkflowExecutionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.SignalExternalWorkflowExecutionFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.StartChildWorkflowExecutionDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.StartChildWorkflowExecutionFailedCause; import com.amazonaws.services.simpleworkflow.model.StartChildWorkflowExecutionFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.TaskList; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; import com.amazonaws.services.simpleworkflow.model.WorkflowType; class GenericWorkflowClientImpl implements GenericWorkflowClient { private static class StartChildWorkflowReplyImpl implements StartChildWorkflowReply { private String workflowId; private String runId; private final Settable<String> result = new Settable<String>(); public StartChildWorkflowReplyImpl(String workflowId, String runId, String description) { this.runId = runId; this.workflowId = workflowId; result.setDescription(description); } @Override public String getWorkflowId() { return workflowId; } @Override public String getRunId() { return runId; } @Override public Promise<String> getResult() { return result; } public void setResult(String value) { result.set(value); } } private final class ChildWorkflowCancellationHandler implements ExternalTaskCancellationHandler { private final String requestedWorkflowId; private final ExternalTaskCompletionHandle handle; private ChildWorkflowCancellationHandler(String requestedWorkflowId, ExternalTaskCompletionHandle handle) { this.requestedWorkflowId = requestedWorkflowId; this.handle = handle; } @Override public void handleCancellation(Throwable cause) { RequestCancelExternalWorkflowExecutionDecisionAttributes cancelAttributes = new RequestCancelExternalWorkflowExecutionDecisionAttributes(); String actualWorkflowId = decisions.getActualChildWorkflowId(requestedWorkflowId); cancelAttributes.setWorkflowId(actualWorkflowId); decisions.requestCancelExternalWorkflowExecution(cancelAttributes, new Runnable() { @Override public void run() { OpenRequestInfo<StartChildWorkflowReply, WorkflowType> scheduled = scheduledExternalWorkflows.remove(actualWorkflowId); if (scheduled == null) { throw new IllegalArgumentException("Workflow \"" + actualWorkflowId + "\" wasn't scheduled"); } handle.complete(); } }); } } private final DecisionsHelper decisions; private final WorkflowContext workflowContext; private final Map<String, OpenRequestInfo<StartChildWorkflowReply, WorkflowType>> scheduledExternalWorkflows = new HashMap<String, OpenRequestInfo<StartChildWorkflowReply, WorkflowType>>(); private final Map<String, OpenRequestInfo<Void, Void>> scheduledSignals = new HashMap<String, OpenRequestInfo<Void, Void>>(); GenericWorkflowClientImpl(DecisionsHelper decisions, WorkflowContext workflowContext) { this.decisions = decisions; this.workflowContext = workflowContext; } @Override public Promise<StartChildWorkflowReply> startChildWorkflow(final StartChildWorkflowExecutionParameters parameters) { final OpenRequestInfo<StartChildWorkflowReply, WorkflowType> context = new OpenRequestInfo<StartChildWorkflowReply, WorkflowType>(); final StartChildWorkflowExecutionDecisionAttributes attributes = new StartChildWorkflowExecutionDecisionAttributes(); attributes.setWorkflowType(parameters.getWorkflowType()); String workflowId = parameters.getWorkflowId(); if (workflowId == null) { workflowId = generateUniqueId(); } attributes.setWorkflowId(workflowId); attributes.setInput(parameters.getInput()); attributes.setExecutionStartToCloseTimeout(FlowHelpers.secondsToDuration(parameters.getExecutionStartToCloseTimeoutSeconds())); attributes.setTaskStartToCloseTimeout(FlowHelpers.secondsToDuration(parameters.getTaskStartToCloseTimeoutSeconds())); attributes.setTaskPriority(FlowHelpers.taskPriorityToString(parameters.getTaskPriority())); List<String> tagList = parameters.getTagList(); if (tagList != null) { attributes.setTagList(tagList); } ChildPolicy childPolicy = parameters.getChildPolicy(); if (childPolicy != null) { attributes.setChildPolicy(childPolicy); } String taskList = parameters.getTaskList(); if (taskList != null && !taskList.isEmpty()) { attributes.setTaskList(new TaskList().withName(taskList)); } attributes.setLambdaRole(parameters.getLambdaRole()); String taskName = "workflowId=" + workflowId + ", workflowType=" + attributes.getWorkflowType(); new ExternalTask() { @Override protected ExternalTaskCancellationHandler doExecute(final ExternalTaskCompletionHandle handle) throws Throwable { context.setCompletionHandle(handle); String workflowId = attributes.getWorkflowId(); if (scheduledExternalWorkflows.containsKey(decisions.getActualChildWorkflowId(workflowId))) { WorkflowExecution workflowExecution = new WorkflowExecution(); workflowExecution.setWorkflowId(workflowId); WorkflowType workflowType = attributes.getWorkflowType(); long fakeEventId = -1; handle.fail(new StartChildWorkflowFailedException(fakeEventId, workflowExecution, workflowType, StartChildWorkflowExecutionFailedCause.WORKFLOW_ALREADY_RUNNING.toString())); return new ChildWorkflowCancellationHandler(workflowId, handle); } // should not update this map if the same work flow is running decisions.startChildWorkflowExecution(attributes); scheduledExternalWorkflows.put(workflowId, context); return new ChildWorkflowCancellationHandler(workflowId, handle); } }.setName(taskName); context.setResultDescription("startChildWorkflow " + taskName); return context.getResult(); } @Override public Promise<String> startChildWorkflow(String workflow, String version, String input) { StartChildWorkflowExecutionParameters parameters = new StartChildWorkflowExecutionParameters(); parameters.setWorkflowType(new WorkflowType().withName(workflow).withVersion(version)); parameters.setInput(input); final Promise<StartChildWorkflowReply> started = startChildWorkflow(parameters); return new Functor<String>(started) { @Override protected Promise<String> doExecute() throws Throwable { return started.get().getResult(); } }; } @Override public Promise<String> startChildWorkflow(final String workflow, 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(startChildWorkflow(workflow, version, input.get())); } }; return result; } @Override public Promise<Void> signalWorkflowExecution(final SignalExternalWorkflowParameters parameters) { final OpenRequestInfo<Void, Void> context = new OpenRequestInfo<Void, Void>(); final SignalExternalWorkflowExecutionDecisionAttributes attributes = new SignalExternalWorkflowExecutionDecisionAttributes(); String signalId = decisions.getNextId(); attributes.setControl(signalId); attributes.setSignalName(parameters.getSignalName()); attributes.setInput(parameters.getInput()); attributes.setRunId(parameters.getRunId()); attributes.setWorkflowId(parameters.getWorkflowId()); String taskName = "signalId=" + signalId + ", workflowId=" + parameters.getWorkflowId() + ", workflowRunId=" + parameters.getRunId(); new ExternalTask() { @Override protected ExternalTaskCancellationHandler doExecute(final ExternalTaskCompletionHandle handle) throws Throwable { decisions.signalExternalWorkflowExecution(attributes); context.setCompletionHandle(handle); final String finalSignalId = attributes.getControl(); scheduledSignals.put(finalSignalId, context); return new ExternalTaskCancellationHandler() { @Override public void handleCancellation(Throwable cause) { decisions.cancelSignalExternalWorkflowExecution(finalSignalId, null); OpenRequestInfo<Void, Void> scheduled = scheduledSignals.remove(finalSignalId); if (scheduled == null) { throw new IllegalArgumentException("Signal \"" + finalSignalId + "\" wasn't scheduled"); } handle.complete(); } }; } }.setName(taskName); context.setResultDescription("signalWorkflowExecution " + taskName); return context.getResult(); } @Override public void requestCancelWorkflowExecution(WorkflowExecution execution) { RequestCancelExternalWorkflowExecutionDecisionAttributes attributes = new RequestCancelExternalWorkflowExecutionDecisionAttributes(); attributes.setWorkflowId(decisions.getActualChildWorkflowId(execution.getWorkflowId())); attributes.setRunId(execution.getRunId()); // TODO: See if immediate cancellation needed decisions.requestCancelExternalWorkflowExecution(attributes, null); } @Override public void continueAsNewOnCompletion(ContinueAsNewWorkflowExecutionParameters continueParameters) { // TODO: add validation to check if continueAsNew is not set workflowContext.setContinueAsNewOnCompletion(continueParameters); } @Override public String generateUniqueId() { return decisions.getChildWorkflowIdHandler().generateWorkflowId(workflowContext.getWorkflowExecution(), decisions::getNextId); } public void handleChildWorkflowExecutionCancelRequested(HistoryEvent event) { decisions.handleChildWorkflowExecutionCancelRequested(event); } void handleChildWorkflowExecutionCanceled(HistoryEvent event) { ChildWorkflowExecutionCanceledEventAttributes attributes = event.getChildWorkflowExecutionCanceledEventAttributes(); WorkflowExecution execution = attributes.getWorkflowExecution(); String workflowId = execution.getWorkflowId(); if (decisions.handleChildWorkflowExecutionCanceled(workflowId)) { OpenRequestInfo<StartChildWorkflowReply, WorkflowType> scheduled = scheduledExternalWorkflows.remove(workflowId); if (scheduled != null) { CancellationException e = new CancellationException(); ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); // It is OK to fail with subclass of CancellationException when cancellation requested. // It allows passing information about cancellation (details in this case) to the surrounding doCatch block completionHandle.fail(e); } } } void handleChildWorkflowExecutionInitiated(HistoryEvent event) { String actualWorkflowId = event.getStartChildWorkflowExecutionInitiatedEventAttributes().getWorkflowId(); String requestedWorkflowId = decisions.getChildWorkflowIdHandler().extractRequestedWorkflowId(actualWorkflowId); if (!actualWorkflowId.equals(requestedWorkflowId)) { OpenRequestInfo<StartChildWorkflowReply, WorkflowType> scheduled = scheduledExternalWorkflows.remove(requestedWorkflowId); scheduledExternalWorkflows.put(actualWorkflowId, scheduled); } decisions.handleStartChildWorkflowExecutionInitiated(event); } void handleChildWorkflowExecutionStarted(HistoryEvent event) { ChildWorkflowExecutionStartedEventAttributes attributes = event.getChildWorkflowExecutionStartedEventAttributes(); WorkflowExecution execution = attributes.getWorkflowExecution(); String workflowId = execution.getWorkflowId(); decisions.handleChildWorkflowExecutionStarted(event); OpenRequestInfo<StartChildWorkflowReply, WorkflowType> scheduled = scheduledExternalWorkflows.get(workflowId); if (scheduled != null) { String runId = attributes.getWorkflowExecution().getRunId(); Settable<StartChildWorkflowReply> result = scheduled.getResult(); if (!result.isReady()) { String description = "startChildWorkflow workflowId=" + workflowId + ", runId=" + runId; result.set(new StartChildWorkflowReplyImpl(workflowId, runId, description)); } } } void handleChildWorkflowExecutionTimedOut(HistoryEvent event) { ChildWorkflowExecutionTimedOutEventAttributes attributes = event.getChildWorkflowExecutionTimedOutEventAttributes(); WorkflowExecution execution = attributes.getWorkflowExecution(); String workflowId = execution.getWorkflowId(); if (decisions.handleChildWorkflowExecutionClosed(workflowId)) { OpenRequestInfo<StartChildWorkflowReply, WorkflowType> scheduled = scheduledExternalWorkflows.remove(workflowId); if (scheduled != null) { Exception failure = new ChildWorkflowTimedOutException(event.getEventId(), execution, attributes.getWorkflowType()); ExternalTaskCompletionHandle context = scheduled.getCompletionHandle(); context.fail(failure); } } } void handleChildWorkflowExecutionTerminated(HistoryEvent event) { ChildWorkflowExecutionTerminatedEventAttributes attributes = event.getChildWorkflowExecutionTerminatedEventAttributes(); WorkflowExecution execution = attributes.getWorkflowExecution(); String workflowId = execution.getWorkflowId(); if (decisions.handleChildWorkflowExecutionClosed(workflowId)) { OpenRequestInfo<StartChildWorkflowReply, WorkflowType> scheduled = scheduledExternalWorkflows.remove(workflowId); if (scheduled != null) { Exception failure = new ChildWorkflowTerminatedException(event.getEventId(), execution, attributes.getWorkflowType()); ExternalTaskCompletionHandle context = scheduled.getCompletionHandle(); context.fail(failure); } } } void handleStartChildWorkflowExecutionFailed(HistoryEvent event) { if (decisions.handleStartChildWorkflowExecutionFailed(event)) { StartChildWorkflowExecutionFailedEventAttributes attributes = event.getStartChildWorkflowExecutionFailedEventAttributes(); String actualWorkflowId = attributes.getWorkflowId(); String requestedWorkflowId = decisions.getChildWorkflowIdHandler().extractRequestedWorkflowId(actualWorkflowId); String workflowId = null; OpenRequestInfo<StartChildWorkflowReply, WorkflowType> scheduled = null; if (scheduledExternalWorkflows.containsKey(requestedWorkflowId)) { scheduled = scheduledExternalWorkflows.remove(requestedWorkflowId); workflowId = requestedWorkflowId; } else if (scheduledExternalWorkflows.containsKey(actualWorkflowId)) { scheduled = scheduledExternalWorkflows.remove(actualWorkflowId); workflowId = actualWorkflowId; } if (scheduled != null) { WorkflowExecution workflowExecution = new WorkflowExecution(); workflowExecution.setWorkflowId(workflowId); WorkflowType workflowType = attributes.getWorkflowType(); String cause = attributes.getCause(); Exception failure = new StartChildWorkflowFailedException(event.getEventId(), workflowExecution, workflowType, cause); ExternalTaskCompletionHandle context = scheduled.getCompletionHandle(); context.fail(failure); } } } void handleChildWorkflowExecutionFailed(HistoryEvent event) { ChildWorkflowExecutionFailedEventAttributes attributes = event.getChildWorkflowExecutionFailedEventAttributes(); WorkflowExecution execution = attributes.getWorkflowExecution(); String workflowId = execution.getWorkflowId(); if (decisions.handleChildWorkflowExecutionClosed(workflowId)) { OpenRequestInfo<StartChildWorkflowReply, WorkflowType> scheduled = scheduledExternalWorkflows.remove(workflowId); if (scheduled != null) { String reason = attributes.getReason(); String details = attributes.getDetails(); Exception failure = new ChildWorkflowFailedException(event.getEventId(), execution, attributes.getWorkflowType(), reason, details); ExternalTaskCompletionHandle context = scheduled.getCompletionHandle(); context.fail(failure); } } } void handleChildWorkflowExecutionCompleted(HistoryEvent event) { ChildWorkflowExecutionCompletedEventAttributes attributes = event.getChildWorkflowExecutionCompletedEventAttributes(); WorkflowExecution execution = attributes.getWorkflowExecution(); String workflowId = execution.getWorkflowId(); if (decisions.handleChildWorkflowExecutionClosed(workflowId)) { OpenRequestInfo<StartChildWorkflowReply, WorkflowType> scheduled = scheduledExternalWorkflows.remove(workflowId); if (scheduled != null) { ExternalTaskCompletionHandle context = scheduled.getCompletionHandle(); String result = attributes.getResult(); StartChildWorkflowReplyImpl startedReply = (StartChildWorkflowReplyImpl) scheduled.getResult().get(); startedReply.setResult(result); context.complete(); } } } void handleSignalExternalWorkflowExecutionFailed(HistoryEvent event) { SignalExternalWorkflowExecutionFailedEventAttributes attributes = event.getSignalExternalWorkflowExecutionFailedEventAttributes(); String signalId = attributes.getControl(); if (decisions.handleSignalExternalWorkflowExecutionFailed(signalId)) { OpenRequestInfo<Void, Void> signalContextAndResult = scheduledSignals.remove(signalId); if (signalContextAndResult != null) { WorkflowExecution signaledExecution = new WorkflowExecution(); signaledExecution.setWorkflowId(attributes.getWorkflowId()); signaledExecution.setRunId(attributes.getRunId()); Throwable failure = new SignalExternalWorkflowException(event.getEventId(), signaledExecution, attributes.getCause()); signalContextAndResult.getCompletionHandle().fail(failure); } } } void handleExternalWorkflowExecutionSignaled(HistoryEvent event) { ExternalWorkflowExecutionSignaledEventAttributes attributes = event.getExternalWorkflowExecutionSignaledEventAttributes(); String signalId = decisions.getSignalIdFromExternalWorkflowExecutionSignaled(attributes.getInitiatedEventId()); if (decisions.handleExternalWorkflowExecutionSignaled(signalId)) { OpenRequestInfo<Void, Void> signalContextAndResult = scheduledSignals.remove(signalId); if (signalContextAndResult != null) { signalContextAndResult.getResult().set(null); signalContextAndResult.getCompletionHandle().complete(); } } } }
3,657
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/worker/CurrentDecisionContext.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.worker; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.DecisionContextProviderImpl; import com.amazonaws.services.simpleworkflow.flow.WorkflowExecutionLocal; /** * Holds DecisionContext for currently executing decision task. Do not use this * class directly. Instead use {@link DecisionContextProviderImpl}. */ public abstract class CurrentDecisionContext { private final static WorkflowExecutionLocal<DecisionContext> CURRENT = new WorkflowExecutionLocal<DecisionContext>(); /** * retrieves the current DecisionContext for a particular thread * * @return current decider context being used for the decision * @throws IllegalStateException * if this method is called outside the scope of workflow * definition. */ public static DecisionContext get() { DecisionContext result = CURRENT.get(); if (result == null) { throw new IllegalStateException( "No context found. It means that the method is called outside of the workflow definition code."); } return result; } /** * @return if context is set which means that code is executed as part of * the decision. */ public static boolean isSet() { return CURRENT.get() != null; } public static void set(DecisionContext context) { if (context == null) { throw new IllegalArgumentException("null context"); } WorkflowExecutionLocal.before(); CURRENT.set(context); } public static void unset() { WorkflowExecutionLocal.after(); } }
3,658
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/worker/ActivityTypeExecutionOptions.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.worker; public class ActivityTypeExecutionOptions { private boolean manualActivityCompletion; private ActivityTypeCompletionRetryOptions completionRetryOptions; private ActivityTypeCompletionRetryOptions failureRetryOptions; public boolean isManualActivityCompletion() { return manualActivityCompletion; } public void setManualActivityCompletion(boolean manualActivityCompletion) { this.manualActivityCompletion = manualActivityCompletion; } public ActivityTypeCompletionRetryOptions getCompletionRetryOptions() { return completionRetryOptions; } public void setCompletionRetryOptions(ActivityTypeCompletionRetryOptions completionRetryOptions) { this.completionRetryOptions = completionRetryOptions; } public ActivityTypeCompletionRetryOptions getFailureRetryOptions() { return failureRetryOptions; } public void setFailureRetryOptions(ActivityTypeCompletionRetryOptions failureRetryOptions) { this.failureRetryOptions = failureRetryOptions; } }
3,659
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/worker/CircularLongBuffer.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.worker; class CircularLongBuffer { private long[] values_; public CircularLongBuffer(int size) { values_ = new long[size]; } public CircularLongBuffer(long[] values) { values_ = values; } public void set(long i, long value) { values_[getArrayOffset(i)] = value; }; public long get(long i) { return values_[getArrayOffset(i)]; }; public int size() { return values_.length; }; public CircularLongBuffer copy(long index1, int length) { if (length == 0) { return new CircularLongBuffer(0); } int i1 = getArrayOffset(index1); int i2 = getArrayOffset(index1 + Math.min(length, values_.length)); long[] result = new long[length]; if (i1 < i2) { int l = i2 - i1; System.arraycopy(values_, i1, result, 0, l); } else { int tailLength = values_.length - i1; System.arraycopy(values_, i1, result, 0, tailLength); System.arraycopy(values_, 0, result, tailLength, i2); } return new CircularLongBuffer(result); } private int getArrayOffset(long index) { if (values_.length == 0) { throw new IllegalStateException("zero data size"); } int result = (int) (index % values_.length); if (result < 0) { result = values_.length + result; } return result; } }
3,660
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/worker/SuspendableSemaphore.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.worker; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Semaphore that can be suspended. When suspended {@link #acquire()} operation * doesn't return permits even if available. * * @author fateev */ class SuspendableSemaphore { private final Semaphore semaphore; private final Lock lock = new ReentrantLock(); private final Condition suspentionCondition = lock.newCondition(); private boolean suspended; public SuspendableSemaphore(int permits, boolean fair) { semaphore = new Semaphore(permits, fair); } public SuspendableSemaphore(int permits) { semaphore = new Semaphore(permits); } public void acquire() throws InterruptedException { semaphore.acquire(); lock.lock(); try { while (suspended) { suspentionCondition.await(); } } finally { lock.unlock(); } } public void release() { semaphore.release(); } public void suspend() { lock.lock(); try { suspended = true; } finally { lock.unlock(); } } public void resume() { lock.lock(); try { suspended = false; suspentionCondition.signalAll(); } finally { lock.unlock(); } } public boolean isSuspended() { lock.lock(); try { return suspended; } finally { lock.unlock(); } } }
3,661
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/worker/SimpleWorkflowDefinitionFactoryFactory.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.worker; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.services.simpleworkflow.flow.WorkflowTypeRegistrationOptions; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactory; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactoryFactory; import com.amazonaws.services.simpleworkflow.model.WorkflowType; public class SimpleWorkflowDefinitionFactoryFactory extends WorkflowDefinitionFactoryFactory { private final Map<WorkflowType, WorkflowDefinitionFactory> factoriesMap = new HashMap<WorkflowType, WorkflowDefinitionFactory>(); private final List<WorkflowType> typesToRegister = new ArrayList<WorkflowType>(); @Override public WorkflowDefinitionFactory getWorkflowDefinitionFactory(WorkflowType workflowType) { return factoriesMap.get(workflowType); } @Override public Iterable<WorkflowType> getWorkflowTypesToRegister() { return typesToRegister; } public void setWorkflowDefinitionFactories(Collection<WorkflowDefinitionFactory> factories) { for (WorkflowDefinitionFactory factory : factories) { addWorkflowDefinitionFactory(factory); } } public Collection<WorkflowDefinitionFactory> getWorkflowDefinitionFactories() { return factoriesMap.values(); } public void addWorkflowDefinitionFactory(WorkflowDefinitionFactory factory) { WorkflowType workflowType = factory.getWorkflowType(); factoriesMap.put(workflowType, factory); WorkflowTypeRegistrationOptions registrationOptions = factory.getWorkflowRegistrationOptions(); if (registrationOptions != null) { typesToRegister.add(workflowType); } } }
3,662
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/worker/DecisionStateMachine.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.worker; import com.amazonaws.services.simpleworkflow.model.Decision; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; interface DecisionStateMachine { Decision getDecision(); void cancel(Runnable immediateCancellationCallback); void handleStartedEvent(HistoryEvent event); void handleCancellationInitiatedEvent(); void handleCancellationEvent(); void handleCancellationFailureEvent(HistoryEvent event); void handleCompletionEvent(); void handleInitiationFailedEvent(HistoryEvent event); void handleInitiatedEvent(HistoryEvent event); void handleDecisionTaskStartedEvent(); DecisionState getState(); boolean isDone(); DecisionId getId(); }
3,663
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/worker/ActivityTypeRegistrationOptions.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.worker; public class ActivityTypeRegistrationOptions { private String defaultTaskList; private String description; private Long defaultTaskHeartbeatTimeoutSeconds; private Long defaultTaskScheduleToCloseTimeoutSeconds; private Long defaultTaskScheduleToStartTimeoutSeconds; private Long defaultTaskStartToCloseTimeoutSeconds; private Integer defaultTaskPriority; public String getDefaultTaskList() { return defaultTaskList; } public void setDefaultTaskList(String defaultTaskList) { this.defaultTaskList = defaultTaskList; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getDefaultTaskHeartbeatTimeoutSeconds() { return defaultTaskHeartbeatTimeoutSeconds; } public void setDefaultTaskHeartbeatTimeoutSeconds(Long defaultTaskHeartbeatTimeoutSeconds) { this.defaultTaskHeartbeatTimeoutSeconds = defaultTaskHeartbeatTimeoutSeconds; } public Long getDefaultTaskScheduleToCloseTimeoutSeconds() { return defaultTaskScheduleToCloseTimeoutSeconds; } public void setDefaultTaskScheduleToCloseTimeoutSeconds(Long defaultTaskScheduleToCloseTimeoutSeconds) { this.defaultTaskScheduleToCloseTimeoutSeconds = defaultTaskScheduleToCloseTimeoutSeconds; } public Long getDefaultTaskScheduleToStartTimeoutSeconds() { return defaultTaskScheduleToStartTimeoutSeconds; } public void setDefaultTaskScheduleToStartTimeoutSeconds(Long defaultTaskScheduleToStartTimeoutSeconds) { this.defaultTaskScheduleToStartTimeoutSeconds = defaultTaskScheduleToStartTimeoutSeconds; } public Long getDefaultTaskStartToCloseTimeoutSeconds() { return defaultTaskStartToCloseTimeoutSeconds; } public void setDefaultTaskStartToCloseTimeoutSeconds(Long defaultTaskStartToCloseTimeoutSeconds) { this.defaultTaskStartToCloseTimeoutSeconds = defaultTaskStartToCloseTimeoutSeconds; } public Integer getDefaultTaskPriority() { return defaultTaskPriority; } public void setDefaultTaskPriority(Integer defaultTaskPriority) { this.defaultTaskPriority = defaultTaskPriority; } @Override public String toString() { return "ActivityTypeRegistrationOptions [defaultTaskList=" + ((defaultTaskList != null) ? defaultTaskList.toString() : "null") + ", description=" + description + ", defaultTaskHeartbeatTimeoutSeconds=" + defaultTaskHeartbeatTimeoutSeconds + ", defaultTaskScheduleToCloseTimeoutSeconds=" + defaultTaskScheduleToCloseTimeoutSeconds + ", defaultTaskScheduleToStartTimeoutSeconds=" + defaultTaskScheduleToStartTimeoutSeconds + ", defaultTaskStartToCloseTimeoutSeconds=" + defaultTaskStartToCloseTimeoutSeconds + ", defaultTaskPriority=" + defaultTaskPriority + "]"; } }
3,664
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/worker/DecisionContextImpl.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.worker; 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; class DecisionContextImpl extends DecisionContext { private final GenericActivityClient activityClient; private final GenericWorkflowClient workflowClient; private final WorkflowClock workflowClock; private final WorkflowContext workflowContext; private final LambdaFunctionClient lambdaFunctionClient; DecisionContextImpl(GenericActivityClient activityClient, GenericWorkflowClient workflowClient, WorkflowClock workflowClock, WorkflowContext workflowContext, LambdaFunctionClient lambdaFunctionClient) { this.activityClient = activityClient; this.workflowClient = workflowClient; this.workflowClock = workflowClock; this.workflowContext = workflowContext; 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 workflowContext; } @Override public LambdaFunctionClient getLambdaFunctionClient() { return lambdaFunctionClient; } }
3,665
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/worker/GenericActivityWorker.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.worker; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.flow.common.FlowHelpers; import com.amazonaws.services.simpleworkflow.flow.common.RequestTimeoutHelper; import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig; import com.amazonaws.services.simpleworkflow.flow.generic.ActivityImplementation; import com.amazonaws.services.simpleworkflow.flow.generic.ActivityImplementationFactory; import com.amazonaws.services.simpleworkflow.flow.retry.ThrottlingRetrier; import com.amazonaws.services.simpleworkflow.model.ActivityTask; import com.amazonaws.services.simpleworkflow.model.ActivityType; import com.amazonaws.services.simpleworkflow.model.RegisterActivityTypeRequest; import com.amazonaws.services.simpleworkflow.model.TaskList; import com.amazonaws.services.simpleworkflow.model.TypeAlreadyExistsException; import lombok.Getter; import lombok.Setter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class GenericActivityWorker extends GenericWorker<ActivityTask> { private static final Log log = LogFactory.getLog(GenericActivityWorker.class); private static final String POLL_THREAD_NAME_PREFIX = "SWF Activity "; @Getter @Setter private ActivityImplementationFactory activityImplementationFactory; public GenericActivityWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll) { this(service, domain, taskListToPoll, null); } public GenericActivityWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll, SimpleWorkflowClientConfig config) { super(service, domain, taskListToPoll, config); if (service == null) { throw new IllegalArgumentException("service"); } } public GenericActivityWorker() { super(); } @Override protected TaskPoller<ActivityTask> createPoller() { ActivityTaskPoller activityTaskPoller = new ActivityTaskPoller(service, domain, getTaskListToPoll(), activityImplementationFactory, executeThreadCount, getClientConfig()); activityTaskPoller.setIdentity(getIdentity()); activityTaskPoller.setUncaughtExceptionHandler(uncaughtExceptionHandler); return activityTaskPoller; } @Override public void registerTypesToPoll() { registerActivityTypes(service, domain, getTaskListToPoll(), activityImplementationFactory, getClientConfig()); } public static void registerActivityTypes(AmazonSimpleWorkflow service, String domain, String defaultTaskList, ActivityImplementationFactory activityImplementationFactory) { registerActivityTypes(service, domain, defaultTaskList, activityImplementationFactory, null); } public static void registerActivityTypes(AmazonSimpleWorkflow service, String domain, String defaultTaskList, ActivityImplementationFactory activityImplementationFactory, SimpleWorkflowClientConfig config) { for (ActivityType activityType : activityImplementationFactory.getActivityTypesToRegister()) { try { ActivityImplementation implementation = activityImplementationFactory.getActivityImplementation(activityType); if (implementation == null) { throw new IllegalStateException("No implementation found for type needed registration: " + activityType); } ActivityTypeRegistrationOptions registrationOptions = implementation.getRegistrationOptions(); if (registrationOptions != null) { registerActivityType(service, domain, activityType, registrationOptions, defaultTaskList, config); } } catch (TypeAlreadyExistsException ex) { if (log.isTraceEnabled()) { log.trace("Activity version already registered: " + activityType.getName() + "_" + activityType.getVersion()); } } } } public static void registerActivityType(AmazonSimpleWorkflow service, String domain, ActivityType activityType, ActivityTypeRegistrationOptions registrationOptions, String taskListToPoll) throws AmazonServiceException { registerActivityType(service, domain, activityType, registrationOptions, taskListToPoll, null); } public static void registerActivityType(AmazonSimpleWorkflow service, String domain, ActivityType activityType, ActivityTypeRegistrationOptions registrationOptions, String taskListToPoll, SimpleWorkflowClientConfig config) throws AmazonServiceException { RegisterActivityTypeRequest registerActivity = buildRegisterActivityTypeRequest(domain, activityType, registrationOptions, taskListToPoll); RequestTimeoutHelper.overrideControlPlaneRequestTimeout(registerActivity, config); registerActivityTypeWithRetry(service, registerActivity); if (log.isInfoEnabled()) { log.info("registered activity type: " + activityType); } } private static RegisterActivityTypeRequest buildRegisterActivityTypeRequest(String domain, ActivityType activityType, ActivityTypeRegistrationOptions registrationOptions, String taskListToPoll) throws AmazonServiceException { RegisterActivityTypeRequest registerActivity = new RegisterActivityTypeRequest(); registerActivity.setDomain(domain); String taskList = registrationOptions.getDefaultTaskList(); if (taskList == null) { taskList = taskListToPoll; } else if (taskList.equals(FlowConstants.NO_DEFAULT_TASK_LIST)) { taskList = null; } if (taskList != null && !taskList.isEmpty()) { registerActivity.setDefaultTaskList(new TaskList().withName(taskList)); } registerActivity.setName(activityType.getName()); registerActivity.setVersion(activityType.getVersion()); registerActivity.setDefaultTaskStartToCloseTimeout(FlowHelpers.secondsToDuration(registrationOptions.getDefaultTaskStartToCloseTimeoutSeconds())); registerActivity.setDefaultTaskScheduleToCloseTimeout(FlowHelpers.secondsToDuration(registrationOptions.getDefaultTaskScheduleToCloseTimeoutSeconds())); registerActivity.setDefaultTaskHeartbeatTimeout(FlowHelpers.secondsToDuration(registrationOptions.getDefaultTaskHeartbeatTimeoutSeconds())); registerActivity.setDefaultTaskScheduleToStartTimeout(FlowHelpers.secondsToDuration(registrationOptions.getDefaultTaskScheduleToStartTimeoutSeconds())); registerActivity.setDefaultTaskPriority(FlowHelpers.taskPriorityToString(registrationOptions.getDefaultTaskPriority())); if (registrationOptions.getDescription() != null) { registerActivity.setDescription(registrationOptions.getDescription()); } return registerActivity; } private static void registerActivityTypeWithRetry(AmazonSimpleWorkflow service, RegisterActivityTypeRequest registerActivityTypeRequest) { ThrottlingRetrier retrier = new ThrottlingRetrier(getRegisterTypeThrottledRetryParameters()); retrier.retry(() -> service.registerActivityType(registerActivityTypeRequest)); } @Override protected void checkRequiredProperties() { checkRequiredProperty(activityImplementationFactory, "activityImplementationFactory"); } @Override public String toString() { return this.getClass().getSimpleName() + " [super=" + super.toString() + ", taskExecutorThreadPoolSize=" + executeThreadCount + "]"; } @Override protected String getPollThreadNamePrefix() { return POLL_THREAD_NAME_PREFIX + getTaskListToPoll() + " "; } }
3,666
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/worker/DecisionId.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.worker; class DecisionId { final DecisionTarget decisionTarget; final String id; public DecisionId(DecisionTarget decisionTarget, String id) { this.id = id; this.decisionTarget = decisionTarget; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((decisionTarget == null) ? 0 : decisionTarget.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DecisionId other = (DecisionId) obj; if (decisionTarget != other.decisionTarget) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return "DecisionId [type=" + decisionTarget + ", id=" + id + "]"; } }
3,667
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/worker/ExponentialRetryParameters.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.worker; public class ExponentialRetryParameters { private long initialInterval = 500; private double backoffCoefficient = 2.0d; private int maximumRetries = Integer.MAX_VALUE; private long expirationInterval = 60000; private long maximumRetryInterval = 20000; private int minimumRetries; public long getInitialInterval() { return initialInterval; } public void setInitialInterval(long initialInterval) { this.initialInterval = initialInterval; } public double getBackoffCoefficient() { return backoffCoefficient; } public void setBackoffCoefficient(double backoffCoefficient) { this.backoffCoefficient = backoffCoefficient; } public int getMaximumRetries() { return maximumRetries; } public void setMaximumRetries(int maximumRetries) { this.maximumRetries = maximumRetries; } public long getExpirationInterval() { return expirationInterval; } public void setExpirationInterval(long expirationInterval) { this.expirationInterval = expirationInterval; } public long getMaximumRetryInterval() { return maximumRetryInterval; } public void setMaximumRetryInterval(long maximumRetryInterval) { this.maximumRetryInterval = maximumRetryInterval; } public int getMinimumRetries() { return minimumRetries; } public void setMinimumRetries(int minimumRetries) { this.minimumRetries = minimumRetries; } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(backoffCoefficient); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + (int) (expirationInterval ^ (expirationInterval >>> 32)); result = prime * result + (int) (initialInterval ^ (initialInterval >>> 32)); result = prime * result + maximumRetries; result = prime * result + (int) (maximumRetryInterval ^ (maximumRetryInterval >>> 32)); result = prime * result + minimumRetries; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ExponentialRetryParameters other = (ExponentialRetryParameters) obj; if (Double.doubleToLongBits(backoffCoefficient) != Double.doubleToLongBits(other.backoffCoefficient)) return false; if (expirationInterval != other.expirationInterval) return false; if (initialInterval != other.initialInterval) return false; if (maximumRetries != other.maximumRetries) return false; if (maximumRetryInterval != other.maximumRetryInterval) return false; if (minimumRetries != other.minimumRetries) return false; return true; } }
3,668
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/pojo/POJOWorkflowImplementationFactory.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.pojo; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; public interface POJOWorkflowImplementationFactory { Object newInstance(DecisionContext decisionContext) throws Exception; Object newInstance(DecisionContext decisionContext, Object[] constructorArgs) throws Exception; void deleteInstance(Object instance); }
3,669
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/pojo/POJOActivityImplementation.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.pojo; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.concurrent.CancellationException; import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContext; import com.amazonaws.services.simpleworkflow.flow.ActivityFailureException; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.DataConverterException; import com.amazonaws.services.simpleworkflow.flow.common.FlowHelpers; import com.amazonaws.services.simpleworkflow.flow.common.FlowValueConstraint; import com.amazonaws.services.simpleworkflow.flow.generic.ActivityImplementationBase; import com.amazonaws.services.simpleworkflow.flow.worker.ActivityTypeExecutionOptions; import com.amazonaws.services.simpleworkflow.flow.worker.ActivityTypeRegistrationOptions; import com.amazonaws.services.simpleworkflow.flow.worker.CurrentActivityExecutionContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; class POJOActivityImplementation extends ActivityImplementationBase { private static final Log log = LogFactory.getLog(POJOActivityImplementation.class); private final Method activity; private final Object activitiesImplmentationObject; private final ActivityTypeExecutionOptions executionOptions; private final DataConverter converter; private final ActivityTypeRegistrationOptions registrationOptions; public POJOActivityImplementation(Object activitiesImplmentationObject, Method activity, ActivityTypeRegistrationOptions registrationOptions, ActivityTypeExecutionOptions executionOptions, DataConverter converter) { this.activitiesImplmentationObject = activitiesImplmentationObject; this.activity = activity; this.registrationOptions = registrationOptions; this.executionOptions = executionOptions; this.converter = converter; } @Override protected String execute(String input, ActivityExecutionContext context) throws ActivityFailureException, CancellationException { Object[] inputParameters = converter.fromData(input, Object[].class); CurrentActivityExecutionContext.set(context); Object result = null; try { // Fill missing parameters with default values to make addition of new parameters backward compatible inputParameters = FlowHelpers.getInputParameters(activity.getParameterTypes(), inputParameters); result = activity.invoke(activitiesImplmentationObject, inputParameters); } catch (InvocationTargetException invocationException) { throwActivityFailureException(invocationException.getTargetException() != null ? invocationException.getTargetException() : invocationException); } catch (IllegalArgumentException illegalArgumentException) { throwActivityFailureException(illegalArgumentException); } catch (IllegalAccessException illegalAccessException) { throwActivityFailureException(illegalAccessException); } finally { CurrentActivityExecutionContext.unset(); } return converter.toData(result); } @Override public ActivityTypeRegistrationOptions getRegistrationOptions() { return registrationOptions; } @Override public ActivityTypeExecutionOptions getExecutionOptions() { return executionOptions; } void throwActivityFailureException(Throwable exception) throws ActivityFailureException, CancellationException { if (exception instanceof CancellationException) { throw (CancellationException) exception; } String reason = exception.getMessage(); String details = null; try { details = converter.toData(exception); } catch (DataConverterException dataConverterException) { if (dataConverterException.getCause() == null) { dataConverterException.initCause(exception); } throw dataConverterException; } if (details.length() > FlowValueConstraint.FAILURE_DETAILS.getMaxSize()) { log.warn("Length of details is over maximum input length of 32768. Actual details: " + details); Throwable truncatedException = new Throwable(reason); truncatedException.setStackTrace(new StackTraceElement[] {exception.getStackTrace()[0]}); details = converter.toData(truncatedException); } throw new ActivityFailureException(reason, details); } public Method getMethod() { return activity; } public Object getActivitiesImplementation() { return activitiesImplmentationObject; } }
3,670
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/pojo/POJOWorkflowDefinitionFactory.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.pojo; import java.util.Map; import java.util.HashMap; import java.util.List; 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.JsonDataConverter; import com.amazonaws.services.simpleworkflow.flow.WorkflowTypeRegistrationOptions; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowTypeComponentImplementationVersion; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowTypeImplementationOptions; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinition; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactory; import com.amazonaws.services.simpleworkflow.flow.worker.CurrentDecisionContext; import com.amazonaws.services.simpleworkflow.model.WorkflowType; class POJOWorkflowDefinitionFactory extends WorkflowDefinitionFactory { private final DataConverter converter = new JsonDataConverter(); private final WorkflowType workflowType; private final WorkflowTypeRegistrationOptions registrationOptions; private final WorkflowTypeImplementationOptions implementationOptions; private final POJOWorkflowImplementationFactory implementationFactory; private final MethodConverterPair workflowImplementationMethod; private final MethodConverterPair getStateMethod; private final Map<String, MethodConverterPair> signals; private final Object[] constructorArgs; public POJOWorkflowDefinitionFactory(POJOWorkflowImplementationFactory implementationFactory, WorkflowType workflowType, WorkflowTypeRegistrationOptions registrationOptions, WorkflowTypeImplementationOptions implementationOptions, MethodConverterPair workflowImplementationMethod, Map<String, MethodConverterPair> signals, MethodConverterPair getStateMethod, Object[] constructorArgs) { this.implementationFactory = implementationFactory; this.workflowType = workflowType; this.registrationOptions = registrationOptions; this.workflowImplementationMethod = workflowImplementationMethod; this.signals = signals; this.getStateMethod = getStateMethod; this.implementationOptions = implementationOptions; this.constructorArgs = constructorArgs; } @Override public WorkflowType getWorkflowType() { return workflowType; } @Override public WorkflowTypeRegistrationOptions getWorkflowRegistrationOptions() { return registrationOptions; } @Override public WorkflowTypeImplementationOptions getWorkflowImplementationOptions() { return implementationOptions; } @Override public WorkflowDefinition getWorkflowDefinition(DecisionContext context) throws Exception { if (implementationFactory == null) { return null; } CurrentDecisionContext.set(context); Object workflowDefinitionObject; if (constructorArgs == null) { workflowDefinitionObject = implementationFactory.newInstance(context); } else { workflowDefinitionObject = implementationFactory.newInstance(context, constructorArgs); } return new POJOWorkflowDefinition(workflowDefinitionObject, workflowImplementationMethod, signals, getStateMethod, converter, context); } @Override public void deleteWorkflowDefinition(WorkflowDefinition instance) { POJOWorkflowDefinition definition = (POJOWorkflowDefinition) instance; implementationFactory.deleteInstance(definition.getImplementationInstance()); CurrentDecisionContext.unset(); } public void setMaximumAllowedComponentImplementationVersions(Map<String, Integer> componentVersions) { componentVersions = new HashMap<String, Integer>(componentVersions); List<WorkflowTypeComponentImplementationVersion> options = implementationOptions.getImplementationComponentVersions(); Map<String, WorkflowTypeComponentImplementationVersion> implementationOptionsMap = new HashMap<String, WorkflowTypeComponentImplementationVersion>(); for (WorkflowTypeComponentImplementationVersion implementationVersion : options) { String componentName = implementationVersion.getComponentName(); implementationOptionsMap.put(componentName, implementationVersion); } for (Entry<String, Integer> pair : componentVersions.entrySet()) { String componentName = pair.getKey(); int maximumAllowed = pair.getValue(); WorkflowTypeComponentImplementationVersion implementationOption = implementationOptionsMap.get(componentName); if (implementationOption != null) { implementationOption.setMaximumAllowed(maximumAllowed); } else { implementationOption = new WorkflowTypeComponentImplementationVersion(componentName, maximumAllowed, maximumAllowed, maximumAllowed); implementationOptions.getImplementationComponentVersions().add(implementationOption); } } } public Map<String, Integer> getMaximumAllowedComponentImplementationVersions() { List<WorkflowTypeComponentImplementationVersion> options = implementationOptions.getImplementationComponentVersions(); Map<String, Integer> result = new HashMap<String, Integer>(); for (WorkflowTypeComponentImplementationVersion implementationVersion : options) { String componentName = implementationVersion.getComponentName(); result.put(componentName, implementationVersion.getMaximumAllowed()); } return result; } }
3,671
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/pojo/MethodConverterPair.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.pojo; import java.lang.reflect.Method; import com.amazonaws.services.simpleworkflow.flow.DataConverter; class MethodConverterPair { private final Method method; private final DataConverter converter; public MethodConverterPair(Method method, DataConverter converter) { super(); this.method = method; this.converter = converter; } Method getMethod() { return method; } DataConverter getConverter() { return converter; } }
3,672
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/pojo/POJOWorkflowDefinition.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.pojo; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicReference; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.DataConverterException; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.WorkflowException; import com.amazonaws.services.simpleworkflow.flow.common.FlowHelpers; import com.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.core.TryCatch; import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinition; @SuppressWarnings("rawtypes") public class POJOWorkflowDefinition extends WorkflowDefinition { private final MethodConverterPair workflowMethod; private final Map<String, MethodConverterPair> signals; private final MethodConverterPair getStateMethod; private final Object workflowImplementationInstance; private final DataConverter converter; private final DecisionContext context; public POJOWorkflowDefinition(Object workflowImplmentationInstance, MethodConverterPair workflowImplementationMethod, Map<String, MethodConverterPair> signals, MethodConverterPair getStateMethod, DataConverter converter, DecisionContext context) throws ClassNotFoundException, SecurityException, NoSuchMethodException, NoSuchFieldException { this.workflowImplementationInstance = workflowImplmentationInstance; this.workflowMethod = workflowImplementationMethod; this.getStateMethod = getStateMethod; this.signals = signals; this.converter = converter; this.context = context; } @Override public Promise<String> execute(final String input) throws WorkflowException { final DataConverter c; if (workflowMethod.getConverter() == null) { c = converter; } else { c = workflowMethod.getConverter(); } final Settable<String> result = new Settable<String>(); final AtomicReference<Promise> methodResult = new AtomicReference<Promise>(); new TryCatchFinally() { @Override protected void doTry() throws Throwable { //TODO: Support ability to call workflow using old client // after new parameters were added to @Execute method // It requires creation of parameters array of the correct size and // populating the new parameter values with default values for each type Object[] parameters = c.fromData(input, Object[].class); Method method = workflowMethod.getMethod(); Object r = invokeMethod(method, parameters); if (!method.getReturnType().equals(Void.TYPE)) { methodResult.set((Promise) r); } } @Override protected void doCatch(Throwable e) throws Throwable { // CancellationException can be caused by: // 1. cancellation request from a server (indicated by isCancelRequested returning true). // Should not be converted. // 2. being thrown by user code. Ut should be converted to WorkflowException as any other exception. // 3. being caused by exception from the sibling (signal handler). // In this case the exception cause is already WorkflowException. No double conversion necessary. if (!(e instanceof CancellationException) || (!context.getWorkflowContext().isCancelRequested() && !(e.getCause() instanceof WorkflowException))) { throwWorkflowException(c, e); } } @Override protected void doFinally() throws Throwable { Promise r = methodResult.get(); if (r == null || r.isReady()) { Object workflowResult = r == null ? null : r.get(); String convertedResult = c.toData(workflowResult); result.set(convertedResult); } } }; return result; } @Override public void signalRecieved(String signalName, String details) throws WorkflowException { MethodConverterPair signalMethod = signals.get(signalName); if (signalMethod != null) { DataConverter c = signalMethod.getConverter(); if (c == null) { c = converter; } Method method = signalMethod.getMethod(); Object[] parameters = c.fromData(details, Object[].class); final DataConverter delegatedConverter = c; new TryCatch() { @Override protected void doTry() throws Throwable { invokeMethod(method, parameters); } @Override protected void doCatch(Throwable e) throws Throwable { throwWorkflowException(delegatedConverter, e); throw new IllegalStateException("Unreacheable"); } }; } else { // TODO: Unhandled signal } } @Override public String getWorkflowState() throws WorkflowException { if (getStateMethod == null) { return null; } final DataConverter c; if (getStateMethod.getConverter() == null) { c = converter; } else { c = getStateMethod.getConverter(); } try { Method method = getStateMethod.getMethod(); Object result = invokeMethod(method, null); return c.toData(result); } catch (Throwable e) { throwWorkflowException(c, e); throw new IllegalStateException("Unreacheable"); } } private Object invokeMethod(final Method method, final Object[] input) throws Throwable { try { // Fill missing parameters with default values to make addition of new parameters backward compatible Object[] parameters = FlowHelpers.getInputParameters(method.getParameterTypes(), input); return method.invoke(workflowImplementationInstance, parameters); } catch (InvocationTargetException invocationException) { if (invocationException.getTargetException() != null) { throw invocationException.getTargetException(); } throw invocationException; } } private void throwWorkflowException(DataConverter c, Throwable exception) throws WorkflowException { if (exception instanceof WorkflowException) { throw (WorkflowException) exception; } String reason = WorkflowExecutionUtils.truncateReason(exception.getMessage()); String details = null; try { details = c.toData(exception); } catch (DataConverterException dataConverterException) { if (dataConverterException.getCause() == null) { dataConverterException.initCause(exception); } throw dataConverterException; } throw new WorkflowException(reason, details); } public Object getImplementationInstance() { return workflowImplementationInstance; } }
3,673
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/pojo/POJOWorkflowDefinitionFactoryFactory.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.pojo; import java.beans.Expression; import java.lang.reflect.Method; 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; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.JsonDataConverter; import com.amazonaws.services.simpleworkflow.flow.WorkflowTypeRegistrationOptions; import com.amazonaws.services.simpleworkflow.flow.annotations.Execute; import com.amazonaws.services.simpleworkflow.flow.annotations.GetState; import com.amazonaws.services.simpleworkflow.flow.annotations.NullDataConverter; import com.amazonaws.services.simpleworkflow.flow.annotations.Signal; import com.amazonaws.services.simpleworkflow.flow.annotations.SkipTypeRegistration; import com.amazonaws.services.simpleworkflow.flow.annotations.Workflow; import com.amazonaws.services.simpleworkflow.flow.annotations.WorkflowComponentImplementationVersion; import com.amazonaws.services.simpleworkflow.flow.annotations.WorkflowComponentImplementationVersions; import com.amazonaws.services.simpleworkflow.flow.annotations.WorkflowRegistrationOptions; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactory; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactoryFactory; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowTypeComponentImplementationVersion; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowTypeImplementationOptions; import com.amazonaws.services.simpleworkflow.model.WorkflowType; public class POJOWorkflowDefinitionFactoryFactory extends WorkflowDefinitionFactoryFactory { private static class AddedType { final Class<?> workflowImplementationType; final DataConverter converterOverride; final Map<String, Integer> maximumAllowedComponentImplementationVersions; public AddedType(Class<?> workflowImplementationType, DataConverter converterOverride, Map<String, Integer> maximumAllowedComponentImplementationVersions) { super(); this.workflowImplementationType = workflowImplementationType; this.converterOverride = converterOverride; this.maximumAllowedComponentImplementationVersions = maximumAllowedComponentImplementationVersions; } public Class<?> getWorkflowImplementationType() { return workflowImplementationType; } public DataConverter getConverterOverride() { return converterOverride; } public Map<String, Integer> getMaximumAllowedComponentImplementationVersions() { return maximumAllowedComponentImplementationVersions; } } private DataConverter dataConverter; /** * Needed to support setting converter after types */ private List<AddedType> addedTypes = new ArrayList<AddedType>(); private List<WorkflowType> workflowTypesToRegister = new ArrayList<WorkflowType>(); private Map<WorkflowType, POJOWorkflowDefinitionFactory> factories = new HashMap<WorkflowType, POJOWorkflowDefinitionFactory>(); private final Collection<Class<?>> workflowImplementationTypes = new ArrayList<Class<?>>(); public DataConverter getDataConverter() { return dataConverter; } public void setDataConverter(DataConverter converter) { this.dataConverter = converter; List<AddedType> typesToAdd = addedTypes; addedTypes = new ArrayList<AddedType>(); for (AddedType toAdd : typesToAdd) { try { addWorkflowImplementationType(toAdd.getWorkflowImplementationType(), toAdd.getConverterOverride(), null, toAdd.getMaximumAllowedComponentImplementationVersions()); } catch (Exception e) { throw new IllegalStateException("Failure adding type " + toAdd.getWorkflowImplementationType() + " after setting converter to " + converter, e); } } } @Override public WorkflowDefinitionFactory getWorkflowDefinitionFactory(WorkflowType workflowType) { return factories.get(workflowType); } @Override public Iterable<WorkflowType> getWorkflowTypesToRegister() { return workflowTypesToRegister; } public void addWorkflowImplementationType(Class<?> workflowImplementationType) throws InstantiationException, IllegalAccessException { addWorkflowImplementationType(workflowImplementationType, null, null, null); } public void addWorkflowImplementationType(Class<?> workflowImplementationType, DataConverter converterOverride) throws InstantiationException, IllegalAccessException { addWorkflowImplementationType(workflowImplementationType, converterOverride, null, null); } public void addWorkflowImplementationType(Class<?> workflowImplementationType, DataConverter converterOverride, Object[] constructorArgs , Map<String, Integer> maximumAllowedComponentImplementationVersions) throws InstantiationException, IllegalAccessException { if (workflowImplementationType.isInterface()) { throw new IllegalArgumentException(workflowImplementationType + " has to be a instantiatable class"); } Set<Class<?>> implementedInterfaces = new HashSet<Class<?>>(); getImplementedInterfacesAnnotatedWithWorkflow(workflowImplementationType, implementedInterfaces); if (implementedInterfaces.size() == 0) { throw new IllegalArgumentException("Workflow definition does not implement any @Workflow interface. " + workflowImplementationType); } for (Class<?> interfaze : implementedInterfaces) { addWorkflowType(interfaze, workflowImplementationType, converterOverride, constructorArgs, maximumAllowedComponentImplementationVersions); } addedTypes.add(new AddedType(workflowImplementationType, converterOverride, maximumAllowedComponentImplementationVersions)); } public void addWorkflowImplementationType(Class<?> workflowImplementationType, Map<String, Integer> maximumAllowedComponentImplementationVersions) throws InstantiationException, IllegalAccessException { addWorkflowImplementationType(workflowImplementationType, null, null, maximumAllowedComponentImplementationVersions); } public void setWorkflowImplementationTypes(Collection<Class<?>> workflowImplementationTypes) throws InstantiationException, IllegalAccessException { for (Class<?> type : workflowImplementationTypes) { addWorkflowImplementationType(type); } } public Collection<Class<?>> getWorkflowImplementationTypes() { return workflowImplementationTypes; } private void addWorkflowType(Class<?> interfaze, Class<?> workflowImplementationType, DataConverter converterOverride, Object[] constructorArgs, Map<String, Integer> maximumAllowedComponentImplementationVersions) throws InstantiationException, IllegalAccessException { Workflow workflowAnnotation = interfaze.getAnnotation(Workflow.class); String interfaceName = interfaze.getSimpleName(); MethodConverterPair workflowImplementationMethod = null; MethodConverterPair getStateMethod = null; WorkflowType workflowType = null; WorkflowTypeRegistrationOptions registrationOptions = null; WorkflowTypeImplementationOptions implementationOptions = new WorkflowTypeImplementationOptions(); Map<String, MethodConverterPair> signals = new HashMap<String, MethodConverterPair>(); for (Method method : interfaze.getMethods()) { if (method.getDeclaringClass().getAnnotation(Workflow.class) == null) { continue; } Execute executeAnnotation = method.getAnnotation(Execute.class); Signal signalAnnotation = method.getAnnotation(Signal.class); GetState getStateAnnotation = method.getAnnotation(GetState.class); checkAnnotationUniqueness(method, executeAnnotation, signalAnnotation, getStateAnnotation); if (executeAnnotation != null) { if (workflowImplementationMethod != null) { throw new IllegalArgumentException( "Interface annotated with @Workflow is allowed to have only one method annotated with @Execute. Found " + getMethodFullName(workflowImplementationMethod.getMethod()) + " and " + getMethodFullName(method)); } if (!method.getReturnType().equals(void.class) && !(Promise.class.isAssignableFrom(method.getReturnType()))) { throw new IllegalArgumentException( "Workflow implementation method annotated with @Execute can return only Promise or void: " + getMethodFullName(method)); } if (!method.getDeclaringClass().equals(interfaze)) { throw new IllegalArgumentException("Interface " + interfaze.getName() + " cannot inherit workflow implementation method annotated with @Execute: " + getMethodFullName(method)); } DataConverter converter = createConverter(workflowAnnotation.dataConverter(), converterOverride); workflowImplementationMethod = new MethodConverterPair(method, converter); workflowType = getWorkflowType(interfaceName, method, executeAnnotation); WorkflowRegistrationOptions registrationOptionsAnnotation = interfaze.getAnnotation(WorkflowRegistrationOptions.class); SkipTypeRegistration skipRegistrationAnnotation = interfaze.getAnnotation(SkipTypeRegistration.class); if (skipRegistrationAnnotation == null) { if (registrationOptionsAnnotation == null) { throw new IllegalArgumentException( "@WorkflowRegistrationOptions is required for the interface that contains method annotated with @Execute"); } registrationOptions = createRegistrationOptions(registrationOptionsAnnotation); } else { if (registrationOptionsAnnotation != null) { throw new IllegalArgumentException( "@WorkflowRegistrationOptions is not allowed for the interface annotated with @SkipTypeRegistration."); } } WorkflowComponentImplementationVersions implementationOptionsAnnotation = workflowImplementationType.getAnnotation(WorkflowComponentImplementationVersions.class); if (implementationOptionsAnnotation != null) { List<WorkflowTypeComponentImplementationVersion> implementationComponentVersions = new ArrayList<WorkflowTypeComponentImplementationVersion>(); WorkflowComponentImplementationVersion[] componentVersionsAnnotations = implementationOptionsAnnotation.value(); for (WorkflowComponentImplementationVersion componentVersionAnnotation : componentVersionsAnnotations) { String componentName = componentVersionAnnotation.componentName(); int minimumSupportedImplementationVersion = componentVersionAnnotation.minimumSupported(); int maximumSupportedImplementationVersion = componentVersionAnnotation.maximumSupported(); int maximumAllowedImplementationVersion = componentVersionAnnotation.maximumAllowed(); WorkflowTypeComponentImplementationVersion componentVersion = new WorkflowTypeComponentImplementationVersion( componentName, minimumSupportedImplementationVersion, maximumSupportedImplementationVersion, maximumAllowedImplementationVersion); implementationComponentVersions.add(componentVersion); } implementationOptions.setImplementationComponentVersions(implementationComponentVersions); } } if (signalAnnotation != null) { String signalName = signalAnnotation.name(); if (signalName == null || signalName.isEmpty()) { signalName = method.getName(); } DataConverter signalConverter = createConverter(workflowAnnotation.dataConverter(), converterOverride); signals.put(signalName, new MethodConverterPair(method, signalConverter)); } if (getStateAnnotation != null) { if (getStateMethod != null) { throw new IllegalArgumentException( "Interface annotated with @Workflow is allowed to have only one method annotated with @GetState. Found " + getMethodFullName(getStateMethod.getMethod()) + " and " + getMethodFullName(method)); } if (method.getReturnType().equals(void.class) || (Promise.class.isAssignableFrom(method.getReturnType()))) { throw new IllegalArgumentException( "Workflow method annotated with @GetState cannot have void or Promise return type: " + getMethodFullName(method)); } DataConverter converter = createConverter(workflowAnnotation.dataConverter(), converterOverride); getStateMethod = new MethodConverterPair(method, converter); } } if (workflowImplementationMethod == null) { throw new IllegalArgumentException("Workflow definition does not implement any method annotated with @Execute. " + workflowImplementationType); } POJOWorkflowImplementationFactory implementationFactory = getImplementationFactory(workflowImplementationType, interfaze, workflowType); POJOWorkflowDefinitionFactory factory = new POJOWorkflowDefinitionFactory(implementationFactory, workflowType, registrationOptions, implementationOptions, workflowImplementationMethod, signals, getStateMethod, constructorArgs); factories.put(workflowType, factory); workflowImplementationTypes.add(workflowImplementationType); if (factory.getWorkflowRegistrationOptions() != null) { workflowTypesToRegister.add(workflowType); } if (maximumAllowedComponentImplementationVersions != null) { setMaximumAllowedComponentImplementationVersions(workflowType, maximumAllowedComponentImplementationVersions); } } private void checkAnnotationUniqueness(Method method, Object... annotations) { List<Object> notNullOnes = new ArrayList<Object>(); for (Object annotation : annotations) { if (annotation != null) { notNullOnes.add(annotation); } } if (notNullOnes.size() > 1) { throw new IllegalArgumentException("Method " + method.getName() + " is annotated with both " + notNullOnes); } } /** * Override to control how implementation is instantiated. * * @param workflowImplementationType * type that was registered with the factory * @param workflowInteface * interface that defines external workflow contract * @param workflowType * type of the workflow that implementation implements * @return factory that creates new instances of the POJO that implements * workflow */ protected POJOWorkflowImplementationFactory getImplementationFactory(final Class<?> workflowImplementationType, Class<?> workflowInteface, WorkflowType workflowType) { return new POJOWorkflowImplementationFactory() { @Override public Object newInstance(DecisionContext decisionContext) throws Exception { return workflowImplementationType.newInstance(); } @Override public Object newInstance(DecisionContext decisionContext, Object[] constructorArgs) throws Exception { return new Expression(workflowImplementationType, "new", constructorArgs).getValue(); } @Override public void deleteInstance(Object instance) { } }; } /** * Recursively find all interfaces annotated with @Workflow that given class * implements. Don not include interfaces that @Workflow annotated interface * extends. */ private void getImplementedInterfacesAnnotatedWithWorkflow(Class<?> workflowImplementationType, Set<Class<?>> implementedInterfaces) { Class<?> superClass = workflowImplementationType.getSuperclass(); if (superClass != null) { getImplementedInterfacesAnnotatedWithWorkflow(superClass, implementedInterfaces); } Class<?>[] interfaces = workflowImplementationType.getInterfaces(); for (Class<?> i : interfaces) { if (i.getAnnotation(Workflow.class) != null && !implementedInterfaces.contains(i)) { boolean skipAdd = removeSuperInterfaces(i, implementedInterfaces); if (!skipAdd) { implementedInterfaces.add(i); } } else { getImplementedInterfacesAnnotatedWithWorkflow(i, implementedInterfaces); } } } private boolean removeSuperInterfaces(Class<?> interfaceToAdd, Set<Class<?>> implementedInterfaces) { boolean skipAdd = false; List<Class<?>> interfacesToRemove = new ArrayList<Class<?>>(); for (Class<?> addedInterface : implementedInterfaces) { if (addedInterface.isAssignableFrom(interfaceToAdd)) { interfacesToRemove.add(addedInterface); } if (interfaceToAdd.isAssignableFrom(addedInterface)) { skipAdd = true; } } for (Class<?> interfaceToRemove : interfacesToRemove) { implementedInterfaces.remove(interfaceToRemove); } return skipAdd; } private static String getMethodFullName(Method m) { return m.getDeclaringClass().getName() + "." + m.getName(); } private DataConverter createConverter(Class<? extends DataConverter> converterTypeFromAnnotation, DataConverter converterOverride) throws InstantiationException, IllegalAccessException { if (converterOverride != null) { return converterOverride; } if (dataConverter != null) { return dataConverter; } if (converterTypeFromAnnotation == null || converterTypeFromAnnotation.equals(NullDataConverter.class)) { return new JsonDataConverter(); } return converterTypeFromAnnotation.newInstance(); } protected WorkflowType getWorkflowType(String interfaceName, Method method, Execute executeAnnotation) { assert (method != null); assert (executeAnnotation != null); WorkflowType workflowType = new WorkflowType(); String workflowName = null; if (executeAnnotation.name() != null && !executeAnnotation.name().isEmpty()) { workflowName = executeAnnotation.name(); } else { workflowName = interfaceName + "." + method.getName(); } if (executeAnnotation.version().isEmpty()) { throw new IllegalArgumentException( "Empty value of the required \"version\" parameter of the @Execute annotation found on " + getMethodFullName(method)); } workflowType.setName(workflowName); workflowType.setVersion(executeAnnotation.version()); return workflowType; } protected WorkflowTypeRegistrationOptions createRegistrationOptions(WorkflowRegistrationOptions registrationOptionsAnnotation) { WorkflowTypeRegistrationOptions result = new WorkflowTypeRegistrationOptions(); result.setDescription(emptyStringToNull(registrationOptionsAnnotation.description())); result.setDefaultExecutionStartToCloseTimeoutSeconds(registrationOptionsAnnotation.defaultExecutionStartToCloseTimeoutSeconds()); result.setDefaultTaskStartToCloseTimeoutSeconds(registrationOptionsAnnotation.defaultTaskStartToCloseTimeoutSeconds()); String taskList = registrationOptionsAnnotation.defaultTaskList(); if (!taskList.equals(FlowConstants.USE_WORKER_TASK_LIST)) { result.setDefaultTaskList(taskList); } result.setDefaultChildPolicy(registrationOptionsAnnotation.defaultChildPolicy()); String defaultLambdaRole = registrationOptionsAnnotation.defaultLambdaRole(); if (defaultLambdaRole != null && !defaultLambdaRole.isEmpty()) { result.setDefaultLambdaRole(defaultLambdaRole); } return result; } private static String emptyStringToNull(String value) { if (value.length() == 0) { return null; } return value; } public void setMaximumAllowedComponentImplementationVersions( Map<WorkflowType, Map<String, Integer>> maximumAllowedImplementationVersions) { for (Entry<WorkflowType, Map<String, Integer>> pair : maximumAllowedImplementationVersions.entrySet()) { WorkflowType workflowType = pair.getKey(); setMaximumAllowedComponentImplementationVersions(workflowType, pair.getValue()); } } public void setMaximumAllowedComponentImplementationVersions(WorkflowType workflowType, Map<String, Integer> maximumAllowedComponentImplementationVersions) { POJOWorkflowDefinitionFactory factory = factories.get(workflowType); if (factory == null) { throw new IllegalArgumentException("Workflow type " + workflowType + " is not registered"); } factory.setMaximumAllowedComponentImplementationVersions(maximumAllowedComponentImplementationVersions); } public Map<WorkflowType, Map<String, Integer>> getMaximumAllowedComponentImplementationVersions() { Map<WorkflowType, Map<String, Integer>> result = new HashMap<WorkflowType, Map<String, Integer>>(); for (Entry<WorkflowType, POJOWorkflowDefinitionFactory> pair : factories.entrySet()) { result.put(pair.getKey(), pair.getValue().getMaximumAllowedComponentImplementationVersions()); } return result; } }
3,674
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/pojo/POJOActivityImplementationFactory.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.pojo; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.JsonDataConverter; import com.amazonaws.services.simpleworkflow.flow.annotations.Activities; import com.amazonaws.services.simpleworkflow.flow.annotations.Activity; import com.amazonaws.services.simpleworkflow.flow.annotations.ActivityCompletionRetryOptions; import com.amazonaws.services.simpleworkflow.flow.annotations.ActivityExecutionOptions; import com.amazonaws.services.simpleworkflow.flow.annotations.ActivityRegistrationOptions; import com.amazonaws.services.simpleworkflow.flow.annotations.ManualActivityCompletion; import com.amazonaws.services.simpleworkflow.flow.annotations.NullDataConverter; import com.amazonaws.services.simpleworkflow.flow.annotations.SkipTypeRegistration; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.flow.generic.ActivityImplementation; import com.amazonaws.services.simpleworkflow.flow.generic.ActivityImplementationFactory; import com.amazonaws.services.simpleworkflow.flow.worker.ActivityTypeCompletionRetryOptions; import com.amazonaws.services.simpleworkflow.flow.worker.ActivityTypeExecutionOptions; import com.amazonaws.services.simpleworkflow.flow.worker.ActivityTypeRegistrationOptions; import com.amazonaws.services.simpleworkflow.model.ActivityType; public class POJOActivityImplementationFactory extends ActivityImplementationFactory { private static class ParentInterfaceOptions { private String version; private String prefix; private ActivityRegistrationOptions registrationOptions; private boolean skipRegistration; public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public ActivityRegistrationOptions getRegistrationOptions() { return registrationOptions; } public void setRegistrationOptions(ActivityRegistrationOptions options) { if (options != null) { setSkipRegistration(false); } this.registrationOptions = options; } public boolean isSkipRegistration() { return skipRegistration; } public void setSkipRegistration(boolean skipRegistration) { if (skipRegistration) { registrationOptions = null; } this.skipRegistration = skipRegistration; } } private static class AddedType { final Object activitiesImplementation; final DataConverter converter; public AddedType(Object activitiesImplementation, DataConverter converter) { super(); this.activitiesImplementation = activitiesImplementation; this.converter = converter; } public Object getActivitiesImplementation() { return activitiesImplementation; } public DataConverter getConverter() { return converter; } } /** * Needed to support setting converter after activities implementation */ private List<AddedType> addedTypes = new ArrayList<AddedType>(); private List<ActivityType> activityTypesToRegister = new ArrayList<ActivityType>(); private Map<ActivityType, POJOActivityImplementation> implementationsMap = new HashMap<ActivityType, POJOActivityImplementation>(); private DataConverter dataConverter; public POJOActivityImplementationFactory() { super(); } public POJOActivityImplementationFactory(Iterable<Object> activityImplementationObjects) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { this(); addActivitiesImplementations(activityImplementationObjects, null); } public POJOActivityImplementationFactory(Iterable<Object> activityImplementationObjects, DataConverter dataConverter) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { this(); addActivitiesImplementations(activityImplementationObjects, dataConverter); } public DataConverter getDataConverter() { return dataConverter; } public void setDataConverter(DataConverter dataConverter) { if (dataConverter == null) { throw new IllegalArgumentException("null dataConverter"); } this.dataConverter = dataConverter; List<AddedType> typesToAdd = addedTypes; addedTypes = new ArrayList<AddedType>(); activityTypesToRegister.clear(); implementationsMap.clear(); for (AddedType toAdd : typesToAdd) { try { addActivitiesImplementation(toAdd.getActivitiesImplementation(), toAdd.getConverter()); } catch (Exception e) { throw new IllegalStateException("Failure adding activity " + toAdd.getActivitiesImplementation() + " after setting converter to " + dataConverter, e); } } } public void setActivitiesImplementations(Iterable<Object> activitiesImplementations) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { addActivitiesImplementations(activitiesImplementations, null); } public Iterable<Object> getActivitiesImplementations() { List<Object> result = new ArrayList<Object>(); for (POJOActivityImplementation impl : implementationsMap.values()) { result.add(impl.getActivitiesImplementation()); } return result; } public List<ActivityType> addActivitiesImplementations(Iterable<Object> activitiesImplementations) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { return addActivitiesImplementations(activitiesImplementations, null); } public List<ActivityType> addActivitiesImplementations(Iterable<Object> activitiesImplementations, DataConverter dataConverter) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { List<ActivityType> result = new ArrayList<ActivityType>(); for (Object activityImplementationObject : activitiesImplementations) { result.addAll(addActivitiesImplementation(activityImplementationObject, dataConverter)); } return result; } public List<ActivityType> addActivitiesImplementation(Object activitiesImplementation) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { return addActivitiesImplementation(activitiesImplementation, null); } public List<ActivityType> addActivitiesImplementation(Object activitiesImplementation, DataConverter converter) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { if (activitiesImplementation == null) { throw new IllegalArgumentException("activitiesImplementation is null."); } Set<ActivityType> result = new HashSet<ActivityType>(); Set<Class<?>> activitiesInterfaces = new HashSet<Class<?>>(); getImplementedInterfacesAnnotatedWithActivities(activitiesImplementation.getClass(), activitiesInterfaces); if (activitiesInterfaces.size() == 0) { throw new IllegalArgumentException( "Activity implementation object does not implement any interface annotated with @Activities: " + activitiesImplementation.getClass()); } for (Class<?> interfaze : activitiesInterfaces) { Map<String, Method> methods = new HashMap<String, Method>(); ParentInterfaceOptions parentOptions = new ParentInterfaceOptions(); addActivities(activitiesImplementation, interfaze, methods, parentOptions, converter, result); } addedTypes.add(new AddedType(activitiesImplementation, converter)); return new ArrayList<ActivityType>(result); } private void addActivities(Object implementation, Class<?> interfaze, Map<String, Method> methods, ParentInterfaceOptions parentOptions, DataConverter converter, Set<ActivityType> addedTypes) throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException { Activities activitiesAnnotation = interfaze.getAnnotation(Activities.class); for (Class<?> parent : interfaze.getInterfaces()) { addActivities(implementation, parent, methods, parentOptions, converter, addedTypes); } if (activitiesAnnotation != null) { String interfaceName = interfaze.getSimpleName(); if (!nullOrEmpty(activitiesAnnotation.activityNamePrefix())) { parentOptions.setPrefix(activitiesAnnotation.activityNamePrefix()); } if (!nullOrEmpty(activitiesAnnotation.version())) { parentOptions.setVersion(activitiesAnnotation.version()); } converter = (converter == null) ? createConverter(activitiesAnnotation.dataConverter()) : converter; ActivityRegistrationOptions interfaceRegistrationOptionsAnnotation = interfaze.getAnnotation(ActivityRegistrationOptions.class); SkipTypeRegistration interfaceSkipTypeRegistrationAnnotation = interfaze.getAnnotation(SkipTypeRegistration.class); if (interfaceRegistrationOptionsAnnotation != null) { if (interfaceSkipTypeRegistrationAnnotation != null) { throw new IllegalArgumentException( "@ActivityRegistrationOptions is not allowed for the interface annotated with @SkipTypeRegistration."); } parentOptions.setRegistrationOptions(interfaceRegistrationOptionsAnnotation); } else if (interfaceSkipTypeRegistrationAnnotation != null) { parentOptions.setSkipRegistration(true); } for (Method method : interfaze.getMethods()) { if (!method.getDeclaringClass().equals(interfaze)) { continue; } Activity activityAnnotation = method.getAnnotation(Activity.class); ActivityType activityType = getActivityType(interfaceName, method, activityAnnotation, parentOptions); ActivityRegistrationOptions registrationOptionsAnnotation = method.getAnnotation(ActivityRegistrationOptions.class); SkipTypeRegistration skipTypeRegistrationAnnotation = interfaze.getAnnotation(SkipTypeRegistration.class); ActivityTypeRegistrationOptions registrationOptions = null; if (skipTypeRegistrationAnnotation != null) { if (registrationOptionsAnnotation != null) { throw new IllegalArgumentException( "@ActivityRegistrationOptions is not allowed for the method annotated with @SkipTypeRegistration: " + method); } } else { if (registrationOptionsAnnotation != null || parentOptions.getRegistrationOptions() != null) { POJOActivityImplementation existingImplementation = implementationsMap.get(activityType); if (existingImplementation != null && !addedTypes.contains(activityType)) { String message = "Duplicate declaration for activity type=" + activityType.getName() + ", version=" + activityType.getVersion() + ": " + existingImplementation.getMethod() + " and " + method; throw new IllegalArgumentException(message); } registrationOptions = createRegistrationOptions(registrationOptionsAnnotation, parentOptions.getRegistrationOptions()); } else if (!parentOptions.isSkipRegistration()) { throw new IllegalArgumentException( "No @ActivityRegistrationOptions found either on interface or method for " + method); } } //TODO: support methods defined in parents as well as overrides if (!addedTypes.contains(activityType)) { Method activityImplementationMethod = implementation.getClass().getMethod(method.getName(), method.getParameterTypes()); ActivityTypeExecutionOptions executionOptions = createExecutionOptions(activityType, activityImplementationMethod); POJOActivityImplementation activityImplementation = new POJOActivityImplementation(implementation, method, registrationOptions, executionOptions, converter); activityTypesToRegister.add(activityType); addedTypes.add(activityType); implementationsMap.put(activityType, activityImplementation); } } } } @Override public Iterable<ActivityType> getActivityTypesToRegister() { return activityTypesToRegister; } @Override public ActivityImplementation getActivityImplementation(ActivityType activityType) { return implementationsMap.get(activityType); } private DataConverter createConverter(Class<? extends DataConverter> converterType) throws InstantiationException, IllegalAccessException { if (dataConverter != null) { return dataConverter; } if (converterType == null || converterType.equals(NullDataConverter.class)) { return new JsonDataConverter(); } return converterType.newInstance(); } private static ActivityType getActivityType(String interfaceName, Method activity, Activity activityAnnotation, ParentInterfaceOptions parentOptions) { ActivityType activityType = new ActivityType(); String activityName = null; String activityVersion = null; if (activityAnnotation != null) { if (!nullOrEmpty(activityAnnotation.name())) { activityName = activityAnnotation.name(); } if (!nullOrEmpty(activityAnnotation.version())) { activityVersion = activityAnnotation.version(); } } if (activityName == null) { if (!nullOrEmpty(parentOptions.getPrefix())) { activityName = parentOptions.getPrefix() + activity.getName(); } else { activityName = interfaceName + "." + activity.getName(); } } if (activityVersion == null) { if (!nullOrEmpty(parentOptions.getVersion())) { activityVersion = parentOptions.getVersion(); } else { throw new IllegalArgumentException("No version found for activity defined by " + activity); } } activityType.setName(activityName); activityType.setVersion(activityVersion); return activityType; } private static boolean nullOrEmpty(String nameFromAnnotation) { return nameFromAnnotation == null || nameFromAnnotation.isEmpty(); } /** * Recursively find all interfaces annotated with @Activities that given * class implements. Do not include interfaces that @Activities annotated * interface extends. */ private void getImplementedInterfacesAnnotatedWithActivities(Class<?> implementationType, Set<Class<?>> implementedInterfaces) { Class<?> superClass = implementationType.getSuperclass(); if (superClass != null) { getImplementedInterfacesAnnotatedWithActivities(superClass, implementedInterfaces); } Class<?>[] interfaces = implementationType.getInterfaces(); for (Class<?> i : interfaces) { if (i.getAnnotation(Activities.class) != null && !implementedInterfaces.contains(i)) { boolean skipAdd = removeSuperInterfaces(i, implementedInterfaces); if (!skipAdd) { implementedInterfaces.add(i); } } else { getImplementedInterfacesAnnotatedWithActivities(i, implementedInterfaces); } } } private boolean removeSuperInterfaces(Class<?> interfaceToAdd, Set<Class<?>> implementedInterfaces) { boolean skipAdd = false; List<Class<?>> interfacesToRemove = new ArrayList<Class<?>>(); for (Class<?> addedInterface : implementedInterfaces) { if (addedInterface.isAssignableFrom(interfaceToAdd)) { interfacesToRemove.add(addedInterface); } if (interfaceToAdd.isAssignableFrom(addedInterface)) { skipAdd = true; } } for (Class<?> interfaceToRemove : interfacesToRemove) { implementedInterfaces.remove(interfaceToRemove); } return skipAdd; } private static ActivityTypeRegistrationOptions createRegistrationOptions(ActivityRegistrationOptions registrationOptions, ActivityRegistrationOptions parentRegistrationOptions) { ActivityRegistrationOptions registrationOptionsAnnotation = registrationOptions != null ? registrationOptions : parentRegistrationOptions; ActivityTypeRegistrationOptions result = new ActivityTypeRegistrationOptions(); result.setDescription(emptyStringToNull(registrationOptionsAnnotation.description())); long taskHeartbeatTimeoutSeconds = registrationOptionsAnnotation.defaultTaskHeartbeatTimeoutSeconds(); if (taskHeartbeatTimeoutSeconds > FlowConstants.USE_REGISTERED_DEFAULTS) { result.setDefaultTaskHeartbeatTimeoutSeconds(taskHeartbeatTimeoutSeconds); } long taskScheduleToCloseTimeoutSeconds = registrationOptionsAnnotation.defaultTaskScheduleToCloseTimeoutSeconds(); if (taskScheduleToCloseTimeoutSeconds > FlowConstants.USE_REGISTERED_DEFAULTS) { result.setDefaultTaskScheduleToCloseTimeoutSeconds(taskScheduleToCloseTimeoutSeconds); } long taskScheduleToStartTimeoutSeconds = registrationOptionsAnnotation.defaultTaskScheduleToStartTimeoutSeconds(); if (taskScheduleToStartTimeoutSeconds > FlowConstants.USE_REGISTERED_DEFAULTS) { result.setDefaultTaskScheduleToStartTimeoutSeconds(taskScheduleToStartTimeoutSeconds); } long taskStartToCloseTimeoutSeconds = registrationOptionsAnnotation.defaultTaskStartToCloseTimeoutSeconds(); if (taskStartToCloseTimeoutSeconds > FlowConstants.USE_REGISTERED_DEFAULTS) { result.setDefaultTaskStartToCloseTimeoutSeconds(taskStartToCloseTimeoutSeconds); } String taskList = registrationOptionsAnnotation.defaultTaskList(); if (!taskList.equals(FlowConstants.USE_WORKER_TASK_LIST)) { result.setDefaultTaskList(taskList); } else if (taskList.equals(FlowConstants.NO_DEFAULT_TASK_LIST)) { result.setDefaultTaskList(null); } return result; } private static ActivityTypeExecutionOptions createExecutionOptions(ActivityType activityType, Method activityImplementation) { assert (activityType != null); ActivityTypeExecutionOptions executionOptions = new ActivityTypeExecutionOptions(); if (activityImplementation != null) { ManualActivityCompletion manualCompletion = activityImplementation.getAnnotation(ManualActivityCompletion.class); // Iterate our parent classes as well Class<?> cl = activityImplementation.getDeclaringClass(); while(manualCompletion == null) { cl = cl.getSuperclass(); if(cl == null || cl.equals(Object.class)) { break; } try { Method equivalentMethod = cl.getDeclaredMethod(activityImplementation.getName(), activityImplementation.getParameterTypes()); if (equivalentMethod != null) { manualCompletion = equivalentMethod.getAnnotation(ManualActivityCompletion.class); } } catch (NoSuchMethodException e) { // No problem } } executionOptions.setManualActivityCompletion(manualCompletion != null); ActivityExecutionOptions options = activityImplementation.getAnnotation(ActivityExecutionOptions.class); if (options == null) { //TODO: Check superclasses for the annotation options = activityImplementation.getDeclaringClass().getAnnotation(ActivityExecutionOptions.class); } if (options != null) { ActivityCompletionRetryOptions completionRetryOptions = options.completionRetryOptions(); ActivityTypeCompletionRetryOptions typeCompletionRetryOptions = completionRetryOptionsFromAnnotation(completionRetryOptions); executionOptions.setCompletionRetryOptions(typeCompletionRetryOptions); ActivityCompletionRetryOptions failureRetryOptions = options.failureRetryOptions(); ActivityTypeCompletionRetryOptions typeFailureRetryOptions = completionRetryOptionsFromAnnotation(failureRetryOptions); executionOptions.setFailureRetryOptions(typeFailureRetryOptions); } } return executionOptions; } public static ActivityTypeCompletionRetryOptions completionRetryOptionsFromAnnotation( ActivityCompletionRetryOptions failureRetryOptions) { ActivityTypeCompletionRetryOptions typeFailureRetryOptions = new ActivityTypeCompletionRetryOptions(); typeFailureRetryOptions.setInitialRetryIntervalSeconds(failureRetryOptions.initialRetryIntervalSeconds()); typeFailureRetryOptions.setMaximumRetryIntervalSeconds(failureRetryOptions.maximumRetryIntervalSeconds()); typeFailureRetryOptions.setMinimumAttempts(failureRetryOptions.minimumAttempts()); typeFailureRetryOptions.setMaximumAttempts(failureRetryOptions.maximumAttempts()); typeFailureRetryOptions.setBackoffCoefficient(failureRetryOptions.backoffCoefficient()); typeFailureRetryOptions.setRetryExpirationSeconds(failureRetryOptions.retryExpirationSeconds()); return typeFailureRetryOptions; } private static String emptyStringToNull(String value) { if (value.length() == 0) { return null; } return value; } }
3,675
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/spring/CronInvocationSchedule.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.spring; import java.util.Date; import java.util.TimeZone; import org.springframework.scheduling.support.CronSequenceGenerator; import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants; import com.amazonaws.services.simpleworkflow.flow.interceptors.InvocationSchedule; public class CronInvocationSchedule implements InvocationSchedule { protected static final int SECOND = 1000; private final CronSequenceGenerator cronSequenceGenerator; private final Date expiration; public CronInvocationSchedule(String cronExpression, Date expiration, TimeZone timeZone) { cronSequenceGenerator = new CronSequenceGenerator(cronExpression, timeZone); this.expiration = expiration; } @Override public long nextInvocationDelaySeconds(Date currentTime, Date startTime, Date lastInvocationTime, int pastInvocatonsCount) { Date nextInvocationTime; if (lastInvocationTime == null) { nextInvocationTime = cronSequenceGenerator.next(startTime); } else { nextInvocationTime = cronSequenceGenerator.next(lastInvocationTime); } long resultMilliseconds = nextInvocationTime.getTime() - currentTime.getTime(); if (resultMilliseconds < 0) { resultMilliseconds = 0; } if (currentTime.getTime() + resultMilliseconds >= expiration.getTime()) { return FlowConstants.NONE; } return resultMilliseconds / SECOND; } }
3,676
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/spring/SpringActivityWorker.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.spring; import java.lang.Thread.UncaughtExceptionHandler; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig; import org.springframework.context.SmartLifecycle; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.WorkerBase; import com.amazonaws.services.simpleworkflow.flow.pojo.POJOActivityImplementationFactory; import com.amazonaws.services.simpleworkflow.flow.worker.GenericActivityWorker; import com.amazonaws.services.simpleworkflow.model.ActivityType; public class SpringActivityWorker implements WorkerBase, SmartLifecycle { private final GenericActivityWorker genericWorker; private final POJOActivityImplementationFactory factory; private int startPhase; protected long terminationTimeoutSeconds = 60; private boolean disableAutoStartup; public SpringActivityWorker() { this(new GenericActivityWorker()); } public SpringActivityWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll) { this(new GenericActivityWorker(service, domain, taskListToPoll)); } public SpringActivityWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll, SimpleWorkflowClientConfig config) { this(new GenericActivityWorker(service, domain, taskListToPoll, config)); } public SpringActivityWorker(GenericActivityWorker genericWorker) { Objects.requireNonNull(genericWorker,"the activity worker is required"); this.genericWorker = genericWorker; this.factory = new POJOActivityImplementationFactory(); this.genericWorker.setActivityImplementationFactory(factory); } public SimpleWorkflowClientConfig getClientConfig() { return genericWorker.getClientConfig(); } public AmazonSimpleWorkflow getService() { return genericWorker.getService(); } public void setService(AmazonSimpleWorkflow service) { genericWorker.setService(service); } public String getDomain() { return genericWorker.getDomain(); } public void setDomain(String domain) { genericWorker.setDomain(domain); } public boolean isRegisterDomain() { return genericWorker.isRegisterDomain(); } public void setRegisterDomain(boolean registerDomain) { genericWorker.setRegisterDomain(registerDomain); } public long getDomainRetentionPeriodInDays() { return genericWorker.getDomainRetentionPeriodInDays(); } public void setDomainRetentionPeriodInDays(long domainRetentionPeriodInDays) { genericWorker.setDomainRetentionPeriodInDays(domainRetentionPeriodInDays); } public String getTaskListToPoll() { return genericWorker.getTaskListToPoll(); } public void setTaskListToPoll(String taskListToPoll) { genericWorker.setTaskListToPoll(taskListToPoll); } public DataConverter getDataConverter() { return factory.getDataConverter(); } public void setDataConverter(DataConverter dataConverter) { factory.setDataConverter(dataConverter); } public double getMaximumPollRatePerSecond() { return genericWorker.getMaximumPollRatePerSecond(); } public void setMaximumPollRatePerSecond(double maximumPollRatePerSecond) { genericWorker.setMaximumPollRatePerSecond(maximumPollRatePerSecond); } public int getMaximumPollRateIntervalMilliseconds() { return genericWorker.getMaximumPollRateIntervalMilliseconds(); } public void setMaximumPollRateIntervalMilliseconds(int maximumPollRateIntervalMilliseconds) { genericWorker.setMaximumPollRateIntervalMilliseconds(maximumPollRateIntervalMilliseconds); } public String getIdentity() { return genericWorker.getIdentity(); } public void setIdentity(String identity) { genericWorker.setIdentity(identity); } public UncaughtExceptionHandler getUncaughtExceptionHandler() { return genericWorker.getUncaughtExceptionHandler(); } public void setUncaughtExceptionHandler(UncaughtExceptionHandler uncaughtExceptionHandler) { genericWorker.setUncaughtExceptionHandler(uncaughtExceptionHandler); } public long getPollBackoffInitialInterval() { return genericWorker.getPollBackoffInitialInterval(); } public void setPollBackoffInitialInterval(long backoffInitialInterval) { genericWorker.setPollBackoffInitialInterval(backoffInitialInterval); } public long getPollBackoffMaximumInterval() { return genericWorker.getPollBackoffMaximumInterval(); } public void setPollBackoffMaximumInterval(long backoffMaximumInterval) { genericWorker.setPollBackoffMaximumInterval(backoffMaximumInterval); } public double getPollBackoffCoefficient() { return genericWorker.getPollBackoffCoefficient(); } public void setPollBackoffCoefficient(double backoffCoefficient) { genericWorker.setPollBackoffCoefficient(backoffCoefficient); } public int getPollThreadCount() { return genericWorker.getPollThreadCount(); } public void setPollThreadCount(int threadCount) { genericWorker.setPollThreadCount(threadCount); } @Override public int getExecuteThreadCount() { return genericWorker.getExecuteThreadCount(); } @Override public void setExecuteThreadCount(int threadCount) { genericWorker.setExecuteThreadCount(threadCount); } public boolean isDisableServiceShutdownOnStop() { return genericWorker.isDisableServiceShutdownOnStop(); } public void setDisableServiceShutdownOnStop(boolean disableServiceShutdownOnStop) { genericWorker.setDisableServiceShutdownOnStop(disableServiceShutdownOnStop); } @Override public boolean isAllowCoreThreadTimeOut() { return genericWorker.isAllowCoreThreadTimeOut(); } @Override public void setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) { genericWorker.setAllowCoreThreadTimeOut(allowCoreThreadTimeOut); } @Override public void suspendPolling() { genericWorker.suspendPolling(); } @Override public void resumePolling() { genericWorker.resumePolling(); } @Override public boolean isPollingSuspended() { return genericWorker.isPollingSuspended(); } @Override public void setPollingSuspended(boolean flag) { genericWorker.setPollingSuspended(flag); } @Override public void start() { genericWorker.start(); } public void stopNow() { genericWorker.shutdownNow(); } @Override public void shutdown() { genericWorker.shutdown(); } @Override public void shutdownNow() { genericWorker.shutdownNow(); } @Override public boolean shutdownAndAwaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return genericWorker.shutdownAndAwaitTermination(timeout, unit); } public void shutdownAndAwaitTermination() throws InterruptedException { shutdownAndAwaitTermination(terminationTimeoutSeconds, TimeUnit.SECONDS); } public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return genericWorker.awaitTermination(timeout, unit); } @Override public boolean gracefulShutdown(long timeout, TimeUnit unit) throws InterruptedException { return genericWorker.gracefulShutdown(timeout, unit); } @Override public void stop() { try { gracefulShutdown(terminationTimeoutSeconds, TimeUnit.SECONDS); shutdownNow(); } catch (InterruptedException e) { } } public boolean isRunning() { return genericWorker.isRunning(); } public void setActivitiesImplementations(Iterable<Object> activitiesImplementations) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { for (Object activitiesImplementation : activitiesImplementations) { addActivitiesImplementation(activitiesImplementation); } } public Iterable<Object> getActivitiesImplementations() { return factory.getActivitiesImplementations(); } public List<ActivityType> addActivitiesImplementation(Object activitiesImplementation) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException { return factory.addActivitiesImplementation(activitiesImplementation); } @Override public void registerTypesToPoll() { genericWorker.registerTypesToPoll(); } /** * @return default is 0 */ @Override public int getPhase() { return startPhase; } public void setPhase(int startPhase) { this.startPhase = startPhase; } @Override public boolean isAutoStartup() { return !disableAutoStartup; } public long getTerminationTimeoutSeconds() { return terminationTimeoutSeconds; } public void setTerminationTimeoutSeconds(long terminationTimeoutSeconds) { this.terminationTimeoutSeconds = terminationTimeoutSeconds; } public boolean isDisableAutoStartup() { return disableAutoStartup; } public void setDisableAutoStartup(boolean disableAutoStartup) { this.disableAutoStartup = disableAutoStartup; } @Override public void setDisableTypeRegistrationOnStart(boolean disableTypeRegistrationOnStart) { genericWorker.setDisableTypeRegistrationOnStart(disableTypeRegistrationOnStart); } @Override public boolean isDisableTypeRegistrationOnStart() { return genericWorker.isDisableTypeRegistrationOnStart(); } @Override public void stop(Runnable callback) { stop(); callback.run(); } @Override public String toString() { return this.getClass().getSimpleName() + "[genericWorker=" + genericWorker + ", factory=" + factory + "]"; } }
3,677
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/spring/CronDecorator.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.spring; import java.util.Date; import java.util.TimeZone; import org.springframework.scheduling.support.CronSequenceGenerator; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.interceptors.ScheduleDecorator; /** * Repeats any call to the decorated object according to a schedule specified using unix "cron" syntax. * Relies on {@link CronSequenceGenerator} for cron parsing and interpretation. * * @author fateev */ public class CronDecorator extends ScheduleDecorator { public CronDecorator(String cronExpression, Date expiration, TimeZone timeZone, WorkflowClock clock) { super(new CronInvocationSchedule(cronExpression, expiration, timeZone), clock); } }
3,678
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/spring/POJOWorkflowStubImplementationFactory.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.spring; import com.amazonaws.services.simpleworkflow.flow.DecisionContext; import com.amazonaws.services.simpleworkflow.flow.pojo.POJOWorkflowImplementationFactory; /** * A stub implementation of the @see{POJOWorkflowImplementationFactory} * Used for Spring injection proxying * * @author nicholasterry */ public class POJOWorkflowStubImplementationFactory implements POJOWorkflowImplementationFactory { private Object instanceProxy; public POJOWorkflowStubImplementationFactory(Object instanceProxy) { this.instanceProxy = instanceProxy; } @Override public Object newInstance(DecisionContext decisionContext) throws Exception { WorkflowScope.setDecisionContext(decisionContext); return instanceProxy; } @Override public void deleteInstance(Object instance) { WorkflowScope.removeDecisionContext(); } @Override public Object newInstance(DecisionContext decisionContext, Object[] constructorArgs) throws Exception { WorkflowScope.setDecisionContext(decisionContext); return instanceProxy; } }
3,679
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/spring/WorkflowScopeBeanNames.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.spring; public class WorkflowScopeBeanNames { public static final String GENERIC_ACTIVITY_CLIENT = "genericActivityClient"; public static final String GENERIC_WORKFLOW_CLIENT = "genericWorkflowClient"; public static final String WORKFLOW_CLOCK = "workflowClock"; public static final String WORKFLOW_CONTEXT = "workflowContext"; public static final String DECISION_CONTEXT = "decisionContext"; public static boolean isWorkflowScopeBeanName(String name) { if (GENERIC_ACTIVITY_CLIENT.equals(name)) { return true; } if (GENERIC_WORKFLOW_CLIENT.equals(name)) { return true; } if (WORKFLOW_CLOCK.equals(name)) { return true; } if (WORKFLOW_CONTEXT.equals(name)) { return true; } if (DECISION_CONTEXT.equals(name)) { return true; } return false; } }
3,680
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/spring/SpringWorkflowDefinitionFactoryFactory.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.spring; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.aop.framework.Advised; import com.amazonaws.services.simpleworkflow.flow.DataConverter; 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.core.Promise; import com.amazonaws.services.simpleworkflow.flow.core.Settable; import com.amazonaws.services.simpleworkflow.flow.generic.ContinueAsNewWorkflowExecutionParameters; import com.amazonaws.services.simpleworkflow.flow.generic.ExecuteActivityParameters; 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.WorkflowDefinitionFactory; import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactoryFactory; import com.amazonaws.services.simpleworkflow.flow.pojo.POJOWorkflowDefinitionFactoryFactory; import com.amazonaws.services.simpleworkflow.flow.pojo.POJOWorkflowImplementationFactory; import com.amazonaws.services.simpleworkflow.flow.worker.LambdaFunctionClient; import com.amazonaws.services.simpleworkflow.model.ChildPolicy; import com.amazonaws.services.simpleworkflow.model.WorkflowExecution; import com.amazonaws.services.simpleworkflow.model.WorkflowType; class SpringWorkflowDefinitionFactoryFactory extends WorkflowDefinitionFactoryFactory { /** * Used to instantiate workflow implementation with workflow scope to get * its class. */ private static final class DummyDecisionContext extends DecisionContext { @Override public GenericActivityClient getActivityClient() { return new GenericActivityClient() { @Override public Promise<String> scheduleActivityTask(String activity, String version, Promise<String> input) { throw new UnsupportedOperationException(); } @Override public Promise<String> scheduleActivityTask(String activity, String version, String input) { throw new UnsupportedOperationException(); } @Override public Promise<String> scheduleActivityTask(ExecuteActivityParameters parameters) { throw new UnsupportedOperationException(); } }; } @Override public GenericWorkflowClient getWorkflowClient() { return new GenericWorkflowClient() { @Override public Promise<String> startChildWorkflow(String workflow, String version, Promise<String> input) { throw new UnsupportedOperationException(); } @Override public Promise<String> startChildWorkflow(String workflow, String version, String input) { throw new UnsupportedOperationException(); } @Override public Promise<StartChildWorkflowReply> startChildWorkflow(StartChildWorkflowExecutionParameters parameters) { throw new UnsupportedOperationException(); } @Override public Promise<Void> signalWorkflowExecution(SignalExternalWorkflowParameters signalParameters) { throw new UnsupportedOperationException(); } @Override public void requestCancelWorkflowExecution(WorkflowExecution execution) { throw new UnsupportedOperationException(); } @Override public String generateUniqueId() { throw new UnsupportedOperationException(); } @Override public void continueAsNewOnCompletion(ContinueAsNewWorkflowExecutionParameters parameters) { throw new UnsupportedOperationException(); } }; } @Override public WorkflowClock getWorkflowClock() { return new WorkflowClock() { @Override public long currentTimeMillis() { return 0; } @Override public boolean isReplaying() { return false; } @Override public Promise<Void> createTimer(long delaySeconds) { return new Settable<Void>(); } @Override public <T> Promise<T> createTimer(long delaySeconds, T context) { return new Settable<T>(); } @Override public <T> Promise<T> createTimer(long delaySeconds, T context, String timerId) { return new Settable<T>(); } }; } @Override public WorkflowContext getWorkflowContext() { return new WorkflowContext() { @Override public WorkflowExecution getWorkflowExecution() { WorkflowExecution result = new WorkflowExecution(); result.setRunId("dummyRunId"); result.setWorkflowId("dummyWorkflowId"); return result; } @Override public WorkflowExecution getParentWorkflowExecution() { return null; } @Override public WorkflowType getWorkflowType() { WorkflowType result = new WorkflowType(); result.setName("dummyName"); result.setVersion("dummyVersion"); return result; } @Override public boolean isCancelRequested() { return false; } @Override public ContinueAsNewWorkflowExecutionParameters getContinueAsNewOnCompletion() { return null; } @Override public void setContinueAsNewOnCompletion(ContinueAsNewWorkflowExecutionParameters continueParameters) { } @Override public List<String> getTagList() { return Collections.emptyList(); } @Override public ChildPolicy getChildPolicy() { return ChildPolicy.TERMINATE; } @Override public String getContinuedExecutionRunId() { return null; } @Override public long getExecutionStartToCloseTimeout() { return 0; } @Override public String getTaskList() { return "dummyTaskList"; } @Override public boolean isImplementationVersion(String componentName, int internalVersion) { return false; } @Override public Integer getVersion(String component) { return 0; } @Override public int getTaskPriority() { return 0; } @Override public String getLambdaRole() { return null; } }; } @Override public LambdaFunctionClient getLambdaFunctionClient() { return new LambdaFunctionClient() { @Override public Promise<String> scheduleLambdaFunction(String name, String input, long timeoutSeconds) { return new Settable<String>(); } @Override public Promise<String> scheduleLambdaFunction(String name, String input) { return new Settable<String>(); } @Override public Promise<String> scheduleLambdaFunction(String name, Promise<String> input) { return new Settable<String>(); } @Override public Promise<String> scheduleLambdaFunction(String name, Promise<String> input, long timeoutSeconds) { return new Settable<String>(); } @Override public Promise<String> scheduleLambdaFunction(String name, String input, long timeoutSeconds, String functionId) { return new Settable<String>(); } }; } } private final POJOWorkflowDefinitionFactoryFactory impl = 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>(); @Override public WorkflowDefinitionFactory getWorkflowDefinitionFactory(WorkflowType workflowType) { return impl.getWorkflowDefinitionFactory(workflowType); } @Override public Iterable<WorkflowType> getWorkflowTypesToRegister() { return impl.getWorkflowTypesToRegister(); } 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; if (workflowImplementation instanceof Advised) { Advised advised = (Advised) workflowImplementation; // Cannot use advised.getTargetClass() as the following configuration: // // @Bean(name="workflowImpl", autowire=Autowire.BY_TYPE) // @Scope(value="workflow", proxyMode=ScopedProxyMode.INTERFACES) // public MyWorkflow myWorkflow() { // return new MyWorkflowImpl(); // } // // returns MyWorkflow.class when // we need MyWorkflowImpl.class // So the workaround is to instantiate workflow implementation which requires // initialization of the WorkflowScope with a context. try { WorkflowScope.setDecisionContext(new DummyDecisionContext()); Object target = advised.getTargetSource().getTarget(); implementationClass = target.getClass(); } catch (Exception e) { throw new IllegalArgumentException(e); } finally { WorkflowScope.removeDecisionContext(); } } else { implementationClass = workflowImplementation.getClass(); } workflowImplementations.put(implementationClass, workflowImplementation); impl.addWorkflowImplementationType(implementationClass); } public DataConverter getDataConverter() { return impl.getDataConverter(); } public void setDataConverter(DataConverter converter) { impl.setDataConverter(converter); } public void setMaximumAllowedComponentImplementationVersions( Map<WorkflowType, Map<String, Integer>> maximumAllowedImplementationVersions) { impl.setMaximumAllowedComponentImplementationVersions(maximumAllowedImplementationVersions); } public Map<WorkflowType, Map<String, Integer>> getMaximumAllowedComponentImplementationVersions() { return impl.getMaximumAllowedComponentImplementationVersions(); } }
3,681
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/spring/WorkflowScope.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.spring; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.BeansException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.Scope; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; 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.WorkflowExecutionLocal; import com.amazonaws.services.simpleworkflow.flow.generic.GenericActivityClient; import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClient; import com.amazonaws.services.simpleworkflow.flow.worker.CurrentDecisionContext; /** * */ public class WorkflowScope implements Scope, ApplicationContextAware { public static final String NAME = "workflow"; private DecisionContextProvider contextProvider = new DecisionContextProviderImpl(); private static WorkflowExecutionLocal<Map<String, Object>> objects = new WorkflowExecutionLocal<Map<String, Object>>() { @Override protected Map<String, Object> initialValue() { return new HashMap<String, Object>(); } }; private static WorkflowExecutionLocal<List<Runnable>> destructionCallbacks = new WorkflowExecutionLocal<List<Runnable>>() { @Override protected List<Runnable> initialValue() { return new ArrayList<Runnable>(); } }; public static void setDecisionContext(DecisionContext context) { CurrentDecisionContext.set(context); destructionCallbacks.get().clear(); set(WorkflowScopeBeanNames.GENERIC_ACTIVITY_CLIENT, context.getActivityClient()); set(WorkflowScopeBeanNames.GENERIC_WORKFLOW_CLIENT, context.getWorkflowClient()); set(WorkflowScopeBeanNames.WORKFLOW_CLOCK, context.getWorkflowClock()); set(WorkflowScopeBeanNames.WORKFLOW_CONTEXT, context.getWorkflowContext()); set(WorkflowScopeBeanNames.DECISION_CONTEXT, context); } public static void removeDecisionContext() { for (Runnable callback: destructionCallbacks.get()) { callback.run(); } CurrentDecisionContext.unset(); } @Override public Object get(String name, ObjectFactory<?> objectFactory) { Map<String, Object> map = objects.get(); Object result = map.get(name); if (result == null) { result = objectFactory.getObject(); map.put(name, result); } return result; } private static void set(String name, Object bean) { Map<String, Object> map = objects.get(); map.put(name, bean); } @Override public String getConversationId() { return contextProvider.getDecisionContext().getWorkflowContext().getWorkflowExecution().getRunId(); } @Override public void registerDestructionCallback(String name, Runnable callback) { destructionCallbacks.get().add(callback); } @Override public Object remove(String name) { Map<String, Object> map = objects.get(); return map.remove(name); } @Override public Object resolveContextualObject(String name) { //TODO: Understand why WorkflowScopeBeans cannot be returned from this method return null; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory(); if (!(autowireCapableBeanFactory instanceof DefaultListableBeanFactory)) { throw new IllegalArgumentException( "The implementation returned from applicationContext.getAutowireCapableBeanFactory() " + "doesn't implement DefaultListableBeanFactory"); } DefaultListableBeanFactory factory = (DefaultListableBeanFactory) autowireCapableBeanFactory; registerBean(factory, WorkflowScopeBeanNames.GENERIC_ACTIVITY_CLIENT, GenericActivityClient.class); registerBean(factory, WorkflowScopeBeanNames.GENERIC_WORKFLOW_CLIENT, GenericWorkflowClient.class); registerBean(factory, WorkflowScopeBeanNames.WORKFLOW_CLOCK, WorkflowClock.class); registerBean(factory, WorkflowScopeBeanNames.WORKFLOW_CONTEXT, WorkflowContext.class); registerBean(factory, WorkflowScopeBeanNames.DECISION_CONTEXT, DecisionContext.class); } private void registerBean(DefaultListableBeanFactory factory, String beanName, Class<?> beanClass) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(beanClass); builder.setScope(NAME); factory.registerBeanDefinition(beanName, builder.getBeanDefinition()); } }
3,682
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/spring/SpringWorkflowWorker.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.spring; import com.amazonaws.services.simpleworkflow.flow.ChildWorkflowIdHandler; import java.lang.Thread.UncaughtExceptionHandler; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig; import org.springframework.context.SmartLifecycle; import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow; import com.amazonaws.services.simpleworkflow.flow.DataConverter; import com.amazonaws.services.simpleworkflow.flow.WorkerBase; import com.amazonaws.services.simpleworkflow.flow.worker.GenericWorkflowWorker; import com.amazonaws.services.simpleworkflow.model.WorkflowType; /** * To be used with Spring. Assumes that injected implementation bean has * "workflow" scope. Otherwise the same object instance will be reused for * multiple decisions which is guaranteed to break replay if any instance fields * are used. */ public class SpringWorkflowWorker implements WorkerBase, SmartLifecycle { private final GenericWorkflowWorker genericWorker; private final SpringWorkflowDefinitionFactoryFactory factoryFactory; private int startPhase; protected long terminationTimeoutSeconds = 60; private boolean disableAutoStartup; public SpringWorkflowWorker() { this(new GenericWorkflowWorker()); } public SpringWorkflowWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll) { this(new GenericWorkflowWorker(service, domain, taskListToPoll)); } public SpringWorkflowWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll, SimpleWorkflowClientConfig config) { this(new GenericWorkflowWorker(service, domain, taskListToPoll, config)); } public SpringWorkflowWorker(GenericWorkflowWorker genericWorker) { Objects.requireNonNull(genericWorker,"the workflow worker is required"); this.genericWorker = genericWorker; this.factoryFactory = new SpringWorkflowDefinitionFactoryFactory(); this.genericWorker.setWorkflowDefinitionFactoryFactory(factoryFactory); } public SimpleWorkflowClientConfig getClientConfig() { return genericWorker.getClientConfig(); } public AmazonSimpleWorkflow getService() { return genericWorker.getService(); } public void setService(AmazonSimpleWorkflow service) { genericWorker.setService(service); } @Override public String getDomain() { return genericWorker.getDomain(); } public void setDomain(String domain) { genericWorker.setDomain(domain); } @Override public boolean isRegisterDomain() { return genericWorker.isRegisterDomain(); } public void setRegisterDomain(boolean registerDomain) { genericWorker.setRegisterDomain(registerDomain); } @Override public long getDomainRetentionPeriodInDays() { return genericWorker.getDomainRetentionPeriodInDays(); } public void setDomainRetentionPeriodInDays(long domainRetentionPeriodInDays) { genericWorker.setDomainRetentionPeriodInDays(domainRetentionPeriodInDays); } @Override public String getTaskListToPoll() { return genericWorker.getTaskListToPoll(); } public void setTaskListToPoll(String taskListToPoll) { genericWorker.setTaskListToPoll(taskListToPoll); } public DataConverter getDataConverter() { return factoryFactory.getDataConverter(); } public void setDataConverter(DataConverter converter) { factoryFactory.setDataConverter(converter); } @Override public double getMaximumPollRatePerSecond() { return genericWorker.getMaximumPollRatePerSecond(); } @Override public void setMaximumPollRatePerSecond(double maximumPollRatePerSecond) { genericWorker.setMaximumPollRatePerSecond(maximumPollRatePerSecond); } @Override public int getMaximumPollRateIntervalMilliseconds() { return genericWorker.getMaximumPollRateIntervalMilliseconds(); } @Override public void setMaximumPollRateIntervalMilliseconds(int maximumPollRateIntervalMilliseconds) { genericWorker.setMaximumPollRateIntervalMilliseconds(maximumPollRateIntervalMilliseconds); } @Override public UncaughtExceptionHandler getUncaughtExceptionHandler() { return genericWorker.getUncaughtExceptionHandler(); } @Override public void setUncaughtExceptionHandler(UncaughtExceptionHandler uncaughtExceptionHandler) { genericWorker.setUncaughtExceptionHandler(uncaughtExceptionHandler); } @Override public String getIdentity() { return genericWorker.getIdentity(); } @Override public void setIdentity(String identity) { genericWorker.setIdentity(identity); } @Override public long getPollBackoffInitialInterval() { return genericWorker.getPollBackoffInitialInterval(); } @Override public void setPollBackoffInitialInterval(long backoffInitialInterval) { genericWorker.setPollBackoffInitialInterval(backoffInitialInterval); } @Override public long getPollBackoffMaximumInterval() { return genericWorker.getPollBackoffMaximumInterval(); } @Override public void setPollBackoffMaximumInterval(long backoffMaximumInterval) { genericWorker.setPollBackoffMaximumInterval(backoffMaximumInterval); } @Override public boolean isDisableServiceShutdownOnStop() { return genericWorker.isDisableServiceShutdownOnStop(); } @Override public void setDisableServiceShutdownOnStop(boolean disableServiceShutdownOnStop) { genericWorker.setDisableServiceShutdownOnStop(disableServiceShutdownOnStop); } @Override public boolean isAllowCoreThreadTimeOut() { return genericWorker.isAllowCoreThreadTimeOut(); } @Override public void setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut) { genericWorker.setAllowCoreThreadTimeOut(allowCoreThreadTimeOut); } @Override public void setDisableTypeRegistrationOnStart(boolean disableTypeRegistrationOnStart) { genericWorker.setDisableTypeRegistrationOnStart(disableTypeRegistrationOnStart); } @Override public boolean isDisableTypeRegistrationOnStart() { return genericWorker.isDisableTypeRegistrationOnStart(); } @Override public double getPollBackoffCoefficient() { return genericWorker.getPollBackoffCoefficient(); } @Override public void setPollBackoffCoefficient(double backoffCoefficient) { genericWorker.setPollBackoffCoefficient(backoffCoefficient); } @Override public int getPollThreadCount() { return genericWorker.getPollThreadCount(); } @Override public void setPollThreadCount(int threadCount) { genericWorker.setPollThreadCount(threadCount); } @Override public int getExecuteThreadCount() { return genericWorker.getExecuteThreadCount(); } @Override public void setExecuteThreadCount(int threadCount) { genericWorker.setExecuteThreadCount(threadCount); } public void setChildWorkflowIdHandler(ChildWorkflowIdHandler childWorkflowIdHandler) { genericWorker.setChildWorkflowIdHandler(childWorkflowIdHandler); } @Override public void suspendPolling() { genericWorker.suspendPolling(); } @Override public void resumePolling() { genericWorker.resumePolling(); } @Override public boolean isPollingSuspended() { return genericWorker.isPollingSuspended(); } @Override public void setPollingSuspended(boolean flag) { genericWorker.setPollingSuspended(flag); } public Iterable<WorkflowType> getWorkflowTypesToRegister() { return factoryFactory.getWorkflowTypesToRegister(); } @Override public void start() { genericWorker.start(); } @Override public void shutdown() { genericWorker.shutdown(); } @Override public void shutdownNow() { genericWorker.shutdownNow(); } @Override public boolean shutdownAndAwaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return genericWorker.shutdownAndAwaitTermination(timeout, unit); } public void shutdownAndAwaitTermination() throws InterruptedException { shutdownAndAwaitTermination(terminationTimeoutSeconds, TimeUnit.SECONDS); } public void stopNow() { genericWorker.shutdownNow(); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return genericWorker.awaitTermination(timeout, unit); } @Override public boolean gracefulShutdown(long timeout, TimeUnit unit) throws InterruptedException { return genericWorker.gracefulShutdown(timeout, unit); } public void setWorkflowImplementations(Iterable<Object> workflowImplementations) throws InstantiationException, IllegalAccessException { for (Object workflowImplementation : workflowImplementations) { addWorkflowImplementation(workflowImplementation); } } public Iterable<Object> getWorkflowImplementations() { return factoryFactory.getWorkflowImplementations(); } public void addWorkflowImplementation(Object workflowImplementation) throws InstantiationException, IllegalAccessException { factoryFactory.addWorkflowImplementation(workflowImplementation); } public void setMaximumAllowedComponentImplementationVersions( Map<WorkflowType, Map<String, Integer>> maximumAllowedImplementationVersions) { factoryFactory.setMaximumAllowedComponentImplementationVersions(maximumAllowedImplementationVersions); } public Map<WorkflowType, Map<String, Integer>> getMaximumAllowedComponentImplementationVersions() { return factoryFactory.getMaximumAllowedComponentImplementationVersions(); } @Override public String toString() { return this.getClass().getSimpleName() + "[genericWorker=" + genericWorker + ", factoryFactory=" + factoryFactory + "]"; } @Override public void stop() { try { gracefulShutdown(terminationTimeoutSeconds, TimeUnit.SECONDS); shutdownNow(); } catch (InterruptedException e) { } } @Override public boolean isRunning() { return genericWorker.isRunning(); } /** * @return default is 0 */ @Override public int getPhase() { return startPhase; } public void setPhase(int startPhase) { this.startPhase = startPhase; } @Override public boolean isAutoStartup() { return !disableAutoStartup; } public long getTerminationTimeoutSeconds() { return terminationTimeoutSeconds; } public void setTerminationTimeoutSeconds(long terminationTimeoutSeconds) { this.terminationTimeoutSeconds = terminationTimeoutSeconds; } public boolean isDisableAutoStartup() { return disableAutoStartup; } public void setDisableAutoStartup(boolean disableAutoStartup) { this.disableAutoStartup = disableAutoStartup; } @Override public void stop(Runnable callback) { stop(); callback.run(); } @Override public void registerTypesToPoll() { genericWorker.registerTypesToPoll(); } }
3,683
0
Create_ds/aws-kinesisanalytics-runtime/src/test/java/com/amazonaws/services/kinesisanalytics
Create_ds/aws-kinesisanalytics-runtime/src/test/java/com/amazonaws/services/kinesisanalytics/runtime/KinesisAnalyticsRuntimeTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.kinesisanalytics.runtime; import org.junit.Test; import java.io.IOException; import java.util.Map; import java.util.Properties; import static org.assertj.core.api.Assertions.assertThat; public class KinesisAnalyticsRuntimeTest { @Test public void testGetApplicationProperties() throws IOException { Map<String, Properties> propertyGroups = KinesisAnalyticsRuntime.getApplicationProperties(getClass() .getClassLoader() .getResource("testApplicationProperties.json") .getPath()); Properties stream1Props = propertyGroups.get("Stream1"); assertThat(stream1Props.getProperty("Region")).isEqualTo("us-east-1"); Properties stream2Props = propertyGroups.get("Stream2"); assertThat(stream2Props.getProperty("Region")).isEqualTo("us-east-2"); assertThat(stream2Props.getProperty("Offset")).isEqualTo("latest"); } @Test public void testGetApplicationPropertiesNoFile() throws IOException { Map<String, Properties> propertyGroups = KinesisAnalyticsRuntime.getApplicationProperties("nosuchfile.json"); assertThat(propertyGroups).isEmpty(); } @Test public void testGetConfigProperties() throws IOException { Properties configProperties = KinesisAnalyticsRuntime.getConfigProperties(); assertThat(configProperties).isNotNull(); } }
3,684
0
Create_ds/aws-kinesisanalytics-runtime/src/main/java/com/amazonaws/services/kinesisanalytics/flink
Create_ds/aws-kinesisanalytics-runtime/src/main/java/com/amazonaws/services/kinesisanalytics/flink/serialization/POJODeserializationSchema.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.kinesisanalytics.flink.serialization; import org.apache.flink.api.common.serialization.DeserializationSchema; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; public class POJODeserializationSchema<T> implements DeserializationSchema<T> { private final ObjectMapper mapper = new ObjectMapper(); private final Class<T> clazz; POJODeserializationSchema(Class<T> clazz) { this.clazz = clazz; } @Override public T deserialize(byte[] bytes) throws IOException { return mapper.readValue(bytes, clazz); } @Override public boolean isEndOfStream(T t) { return false; } @Override public TypeInformation<T> getProducedType() { return TypeInformation.of(clazz); } }
3,685
0
Create_ds/aws-kinesisanalytics-runtime/src/main/java/com/amazonaws/services/kinesisanalytics
Create_ds/aws-kinesisanalytics-runtime/src/main/java/com/amazonaws/services/kinesisanalytics/runtime/ConfigConstants.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.kinesisanalytics.runtime; class ConfigConstants { static final String APPLICATION_PROPERTIES_FILE = "application_properties_file"; }
3,686
0
Create_ds/aws-kinesisanalytics-runtime/src/main/java/com/amazonaws/services/kinesisanalytics
Create_ds/aws-kinesisanalytics-runtime/src/main/java/com/amazonaws/services/kinesisanalytics/runtime/KinesisAnalyticsRuntime.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.kinesisanalytics.runtime; import com.amazonaws.services.kinesisanalytics.runtime.models.PropertyGroup; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * This class encapsulates the Runtime values Kinesis Analytics provides to Applications */ public class KinesisAnalyticsRuntime { /** * Returns the application properties passed to the application when the application was started or updated * * @return a map of PropertyGroupId to java.util.Properties * @throws IOException if an exception is encountered */ public static Map<String, Properties> getApplicationProperties() throws IOException { Properties configProperties = getConfigProperties(); return getApplicationProperties(configProperties.getProperty(ConfigConstants.APPLICATION_PROPERTIES_FILE)); } /** * Returns the application properties passed to the application when the application was started or updated * * @param filename name of the file that contains the property groups * @return a map of PropertyGroupId to java.util.Properties * @throws IOException if an exception is encountered */ public static Map<String, Properties> getApplicationProperties(String filename) throws IOException { Map<String, Properties> appProperties = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); try { JsonNode root = mapper.readTree(new FileInputStream(filename)); for (JsonNode elem : root) { PropertyGroup propertyGroup = mapper.treeToValue(elem, PropertyGroup.class); Properties properties = new Properties(); properties.putAll(propertyGroup.properties); appProperties.put(propertyGroup.groupID, properties); } } catch (FileNotFoundException ignored) { // swallow file not found and return empty runtime properties } return appProperties; } @VisibleForTesting static Properties getConfigProperties() throws IOException { InputStream configPropertiesStream = KinesisAnalyticsRuntime.class.getClassLoader().getResourceAsStream("config.properties"); if (configPropertiesStream == null) { throw new FileNotFoundException("config.properties"); } Properties configProperties = new Properties(); configProperties.load(configPropertiesStream); return configProperties; } }
3,687
0
Create_ds/aws-kinesisanalytics-runtime/src/main/java/com/amazonaws/services/kinesisanalytics/runtime
Create_ds/aws-kinesisanalytics-runtime/src/main/java/com/amazonaws/services/kinesisanalytics/runtime/models/PropertyGroup.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License 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.kinesisanalytics.runtime.models; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; public class PropertyGroup { @JsonProperty(value = "PropertyGroupId") public String groupID; @JsonProperty(value = "PropertyMap") public Map<String, String> properties; }
3,688
0
Create_ds/amazon-neptune-sigv4-signer/src/test/java/com/amazonaws/neptune
Create_ds/amazon-neptune-sigv4-signer/src/test/java/com/amazonaws/neptune/auth/NeptuneNettyHttpSigV4SignerTest.java
/* * Copyright 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://www.apache.org/licenses/LICENSE-2.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.neptune.auth; import com.amazonaws.SignableRequest; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import org.apache.commons.io.IOUtils; import org.junit.Test; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class NeptuneNettyHttpSigV4SignerTest extends NeptuneSigV4SignerAbstractTest<FullHttpRequest> { private final NeptuneNettyHttpSigV4Signer signer; public NeptuneNettyHttpSigV4SignerTest() throws NeptuneSigV4SignerException { this.signer = new NeptuneNettyHttpSigV4Signer(TEST_REGION, awsCredentialsProvider); } @Override protected NeptuneSigV4SignerBase<FullHttpRequest> getSigner() { return signer; } @Override protected FullHttpRequest createGetRequest(final String fullURI, final Map<String, String> expectedHeaders) { final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, fullURI, Unpooled.buffer() ); expectedHeaders.entrySet().forEach(entry -> request.headers().add(entry.getKey(), entry.getValue())); return request; } @Override protected FullHttpRequest createPostRequest(final String fullURI, final Map<String, String> expectedHeaders, final String payload) { final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, fullURI, Unpooled.copiedBuffer(payload.getBytes(StandardCharsets.UTF_8)) ); expectedHeaders.entrySet().forEach(entry -> request.headers().add(entry.getKey(), entry.getValue())); return request; } @Override protected Map<String, String> getRequestHeaders(FullHttpRequest request) { final Map<String, String> headers = new HashMap<>(); request.headers().forEach(header -> headers.put(header.getKey(), header.getValue())); return headers; } @Test public void toSignableRequestNoHostInUri() throws Exception { final String uri = TEST_REQUEST_PATH_WITH_SLASH; final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri, Unpooled.buffer() ); request.headers().add(HEADER_ONE_NAME, HEADER_ONE_VALUE); request.headers().add(HEADER_TWO_NAME, HEADER_TWO_VALUE); request.headers().add(HOST_HEADER_NAME, TEST_ENDPOINT); // call final SignableRequest signableRequest = signer.toSignableRequest(request); // verification assertEquals("", IOUtils.toString(signableRequest.getContent(), StandardCharsets.UTF_8)); assertEquals(URI.create(TEST_ENDPOINT_URI), signableRequest.getEndpoint()); assertEquals(TEST_REQUEST_PATH_WITH_SLASH, signableRequest.getResourcePath()); Map<String, String> headers = signableRequest.getHeaders(); assertEquals(2, headers.size()); assertEquals(HEADER_ONE_VALUE, headers.get(HEADER_ONE_NAME)); assertEquals(HEADER_TWO_VALUE, headers.get(HEADER_TWO_NAME)); } }
3,689
0
Create_ds/amazon-neptune-sigv4-signer/src/test/java/com/amazonaws/neptune
Create_ds/amazon-neptune-sigv4-signer/src/test/java/com/amazonaws/neptune/auth/NeptuneRequestMetadataSigV4SignerTest.java
/* * Copyright 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://www.apache.org/licenses/LICENSE-2.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.neptune.auth; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Optional; public class NeptuneRequestMetadataSigV4SignerTest extends NeptuneSigV4SignerAbstractTest<RequestMetadata> { private final NeptuneRequestMetadataSigV4Signer signer; public NeptuneRequestMetadataSigV4SignerTest() throws NeptuneSigV4SignerException { this.signer = new NeptuneRequestMetadataSigV4Signer(TEST_REGION, awsCredentialsProvider); } @Override protected NeptuneSigV4SignerBase<RequestMetadata> getSigner() { return signer; } @Override protected RequestMetadata createGetRequest(String fullURI, Map<String, String> expectedHeaders) { return new RequestMetadata(fullURI, HTTP_GET, Optional.empty(), expectedHeaders, null); } @Override protected RequestMetadata createPostRequest(final String fullURI, final Map<String, String> expectedHeaders, final String payload) { return new RequestMetadata(fullURI, HTTP_POST, Optional.of(payload.getBytes(StandardCharsets.UTF_8)), expectedHeaders, null); } @Override protected Map<String, String> getRequestHeaders(final RequestMetadata request) { return request.getHeaders(); } }
3,690
0
Create_ds/amazon-neptune-sigv4-signer/src/test/java/com/amazonaws/neptune
Create_ds/amazon-neptune-sigv4-signer/src/test/java/com/amazonaws/neptune/auth/NeptuneSigV4SignerAbstractTest.java
/* * Copyright 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://www.apache.org/licenses/LICENSE-2.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.neptune.auth; import com.amazonaws.SignableRequest; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.internal.SignerConstants; import org.apache.commons.io.IOUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.net.URI; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; /** * Defines the basic set of tests that each signer implementation should pass. * @param <T> the type of the request object for the implemented signer class. */ @Ignore public abstract class NeptuneSigV4SignerAbstractTest<T> { protected static final String HEADER_ONE_NAME = "header1"; protected static final String HEADER_ONE_VALUE = "value1"; protected static final String HEADER_TWO_NAME = "header2"; protected static final String HEADER_TWO_VALUE = "value2"; protected static final String HOST_HEADER_NAME = "host"; protected static final String TEST_REQUEST_PATH = "/path/test"; protected static final String TEST_REQUEST_PATH_WITH_SLASH = TEST_REQUEST_PATH + "/"; protected static final String TEST_HOST_NAME = "example.com"; protected static final String TEST_PORT = "8182"; protected static final String TEST_ENDPOINT = TEST_HOST_NAME + ":" + TEST_PORT; protected static final String TEST_ENDPOINT_URI = "http://" + TEST_ENDPOINT; protected static final String TEST_FULL_URI = TEST_ENDPOINT_URI + TEST_REQUEST_PATH; protected static final String TEST_FULL_URI_WITH_SLASH = TEST_ENDPOINT_URI + TEST_REQUEST_PATH_WITH_SLASH; protected static final String TEST_REGION = "us-east-1"; protected static final String TEST_SPARQL_QUERY = "select * from {?s ?p ?o}"; protected static final String HTTP_GET = "GET"; protected static final String HTTP_POST = "POST"; protected static final String TEST_QUERY_PARAM_NAME = "query"; protected static final String TEST_DATE_HEADER_VALUE = "2020/10/04"; protected static final String TEST_AUTHORIZATION_HEADER_VALUE = "Authorization Header"; protected static final String TEST_SESSION_TOKEN_VALUE = "Session Token"; protected final AWSCredentialsProvider awsCredentialsProvider = mock(AWSCredentialsProvider.class); private NeptuneSigV4SignerBase<T> signer; @Before public void setup() { signer = getSigner(); } abstract protected NeptuneSigV4SignerBase<T> getSigner(); abstract protected T createGetRequest(final String fullURI, final Map<String, String> expectedHeaders); abstract protected T createPostRequest(final String fullURI, final Map<String, String> expectedHeaders, final String payload); abstract protected Map<String, String> getRequestHeaders(final T request); @Test public void toSignableRequestHappyGet() throws Exception { // prep final String uri = TEST_FULL_URI; final Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put(HEADER_ONE_NAME, HEADER_ONE_VALUE); requestHeaders.put(HEADER_TWO_NAME, HEADER_TWO_VALUE); requestHeaders.put(HOST_HEADER_NAME, TEST_ENDPOINT); final T request = createGetRequest(uri, requestHeaders); // call final SignableRequest signableRequest = signer.toSignableRequest(request); // verify final Map<String, List<String>> headers = signableRequest.getHeaders(); assertEquals("Headers host size should be 2", 2, headers.size()); assertEquals("Non host header should be retained", HEADER_ONE_VALUE, headers.get(HEADER_ONE_NAME)); assertEquals("Non host header should be retained", HEADER_TWO_VALUE, headers.get(HEADER_TWO_NAME)); assertEquals("Request content should be blank", "", IOUtils.toString(signableRequest.getContent(), StandardCharsets.UTF_8)); assertEquals("Unexpected endpoint", URI.create(TEST_ENDPOINT_URI), signableRequest.getEndpoint()); assertEquals("Unexpected resource path", TEST_REQUEST_PATH, signableRequest.getResourcePath()); } @Test public void toSignableRequestHappyGetWithQuery() throws Exception { final String plainQuery = TEST_SPARQL_QUERY; final String encodedQuery = URLEncoder.encode(plainQuery, StandardCharsets.UTF_8.name()); // prep final StringBuilder uriBuilder = new StringBuilder(); uriBuilder.append(TEST_FULL_URI) .append("?") .append(TEST_QUERY_PARAM_NAME) .append("=") .append(encodedQuery); final String uri = uriBuilder.toString(); final Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put(HEADER_ONE_NAME, HEADER_ONE_VALUE); requestHeaders.put(HEADER_TWO_NAME, HEADER_TWO_VALUE); requestHeaders.put(HOST_HEADER_NAME, TEST_ENDPOINT); final T request = createGetRequest(uri, requestHeaders); // call final SignableRequest signableRequest = signer.toSignableRequest(request); // verify final Map<String, List<String>> headers = signableRequest.getHeaders(); assertEquals("Headers host size should be 2", 2, headers.size()); assertEquals("Non host header should be retained", HEADER_ONE_VALUE, headers.get(HEADER_ONE_NAME)); assertEquals("Non host header should be retained", HEADER_TWO_VALUE, headers.get(HEADER_TWO_NAME)); assertEquals("Unexpected endpoint", URI.create(TEST_ENDPOINT_URI), signableRequest.getEndpoint()); assertEquals("Unexpected resource path", TEST_REQUEST_PATH, signableRequest.getResourcePath()); final Map<String, List<String>> queryParams = signableRequest.getParameters(); assertEquals("Unexpected query param", plainQuery, queryParams.get("query").get(0)); } @Test public void toSignableRequestHappyPost() throws Exception { // prep final String uri = TEST_FULL_URI; final String requestBody = TEST_SPARQL_QUERY; final Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put(HEADER_ONE_NAME, HEADER_ONE_VALUE); requestHeaders.put(HEADER_TWO_NAME, HEADER_TWO_VALUE); requestHeaders.put(HOST_HEADER_NAME, TEST_ENDPOINT); final T request = createPostRequest(uri, requestHeaders, requestBody); // call final SignableRequest signableRequest = signer.toSignableRequest(request); // verify final Map<String, List<String>> headers = signableRequest.getHeaders(); assertEquals("Headers host size should be 2", 2, headers.size()); assertEquals("Non host header should be retained", HEADER_ONE_VALUE, headers.get(HEADER_ONE_NAME)); assertEquals("Non host header should be retained", HEADER_TWO_VALUE, headers.get(HEADER_TWO_NAME)); assertEquals("", requestBody, IOUtils.toString(signableRequest.getContent(), StandardCharsets.UTF_8)); assertEquals("Unexpected endpoint", URI.create(TEST_ENDPOINT_URI), signableRequest.getEndpoint()); assertEquals("Unexpected resource path", TEST_REQUEST_PATH, signableRequest.getResourcePath()); } @Test public void toSignableRequestHappyGetWithTrailingSlash() throws Exception { // prep final String uri = TEST_FULL_URI_WITH_SLASH; final Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put(HEADER_ONE_NAME, HEADER_ONE_VALUE); requestHeaders.put(HEADER_TWO_NAME, HEADER_TWO_VALUE); requestHeaders.put(HOST_HEADER_NAME, TEST_ENDPOINT); final T request = createGetRequest(uri, requestHeaders); // call final SignableRequest signableRequest = signer.toSignableRequest(request); // verify final Map<String, List<String>> headers = signableRequest.getHeaders(); assertEquals("Headers host size should be 2", 2, headers.size()); assertEquals("Non host header should be retained", HEADER_ONE_VALUE, headers.get(HEADER_ONE_NAME)); assertEquals("Non host header should be retained", HEADER_TWO_VALUE, headers.get(HEADER_TWO_NAME)); assertEquals("Unexpected endpoint", URI.create(TEST_ENDPOINT_URI), signableRequest.getEndpoint()); assertEquals("Unexpected resource path", TEST_REQUEST_PATH_WITH_SLASH, signableRequest.getResourcePath()); } @Test(expected = NeptuneSigV4SignerException.class) public void toSignableRequestGetNoHost() throws NeptuneSigV4SignerException { // prep final String uri = TEST_REQUEST_PATH; final Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put(HEADER_ONE_NAME, HEADER_ONE_VALUE); requestHeaders.put(HEADER_TWO_NAME, HEADER_TWO_VALUE); final T request = createGetRequest(uri, requestHeaders); // call signer.toSignableRequest(request); } private void testAttachSignatureHeaders(final String sessionToken) throws Exception { // prep final String uri = TEST_FULL_URI_WITH_SLASH; final Map<String, String> requestHeaders = new HashMap<>(); requestHeaders.put(HEADER_ONE_NAME, HEADER_ONE_VALUE); requestHeaders.put(HEADER_TWO_NAME, HEADER_TWO_VALUE); final T request = createGetRequest(uri, requestHeaders); final String hostname = TEST_HOST_NAME; final String dateHeader = TEST_DATE_HEADER_VALUE; final String authHeader = TEST_AUTHORIZATION_HEADER_VALUE; final NeptuneSigV4SignerBase.NeptuneSigV4Signature signature = new NeptuneSigV4SignerBase.NeptuneSigV4Signature(hostname, dateHeader, authHeader, sessionToken); signer.attachSignature(request, signature); final Map<String, String> attachedHeaders = getRequestHeaders(request); assertEquals(hostname, attachedHeaders.get(SignerConstants.HOST)); assertEquals(dateHeader, attachedHeaders.get(SignerConstants.X_AMZ_DATE)); assertEquals(HEADER_ONE_VALUE, attachedHeaders.get(HEADER_ONE_NAME)); assertEquals(HEADER_TWO_VALUE, attachedHeaders.get(HEADER_TWO_NAME)); assertEquals(authHeader, attachedHeaders.get(SignerConstants.AUTHORIZATION)); } @Test public void attachSignatureHeadersWithSessionToken() throws Exception { final String sessionToken = TEST_SESSION_TOKEN_VALUE; testAttachSignatureHeaders(sessionToken); } @Test public void attachSignatureHeadersWithEmptySessionToken() throws Exception { final String sessionToken = ""; testAttachSignatureHeaders(sessionToken); } }
3,691
0
Create_ds/amazon-neptune-sigv4-signer/src/test/java/com/amazonaws/neptune
Create_ds/amazon-neptune-sigv4-signer/src/test/java/com/amazonaws/neptune/auth/NeptuneApacheHttpSigV4SignerTest.java
/* * Copyright 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://www.apache.org/licenses/LICENSE-2.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.neptune.auth; import com.amazonaws.SignableRequest; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestWrapper; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.StringEntity; import org.junit.Test; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; public class NeptuneApacheHttpSigV4SignerTest extends NeptuneSigV4SignerAbstractTest<HttpUriRequest> { private NeptuneApacheHttpSigV4Signer signer; public NeptuneApacheHttpSigV4SignerTest() throws NeptuneSigV4SignerException { this.signer = new NeptuneApacheHttpSigV4Signer(TEST_REGION, awsCredentialsProvider); } @Test public void toSignableRequestHappyWithWrapper() throws NeptuneSigV4SignerException { // prep final URI uri = URI.create(TEST_REQUEST_PATH); final HttpGet request = new HttpGet(uri); request.setHeader(HEADER_ONE_NAME, HEADER_ONE_VALUE); request.setHeader(HEADER_TWO_NAME, HEADER_TWO_VALUE); request.setHeader(HOST_HEADER_NAME, TEST_ENDPOINT); final HttpHost httpHost = new HttpHost(TEST_HOST_NAME, Integer.valueOf(TEST_PORT), HttpHost.DEFAULT_SCHEME_NAME); final HttpRequestWrapper wrapper = HttpRequestWrapper.wrap(request, httpHost); // call final SignableRequest signableRequest = signer.toSignableRequest(wrapper); // verify Map<String, List<String>> headers = signableRequest.getHeaders(); assertEquals("Headers host size should be 2", 2, headers.size()); assertEquals("Non host header should be retained", HEADER_ONE_VALUE, headers.get(HEADER_ONE_NAME)); assertEquals("Non host header should be retained", HEADER_TWO_VALUE, headers.get(HEADER_TWO_NAME)); assertEquals("Endpoint returned is not as expected", URI.create(TEST_ENDPOINT_URI), signableRequest.getEndpoint()); assertEquals("Resource returned is not as expected", TEST_REQUEST_PATH, signableRequest.getResourcePath()); } @Override public NeptuneApacheHttpSigV4Signer getSigner() { return signer; } @Override protected HttpUriRequest createGetRequest(final String fullURI, final Map<String, String> expectedHeaders) { final HttpUriRequest request = new HttpGet(URI.create(fullURI)); expectedHeaders.entrySet().forEach(entry -> request.setHeader(entry.getKey(), entry.getValue())); return request; } @Override protected HttpUriRequest createPostRequest(final String fullURI, final Map<String, String> expectedHeaders, final String payload) { final HttpPost request = new HttpPost(URI.create(fullURI)); expectedHeaders.entrySet().forEach(entry -> request.setHeader(entry.getKey(), entry.getValue())); request.setEntity(new StringEntity(payload, StandardCharsets.UTF_8)); return request; } @Override protected Map<String, String> getRequestHeaders(final HttpUriRequest request) { return Arrays.stream(request.getAllHeaders()).collect(Collectors.toMap(Header::getName, Header::getValue)); } }
3,692
0
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune/auth/NeptuneApacheHttpSigV4Signer.java
/* * Copyright 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://www.apache.org/licenses/LICENSE-2.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.neptune.auth; import com.amazonaws.SignableRequest; import com.amazonaws.auth.AWSCredentialsProvider; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.client.methods.HttpRequestWrapper; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.StringEntity; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static com.amazonaws.auth.internal.SignerConstants.AUTHORIZATION; import static com.amazonaws.auth.internal.SignerConstants.HOST; import static com.amazonaws.auth.internal.SignerConstants.X_AMZ_DATE; import static com.amazonaws.auth.internal.SignerConstants.X_AMZ_SECURITY_TOKEN; /** * Signer for HTTP requests made via Apache Commons {@link HttpUriRequest}s. * <p> * Note that there are certain limitations for the usage of this class. In particular: * <ul> * <li> The implementation adds a "Host" header. This may lead to problems if the original request has a host header * with a name in different capitalization (e.g. "host"), leading to duplicate host headers and the signing * process to fail. Hence, when using the API you need to make sure that there is either no host header in your * original request or the host header uses the exact string "Host" as the header name.</li> * <li> When using GET, the underlying HTTP request needs to encode whitespaces in query parameters using '%20' * rather than (what most APIs such as the Apache commons {@link org.apache.http.client.utils.URIBuilder} do) * using '+'.</li> * </ul> */ public class NeptuneApacheHttpSigV4Signer extends NeptuneSigV4SignerBase<HttpUriRequest> { /** * Create a V4 Signer for Apache Commons HTTP requests. * * @param regionName name of the region for which the request is signed * @param awsCredentialsProvider the provider offering access to the credentials used for signing the request * @throws NeptuneSigV4SignerException in case initialization fails */ public NeptuneApacheHttpSigV4Signer( final String regionName, final AWSCredentialsProvider awsCredentialsProvider) throws NeptuneSigV4SignerException { super(regionName, awsCredentialsProvider); } @Override protected SignableRequest<?> toSignableRequest(final HttpUriRequest request) throws NeptuneSigV4SignerException { // make sure the request is not null and contains the minimal required set of information checkNotNull(request, "The request must not be null"); checkNotNull(request.getURI(), "The request URI must not be null"); checkNotNull(request.getMethod(), "The request method must not be null"); // convert the headers to the internal API format final Header[] headers = request.getAllHeaders(); final Map<String, String> headersInternal = new HashMap<>(); for (final Header header : headers) { // Skip adding the Host header as the signing process will add one. if (!header.getName().equalsIgnoreCase(HOST)) { headersInternal.put(header.getName(), header.getValue()); } } // convert the parameters to the internal API format final String queryStr = request.getURI().getRawQuery(); final Map<String, List<String>> parametersInternal = extractParametersFromQueryString(queryStr); // carry over the entity (or an empty entity, if no entity is provided) final InputStream content; try { HttpEntity httpEntity = null; if (request instanceof HttpEntityEnclosingRequest) { httpEntity = ((HttpEntityEnclosingRequest) request).getEntity(); } // fallback: if we either have an HttpEntityEnclosingRequest without entity or // say a GET request (which does not carry an entity), set the content // to be an empty StringEntity as per the SigV4 spec if (httpEntity == null) { httpEntity = new StringEntity(""); } content = httpEntity.getContent(); } catch (final UnsupportedEncodingException e) { throw new NeptuneSigV4SignerException("Encoding of the input string failed", e); } catch (final IOException e) { throw new NeptuneSigV4SignerException("IOException while accessing entity content", e); } final URI uri = request.getURI(); // http://example.com:8182 is the endpoint in http://example.com:8182/test/path URI endpoint; // /test/path is the resource path in http://example.com:8182/test/path String resourcePath; if (uri.getHost() != null) { endpoint = URI.create(uri.getScheme() + "://" + uri.getAuthority()); resourcePath = uri.getPath(); } else if (request instanceof HttpRequestWrapper) { final String host = ((HttpRequestWrapper) request).getTarget().toURI(); endpoint = URI.create(host); resourcePath = uri.getPath(); } else { throw new NeptuneSigV4SignerException( "Unable to extract host information from the request uri, required for SigV4 signing: " + uri); } return convertToSignableRequest( request.getMethod(), endpoint, resourcePath, headersInternal, parametersInternal, content); } @Override protected void attachSignature(final HttpUriRequest request, final NeptuneSigV4Signature signature) throws NeptuneSigV4SignerException { // make sure the request is not null and contains the minimal required set of information checkNotNull(signature, "The signature must not be null"); checkNotNull(signature.getHostHeader(), "The signed Host header must not be null"); checkNotNull(signature.getXAmzDateHeader(), "The signed X-AMZ-DATE header must not be null"); checkNotNull(signature.getAuthorizationHeader(), "The signed Authorization header must not be null"); final Header[] headers = request.getAllHeaders(); // Check if host header is present in the request headers. Optional<String> hostHeaderName = Optional.empty(); for (final Header header: headers) { if (header.getName().equalsIgnoreCase(HOST)) { hostHeaderName = Optional.of(header.getName()); } } // Remove the host header from the request as we are going to add the host header from the signed request. // This also ensures that the right header name is used. hostHeaderName.ifPresent(request::removeHeaders); request.setHeader(HOST, signature.getHostHeader()); request.setHeader(X_AMZ_DATE, signature.getXAmzDateHeader()); request.setHeader(AUTHORIZATION, signature.getAuthorizationHeader()); // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html // For temporary security credentials, it requires an additional HTTP header // or query string parameter for the security token. The name of the header // or query string parameter is X-Amz-Security-Token, and the value is the session token. if (!signature.getSessionToken().isEmpty()) { request.setHeader(X_AMZ_SECURITY_TOKEN, signature.getSessionToken()); } } }
3,693
0
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune/auth/NeptuneSigV4Signer.java
/* * Copyright 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://www.apache.org/licenses/LICENSE-2.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.neptune.auth; /** * Interface to hook in Signature V4 signing logics as per * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html. * * T is the type of the request to be signed, which allows us to support * implementation for different HTTP client APIs. * * @param <T> type of the request to be signed * @author schmdtm */ public interface NeptuneSigV4Signer<T> { /** * Sign the given input request using SigV4. * * @param request the request to be signed * @throws NeptuneSigV4SignerException in case something goes wrong */ void signRequest(final T request) throws NeptuneSigV4SignerException; }
3,694
0
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune/auth/RequestMetadata.java
/* * Copyright 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://www.apache.org/licenses/LICENSE-2.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.neptune.auth; import java.util.Map; import java.util.Optional; /** * Encapsulates the various fields in a Http request that are required to perform SigV4 signing. */ public class RequestMetadata { /** * The full uri including the query string. * E.g. http://example.com:8182/sparql?query=queryString */ private final String fullUri; /** * Http request method. "GET", "POST", "PUT" etc. */ private final String method; /** * The payload of the request in bytes. This is usually set only for PUT or POST requests. */ private final Optional<byte[]> content; /** * A map of headers in the request. Key - header name, value - header value. */ private final Map<String, String> headers; /** * A map containing the query parameters as key, value. */ private final Map<String, String> queryParameters; /** * Constructs an instance of Request metadata. * @param fullUri - the full URI. See {@link #fullUri} * @param method - the http request method. See {@link #method} * @param content - the payload of the http request. See {@link #content} * @param headers - the headers in the http request. See {@link #headers} * @param queryParameters - the query parameters. See {@link #headers} */ public RequestMetadata(final String fullUri, final String method, final Optional<byte[]> content, final Map<String, String> headers, final Map<String, String> queryParameters) { this.fullUri = fullUri; this.method = method; this.content = content; this.headers = headers; this.queryParameters = queryParameters; } /** * @return the fillURI set in the request metadata. */ public String getFullUri() { return fullUri; } /** * @return the method set in the request metadata. */ public String getMethod() { return method; } /** * @return content in the request metadata. */ public Optional<byte[]> getContent() { return content; } /** * @return the headers in the request metadata. */ public Map<String, String> getHeaders() { return headers; } /** * @return the query parameters map in the request metadata. */ public Map<String, String> getQueryParameters() { return queryParameters; } }
3,695
0
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune/auth/NeptuneNettyHttpSigV4Signer.java
/* * Copyright 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://www.apache.org/licenses/LICENSE-2.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.neptune.auth; import com.amazonaws.SignableRequest; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.util.StringUtils; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaders; import org.apache.http.entity.StringEntity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static com.amazonaws.auth.internal.SignerConstants.AUTHORIZATION; import static com.amazonaws.auth.internal.SignerConstants.HOST; import static com.amazonaws.auth.internal.SignerConstants.X_AMZ_DATE; import static com.amazonaws.auth.internal.SignerConstants.X_AMZ_SECURITY_TOKEN; /** * Signer for HTTP requests made via Netty clients {@link FullHttpRequest}s. */ public class NeptuneNettyHttpSigV4Signer extends NeptuneSigV4SignerBase<FullHttpRequest> { /** * Create a V4 Signer for Netty HTTP requests. * * @param regionName name of the region for which the request is signed * @param awsCredentialsProvider the provider offering access to the credentials used for signing the request * @throws NeptuneSigV4SignerException in case initialization fails */ public NeptuneNettyHttpSigV4Signer( final String regionName, final AWSCredentialsProvider awsCredentialsProvider) throws NeptuneSigV4SignerException { super(regionName, awsCredentialsProvider); } @Override protected SignableRequest<?> toSignableRequest(final FullHttpRequest request) throws NeptuneSigV4SignerException { // make sure the request is not null and contains the minimal required set of information checkNotNull(request, "The request must not be null"); checkNotNull(request.uri(), "The request URI must not be null"); checkNotNull(request.method(), "The request method must not be null"); // convert the headers to the internal API format final HttpHeaders headers = request.headers(); final Map<String, String> headersInternal = new HashMap<>(); String hostName = ""; // we don't want to add the Host header as the Signer always adds the host header. for (String header : headers.names()) { // Skip adding the Host header as the signing process will add one. if (!header.equalsIgnoreCase(HOST)) { headersInternal.put(header, headers.get(header)); } else { hostName = headers.get(header); } } // convert the parameters to the internal API format final URI uri = URI.create(request.uri()); final String queryStr = uri.getQuery(); final Map<String, List<String>> parametersInternal = new HashMap<>(extractParametersFromQueryString(queryStr)); // carry over the entity (or an empty entity, if no entity is provided) final InputStream content; final ByteBuf contentBuffer = request.content(); boolean hasContent = false; try { if (contentBuffer != null && contentBuffer.isReadable()) { hasContent = true; contentBuffer.retain(); byte[] bytes = new byte[contentBuffer.readableBytes()]; contentBuffer.getBytes(contentBuffer.readerIndex(), bytes); content = new ByteArrayInputStream(bytes); } else { content = new StringEntity("").getContent(); } } catch (UnsupportedEncodingException e) { throw new NeptuneSigV4SignerException("Encoding of the input string failed", e); } catch (IOException e) { throw new NeptuneSigV4SignerException("IOException while accessing entity content", e); } finally { if (hasContent) { contentBuffer.release(); } } if (StringUtils.isNullOrEmpty(hostName)) { // try to extract hostname from the uri since hostname was not provided in the header. final String authority = uri.getAuthority(); if (authority == null) { throw new NeptuneSigV4SignerException("Unable to identify host information," + " either hostname should be provided in the uri or should be passed as a header"); } hostName = authority; } // Gremlin websocket requests don't contain protocol information. Here, http:// doesn't have any consequence // other than letting the signer work with a full valid uri. The protocol is not used anywhere in signing. final URI endpointUri = URI.create("http://" + hostName); return convertToSignableRequest( request.method().name(), endpointUri, uri.getPath(), headersInternal, parametersInternal, content); } @Override protected void attachSignature(final FullHttpRequest request, final NeptuneSigV4Signature signature) throws NeptuneSigV4SignerException { // make sure the request is not null and contains the minimal required set of information checkNotNull(signature, "The signature must not be null"); checkNotNull(signature.getHostHeader(), "The signed Host header must not be null"); checkNotNull(signature.getXAmzDateHeader(), "The signed X-AMZ-DATE header must not be null"); checkNotNull(signature.getAuthorizationHeader(), "The signed Authorization header must not be null"); final HttpHeaders headers = request.headers(); Optional<String> hostHeaderName = Optional.empty(); // Check if host header is present in the request headers. for (String name: headers.names()) { if (name.equalsIgnoreCase(HOST)) { hostHeaderName = Optional.of(name); break; } } // Remove the host header from the request as we are going to add the host header from the signed request. // This also ensures that the right header name is used. hostHeaderName.ifPresent(name -> headers.remove(name)); request.headers().add(HOST, signature.getHostHeader()); request.headers().add(X_AMZ_DATE, signature.getXAmzDateHeader()); request.headers().add(AUTHORIZATION, signature.getAuthorizationHeader()); // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html // For temporary security credentials, it requires an additional HTTP header // or query string parameter for the security token. The name of the header // or query string parameter is X-Amz-Security-Token, and the value is the session token. if (!signature.getSessionToken().isEmpty()) { request.headers().add(X_AMZ_SECURITY_TOKEN, signature.getSessionToken()); } } }
3,696
0
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune/auth/NeptuneSigV4SignerException.java
/* * Copyright 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://www.apache.org/licenses/LICENSE-2.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.neptune.auth; /** * Exception indicating a problem related to the {@link NeptuneSigV4Signer} * implementation or its usage at runtime (e.g., the signing process itself). * * @author schmdtm */ public class NeptuneSigV4SignerException extends Exception { /** * Constructor. * * @param msg message explaining the exception cause in detail */ public NeptuneSigV4SignerException(final String msg) { super(msg); } /** * Constructor. * * @param cause the root cause of the exception */ public NeptuneSigV4SignerException(final Throwable cause) { super(cause); } /** * Constructor. * * @param msg message explaining the exception cause in detail * @param cause the root cause of the exception */ public NeptuneSigV4SignerException(final String msg, final Throwable cause) { super(msg, cause); } }
3,697
0
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune/auth/NeptuneRequestMetadataSigV4Signer.java
/* * Copyright 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://www.apache.org/licenses/LICENSE-2.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.neptune.auth; import com.amazonaws.SignableRequest; import com.amazonaws.auth.AWSCredentialsProvider; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import static com.amazonaws.auth.internal.SignerConstants.AUTHORIZATION; import static com.amazonaws.auth.internal.SignerConstants.HOST; import static com.amazonaws.auth.internal.SignerConstants.X_AMZ_DATE; import static com.amazonaws.auth.internal.SignerConstants.X_AMZ_SECURITY_TOKEN; /** * Signer for HTTP requests encapsulalted in {@link RequestMetadata}s. * <p> * Note that there are certain limitations for the usage of this class. In particular: * <ul> * <li> The implementation adds a "Host" header. This may lead to problems if the original request has a host header * with a name in different capitalization (e.g. "host"), leading to duplicate host headers and the signing process * to fail. Hence, when using the API you need to make sure that there is either no host header in your original * request or the host header uses the exact string "Host" as the header name.</li> * <li> When using GET, the underlying HTTP request needs to encode whitespaces in query parameters using '%20' * rather than (what most APIs such as the Apache commons {@link org.apache.http.client.utils.URIBuilder} do) * using '+'.</li> * </ul> */ public class NeptuneRequestMetadataSigV4Signer extends NeptuneSigV4SignerBase<RequestMetadata> { /** * Create a V4 Signer for {@link RequestMetadata}. * * @param regionName name of the region for which the request is signed * @param awsCredentialsProvider the provider offering access to the credentials used for signing the request * @throws NeptuneSigV4SignerException in case initialization fails */ public NeptuneRequestMetadataSigV4Signer( final String regionName, final AWSCredentialsProvider awsCredentialsProvider) throws NeptuneSigV4SignerException { super(regionName, awsCredentialsProvider); } /** * Converts a {@link RequestMetadata} to a signable metadata by adding signature headers for AWS SigV4 auth. * * @param request the request metadata object. * @return the signed {@link RequestMetadata}. * @throws NeptuneSigV4SignerException if there are issues while attempting to generate the signature. */ @Override protected SignableRequest<?> toSignableRequest(final RequestMetadata request) throws NeptuneSigV4SignerException { // make sure the request is not null and contains the minimal required set of information checkNotNull(request, "The request must not be null"); checkNotNull(request.getFullUri(), "The request URI must not be null"); checkNotNull(request.getMethod(), "The request method must not be null"); final URI fullUri = URI.create(request.getFullUri()); checkNotNull(fullUri.getAuthority(), "Authority must not be null"); checkNotNull(fullUri.getScheme(), "Scheme must not be null"); // convert the headers to the internal API format final Map<String, String> headersInternal = request.getHeaders() .entrySet() .stream() .filter(e -> !e.getKey().equalsIgnoreCase(HOST)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); // convert the parameters to the internal API format final String queryStr = fullUri.getRawQuery(); final Map<String, List<String>> parametersInternal = extractParametersFromQueryString(queryStr); // carry over the entity (or an empty entity, if no entity is provided) final InputStream content; final byte[] bytes; if (request.getContent().isPresent()) { bytes = request.getContent().get(); } else { bytes = "".getBytes(StandardCharsets.UTF_8); } content = new ByteArrayInputStream(bytes); final URI endpointUri = URI.create(fullUri.getScheme() + "://" + fullUri.getAuthority()); final String resourcePath = fullUri.getPath(); return convertToSignableRequest( request.getMethod(), endpointUri, resourcePath, headersInternal, parametersInternal, content); } /** * Takes a {@link RequestMetadata} and updates the headers required for SigV4 auth. These include the host header, * date header and the authorization header obtained from the {@link NeptuneSigV4Signature}. * Removes the host header if already present in the request. * @param request the request metadata. * @param signature the signature information to attach * @throws NeptuneSigV4SignerException if there is an error in performing the update. */ @Override protected void attachSignature(final RequestMetadata request, final NeptuneSigV4Signature signature) throws NeptuneSigV4SignerException { // make sure the request is not null and contains the minimal required set of information checkNotNull(signature, "The signature must not be null"); checkNotNull(signature.getHostHeader(), "The signed Host header must not be null"); checkNotNull(signature.getXAmzDateHeader(), "The signed X-AMZ-DATE header must not be null"); checkNotNull(signature.getAuthorizationHeader(), "The signed Authorization header must not be null"); final Map<String, String> headers = request.getHeaders(); // Check if host header is present in the request headers. Optional<String> hostHeaderName = Optional.empty(); for (String name: headers.keySet()) { if (name.equalsIgnoreCase(HOST)) { hostHeaderName = Optional.of(name); break; } } // Remove the host header from the request as we are going to add the host header from the signed request. // This also ensures that the right header name is used. hostHeaderName.ifPresent(name -> headers.remove(name)); request.getHeaders().put(HOST, signature.getHostHeader()); request.getHeaders().put(X_AMZ_DATE, signature.getXAmzDateHeader()); request.getHeaders().put(AUTHORIZATION, signature.getAuthorizationHeader()); // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html // For temporary security credentials, it requires an additional HTTP header // or query string parameter for the security token. The name of the header // or query string parameter is X-Amz-Security-Token, and the value is the session token. if (!signature.getSessionToken().isEmpty()) { request.getHeaders().put(X_AMZ_SECURITY_TOKEN, signature.getSessionToken()); } } }
3,698
0
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune
Create_ds/amazon-neptune-sigv4-signer/src/main/java/com/amazonaws/neptune/auth/NeptuneSigV4SignerBase.java
/* * Copyright 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://www.apache.org/licenses/LICENSE-2.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.neptune.auth; import com.amazonaws.DefaultRequest; import com.amazonaws.SignableRequest; import com.amazonaws.auth.AWS4Signer; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.http.HttpMethodName; import com.amazonaws.util.SdkHttpUtils; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.amazonaws.auth.internal.SignerConstants.AUTHORIZATION; import static com.amazonaws.auth.internal.SignerConstants.HOST; import static com.amazonaws.auth.internal.SignerConstants.X_AMZ_DATE; /** * Base implementation of {@link NeptuneSigV4Signer} interface. * <p> * This implementation uses the internal AWS SDK signer to sign requests. The constructor * requires the region name for which to sign as well as an {@link AWSCredentialsProvider} * providing access to the credentials used for signing the request. The service name used * within the signing process is hardcoded to be "neptune-db", which is the official name * of the Amazon Neptune service. * <p> * The implementation uses the following approach for signing the request: * <ol> * <li>Convert the input request nto an AWS SDK {@link SignableRequest}.</li> * <li>Sign the {@link SignableRequest} using an AWS SDK {@link AWS4Signer}</li> * <li>\Attach the computed authorization headers to the input request, thus signing it</li> * </ol> * * The signed request can then be sent to an IAM authorized Neptune instance. * * @param <T> type of the request to be signed * @author schmdtm */ public abstract class NeptuneSigV4SignerBase<T> implements NeptuneSigV4Signer<T> { /** * This signer is supposed to be use in combination with Amazon Neptune. */ private static final String NEPTUNE_SERVICE_NAME = "neptune-db"; /** * The AWS credentials provider, providing access to the credentials. * This needs to be provided by the caller when initializing the signer. */ private final AWSCredentialsProvider awsCredentialsProvider; /** * The {@link AWS4Signer} used internally to compute the request signature. */ private final AWS4Signer aws4Signer; /** * Create a {@link NeptuneSigV4Signer} instance for the given region and service name. * * @param regionName name of the region for which the request is signed * @param awsCredentialsProvider the provider offering access to the credentials used for signing the request * @throws NeptuneSigV4SignerException in case initialization fails */ public NeptuneSigV4SignerBase( final String regionName, final AWSCredentialsProvider awsCredentialsProvider) throws NeptuneSigV4SignerException { checkNotNull(regionName, "The region name must not be null"); checkNotNull(awsCredentialsProvider, "The credentials provider must not be null"); this.awsCredentialsProvider = awsCredentialsProvider; // initialize the signer delegate // => note that using the signer with multiple threads is safe as long as we do not // change the configuration; so what we do here is setting the configuration on init // and, forthon, will only call the aws4Signer.sign() method aws4Signer = new AWS4Signer(); aws4Signer.setRegionName(regionName); aws4Signer.setServiceName(NEPTUNE_SERVICE_NAME); } /** * Convert the native request into an AWS SDK {@link SignableRequest} object which * can be used to perform signing. This means that the information from the request relevant * for signing (such as request URI, query string, headers, etc.) need to be extracted from * the native request and mapped to a {@link SignableRequest} object, which is used internally * for the signing process. * <p> * Note that the signable request internally, during the signing process, adds a "Host" header. * This may lead to problems if the original request has a host header with a name in different * capitalization (e.g. "host"), leading to duplicate host headers and the signing process to fail. * Hence, when using the API you need to make sure that there is either no host header in your * original request or the host header uses the exact string "Host" as the header name. The easiest * solution, if you have control over the native HTTP request, is to just leave out the host * header when translating and create one when signing (the host header value will be part of * the struct returned from the signing process). * * @param nativeRequest the native HTTP request * @return the {@link SignableRequest} * @throws NeptuneSigV4SignerException in case something goes wrong during translation */ protected abstract SignableRequest<?> toSignableRequest(final T nativeRequest) throws NeptuneSigV4SignerException; /** * Attach the signature provided in the signature object to the nativeRequest. * More precisely, the signature contains two headers, X-AMZ-DATE and an Authorization * header, which need to be attached to the native HTTP request as HTTP headers or query string depending on the * type of signature requested - header/pre-signed url. * * @param nativeRequest the native HTTP request * @param signature the signature information to attach * @throws NeptuneSigV4SignerException in case something goes wrong during signing of the native request */ protected abstract void attachSignature(final T nativeRequest, final NeptuneSigV4Signature signature) throws NeptuneSigV4SignerException; /** * Main logics to sign the request. The scheme is to convert the request into a * signable request using toSignableRequest, then sign it using the AWS SDK, and * finally attach the signature headers to the original request using attachSignature. * <p> * Note that toSignableRequest and attachSignature are abstract classes in * this base class, they require dedicated implementations depending on the type of * the native HTTP request. * * @param request the request to be signed * @throws NeptuneSigV4SignerException in case something goes wrong during signing */ @Override public void signRequest(final T request) throws NeptuneSigV4SignerException { try { // 1. Convert the Apache Http request into an AWS SDK signable request // => to be implemented in subclass final SignableRequest<?> awsSignableRequest = toSignableRequest(request); // 2. Sign the AWS SDK signable request (which internally adds some HTTP headers) // => generic, using the AWS SDK signer final AWSCredentials credentials = awsCredentialsProvider.getCredentials(); aws4Signer.sign(awsSignableRequest, credentials); // extract session token if temporary credentials are provided String sessionToken = ""; if ((credentials instanceof BasicSessionCredentials)) { sessionToken = ((BasicSessionCredentials) credentials).getSessionToken(); } final NeptuneSigV4Signature signature = new NeptuneSigV4Signature( awsSignableRequest.getHeaders().get(HOST), awsSignableRequest.getHeaders().get(X_AMZ_DATE), awsSignableRequest.getHeaders().get(AUTHORIZATION), sessionToken); // 3. Copy over the Signature V4 headers to the original request // => to be implemented in subclass attachSignature(request, signature); } catch (final Throwable t) { throw new NeptuneSigV4SignerException(t); } } /** * Helper method to create an AWS SDK {@link SignableRequest} based on HTTP information. * None of the information passed in here must be null. Can (yet must not) be used by * implementing classes. * <p> * Also note that the resulting request will not yet be actually signed; this is really * only a helper to convert the relevant information from the original HTTP request into * the AWS SDK's internal format that will be used for computing the signature in a later * step, see the signRequest method for details. * * @param httpMethodName name of the HTTP method (e.g. "GET", "POST", ...) * @param httpEndpointUri URI of the endpoint to which the HTTP request is sent. E.g. http://[host]:port/ * @param resourcePath the resource path of the request. /resource/id is the path in http://[host]:port/resource/id * @param httpHeaders the headers, defined as a mapping from keys (header name) to values (header values) * @param httpParameters the parameters, defined as a mapping from keys (parameter names) to a list of values * @param httpContent the content carried by the HTTP request; use an empty InputStream for GET requests * * @return the resulting AWS SDK signable request * @throws NeptuneSigV4SignerException in case something goes wrong signing the request */ protected SignableRequest<?> convertToSignableRequest( final String httpMethodName, final URI httpEndpointUri, final String resourcePath, final Map<String, String> httpHeaders, final Map<String, List<String>> httpParameters, final InputStream httpContent) throws NeptuneSigV4SignerException { checkNotNull(httpMethodName, "Http method name must not be null"); checkNotNull(httpEndpointUri, "Http endpoint URI must not be null"); checkNotNull(httpHeaders, "Http headers must not be null"); checkNotNull(httpParameters, "Http parameters must not be null"); checkNotNull(httpContent, "Http content name must not be null"); // create the HTTP AWS SDK Signable Request and carry over information final DefaultRequest<?> awsRequest = new DefaultRequest(NEPTUNE_SERVICE_NAME); awsRequest.setHttpMethod(HttpMethodName.fromValue(httpMethodName)); awsRequest.setEndpoint(httpEndpointUri); awsRequest.setResourcePath(resourcePath); awsRequest.setHeaders(httpHeaders); awsRequest.setParameters(httpParameters); awsRequest.setContent(httpContent); return awsRequest; } /** * Extracts the parameters from a query string (such as param1=value1&amp;param2=value2&amp;...). * The same parameter name may occur multiple times (e.g. param1 might actually be the * same string value as param2). The result is represented as a map from unique key * names to a list of their values. The query string may be null, in which case an * empty map is returned. * * @param queryStr the query string from which parameters are extracted * @return a hash map, mapping parameters by name to a list of values */ protected Map<String, List<String>> extractParametersFromQueryString(final String queryStr) { final Map<String, List<String>> parameters = new HashMap<>(); // convert the parameters to the internal API format if (queryStr != null) { for (final String queryParam : queryStr.split("&")) { if (!queryParam.isEmpty()) { final String[] keyValuePair = queryParam.split("=", 2); // parameters are encoded in the HTTP request, we need to decode them here final String key = SdkHttpUtils.urlDecode(keyValuePair[0]); final String value; if (keyValuePair.length == 2) { value = SdkHttpUtils.urlDecode(keyValuePair[1]); } else { value = ""; } // insert the parameter key into the map, if not yet present if (!parameters.containsKey(key)) { parameters.put(key, new ArrayList<>()); } // append the parameter value to the list for the given key parameters.get(key).add(value); } } } return parameters; } /** * Tiny helper function to assert that the object is not null. In case it is null, * a {@link NeptuneSigV4SignerException} is thrown, with the specified error message. * * @param obj the object to be checked for null * @param errMsg the error message to be propagated in case the check fails * * @throws NeptuneSigV4SignerException if the check fails */ protected void checkNotNull(final Object obj, final String errMsg) throws NeptuneSigV4SignerException { if (obj == null) { throw new NeptuneSigV4SignerException(errMsg); } } /** * Simple struct encapsulating pre-computed Signature V4 signing information. */ public static class NeptuneSigV4Signature { /** * Value of the Host header to be used to sign the request. */ private final String hostHeader; /** * Value of the X-AMZ-DATE header to be used to sign the request. */ private final String xAmzDateHeader; /** * Value of the Authorization header to be used to sign the request. */ private final String authorizationHeader; /** * Value of the Temporary credential session token. */ private final String sessionToken; /** * Constructor. * * @param hostHeader the host header value used when signing the request * @param xAmzDateHeader string value of the xAmzDateHeader used for signing the request * @param authorizationHeader string value of the authorization header used for signing the request */ public NeptuneSigV4Signature( final String hostHeader, final String xAmzDateHeader, final String authorizationHeader, final String sessionToken) { this.hostHeader = hostHeader; this.xAmzDateHeader = xAmzDateHeader; this.authorizationHeader = authorizationHeader; this.sessionToken = sessionToken; } /** * @return the Host header value */ public String getHostHeader() { return hostHeader; } /** * @return the X-AMZ-DATE header value */ public String getXAmzDateHeader() { return xAmzDateHeader; } /** * @return the Authorization header value */ public String getAuthorizationHeader() { return authorizationHeader; } /** * @return the Session Token value */ public String getSessionToken() { return sessionToken; } } }
3,699