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/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/common/SampleConstants.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.examples.common;
public class SampleConstants {
public static final String HOME_DIRECTORY_PROPERTY = "user.home";
public static final String HOME_DIRECTORY_FILENAME = ".swf-flow-samples.properties";
public static final String ACCESS_PROPERTIES_FILENAME = "access.properties";
public static final String ACCESS_PROPERTIES_RELATIVE_PATH = "../../../common";
public static final String ACCESS_PROPERTIES_ENVIRONMENT_VARIABLE = "AWS_SWF_SAMPLES_CONFIG";
}
| 3,400 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/common/WorkflowExecutionGetState.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.examples.common;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClientExternal;
import com.amazonaws.services.simpleworkflow.flow.worker.GenericWorkflowClientExternalImpl;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
/**
* Simple example utility to pretty print workflow execution history.
*
* @author fateev
*/
public class WorkflowExecutionGetState {
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.err.println("Usage: java " + WorkflowExecutionGetState.class.getName() + " <workflowId> <runId>");
System.exit(1);
}
ConfigHelper configHelper = ConfigHelper.createConfig();
AmazonSimpleWorkflow swfService = configHelper.createSWFClient();
String domain = configHelper.getDomain();
WorkflowExecution workflowExecution = new WorkflowExecution();
String workflowId = args[1];
workflowExecution.setWorkflowId(workflowId);
String runId = args[2];
workflowExecution.setRunId(runId);
GenericWorkflowClientExternal client = new GenericWorkflowClientExternalImpl(swfService, domain);
String state = client.getWorkflowState(workflowExecution);
System.out.println("Current state of " + workflowExecution + ":");
System.out.println(state);
}
}
| 3,401 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/common/ConfigHelper.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.examples.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflowClient;
/**
* Configuration Helper to used to create SWF and S3 clients
*/
public class ConfigHelper {
private Properties sampleConfig;
private String swfServiceUrl;
private String swfAccessId;
private String swfSecretKey;
private String s3AccessId;
private String s3SecretKey;
private String swfLambdaRoleArn;
private String swfLambdaFunction;
private String swfLambdaFunctionInput;
private String domain;
private long domainRetentionPeriodInDays;
private ConfigHelper(File propertiesFile) throws IOException {
loadProperties(propertiesFile);
}
private void loadProperties(File propertiesFile) throws IOException {
FileInputStream inputStream = new FileInputStream(propertiesFile);
sampleConfig = new Properties();
sampleConfig.load(inputStream);
this.swfServiceUrl = sampleConfig.getProperty(ConfigKeys.SWF_SERVICE_URL_KEY);
this.swfAccessId = sampleConfig.getProperty(ConfigKeys.SWF_ACCESS_ID_KEY);
this.swfSecretKey = sampleConfig.getProperty(ConfigKeys.SWF_SECRET_KEY_KEY);
this.s3AccessId = sampleConfig.getProperty(ConfigKeys.S3_ACCESS_ID_KEY);
this.s3SecretKey = sampleConfig.getProperty(ConfigKeys.S3_SECRET_KEY_KEY);
this.swfLambdaRoleArn = sampleConfig.getProperty(ConfigKeys.SWF_LAMBDA_ROLE_ARN);
this.swfLambdaFunction = sampleConfig.getProperty(ConfigKeys.SWF_LAMBDA_FUNCTION);
this.swfLambdaFunctionInput = sampleConfig.getProperty(ConfigKeys.SWF_LAMBDA_FUNCTION_INPUT);
this.domain = sampleConfig.getProperty(ConfigKeys.DOMAIN_KEY);
this.domainRetentionPeriodInDays = Long.parseLong(sampleConfig.getProperty(ConfigKeys.DOMAIN_RETENTION_PERIOD_KEY));
}
public static ConfigHelper createConfig() throws IOException, IllegalArgumentException {
BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.ERROR);
// Logger.getLogger("org.apache.http").setLevel(Level.INFO);
ConfigHelper configHelper = null;
boolean envVariableExists = false;
//first check the existence of environment variable
String sampleConfigPath = System.getenv(SampleConstants.ACCESS_PROPERTIES_ENVIRONMENT_VARIABLE);
if (sampleConfigPath != null && sampleConfigPath.length() > 0) {
envVariableExists = true;
}
File accessProperties = new File(System.getProperty(SampleConstants.HOME_DIRECTORY_PROPERTY), SampleConstants.HOME_DIRECTORY_FILENAME);
if(accessProperties.exists()){
configHelper = new ConfigHelper(accessProperties);
}
else if (envVariableExists) {
accessProperties = new File(sampleConfigPath, SampleConstants.ACCESS_PROPERTIES_FILENAME);
configHelper = new ConfigHelper(accessProperties);
}
else {
//try checking the existence of file on relative path.
try {
accessProperties = new File(SampleConstants.ACCESS_PROPERTIES_RELATIVE_PATH, SampleConstants.ACCESS_PROPERTIES_FILENAME);
configHelper = new ConfigHelper(accessProperties);
}
catch (Exception e) {
throw new FileNotFoundException("Cannot find AWS_SWF_SAMPLES_CONFIG environment variable, Exiting!!!");
}
}
return configHelper;
}
public AmazonSimpleWorkflow createSWFClient() {
AWSCredentials awsCredentials = new BasicAWSCredentials(this.swfAccessId, this.swfSecretKey);
AmazonSimpleWorkflow client = new AmazonSimpleWorkflowClient(awsCredentials);
client.setEndpoint(this.swfServiceUrl);
return client;
}
public AmazonS3 createS3Client() {
AWSCredentials s3AWSCredentials = new BasicAWSCredentials(this.s3AccessId, this.s3SecretKey);
AmazonS3 client = new AmazonS3Client(s3AWSCredentials);
return client;
}
public String getDomain() {
return domain;
}
public long getDomainRetentionPeriodInDays() {
return domainRetentionPeriodInDays;
}
public String getValueFromConfig(String key) {
return sampleConfig.getProperty(key);
}
public String getSwfLambdaRoleArn() {
return swfLambdaRoleArn;
}
public String getSwfLambdaFunction() {
return swfLambdaFunction;
}
public String getSwfLambdaFunctionInput() {
return swfLambdaFunctionInput;
}
}
| 3,402 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/hellolambda/HelloLambdaWorkflowImpl.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.examples.hellolambda;
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.examples.common.ConfigHelper;
import com.amazonaws.services.simpleworkflow.flow.worker.LambdaFunctionClient;
/**
* Implementation of the hello lambda workflow
*/
public class HelloLambdaWorkflowImpl implements HelloLambdaWorkflow{
@Override
public void helloWorld(String name) throws Exception {
ConfigHelper configHelper = ConfigHelper.createConfig();
DecisionContextProvider decisionProvider = new DecisionContextProviderImpl();
DecisionContext decisionContext = decisionProvider.getDecisionContext();
LambdaFunctionClient lambdaClient = decisionContext.getLambdaFunctionClient();
lambdaClient.scheduleLambdaFunction(configHelper.getSwfLambdaFunction(), configHelper.getSwfLambdaFunctionInput());
}
}
| 3,403 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/hellolambda/HelloLambdaWorkflow.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.examples.hellolambda;
import com.amazonaws.services.simpleworkflow.flow.annotations.Execute;
import com.amazonaws.services.simpleworkflow.flow.annotations.Workflow;
import com.amazonaws.services.simpleworkflow.flow.annotations.WorkflowRegistrationOptions;
/**
* Contract of the hello lambda workflow
*/
@Workflow
// replace with the ARN of an IAM role that allows SWF to invoke your lambda functions to use it by default
// when calling lambda functions in this workflow
@WorkflowRegistrationOptions(defaultExecutionStartToCloseTimeoutSeconds = 60)
public interface HelloLambdaWorkflow {
@Execute(version = "1.0")
void helloWorld(String name) throws Exception;
}
| 3,404 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/hellolambda/WorkflowExecutionStarter.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.examples.hellolambda;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.StartWorkflowOptions;
import com.amazonaws.services.simpleworkflow.flow.examples.common.ConfigHelper;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
public class WorkflowExecutionStarter {
public static void main(String[] args) throws Exception {
ConfigHelper configHelper = ConfigHelper.createConfig();
AmazonSimpleWorkflow swfService = configHelper.createSWFClient();
String domain = configHelper.getDomain();
String defaultLambdaRoleArn = configHelper.getSwfLambdaRoleArn();
HelloLambdaWorkflowClientExternalFactory clientFactory = new HelloLambdaWorkflowClientExternalFactoryImpl(swfService,
domain);
HelloLambdaWorkflowClientExternal workflow = clientFactory.getClient();
// give the ARN of an IAM role that allows SWF to invoke lambda functions on your behalf
StartWorkflowOptions options = new StartWorkflowOptions().withLambdaRole(defaultLambdaRoleArn);
// Start Workflow Execution
workflow.helloWorld("User", options);
// WorkflowExecution is available after workflow creation
WorkflowExecution workflowExecution = workflow.getWorkflowExecution();
System.out.println("Started helloLambda workflow with workflowId=\"" + workflowExecution.getWorkflowId()
+ "\" and runId=\"" + workflowExecution.getRunId() + "\"");
}
}
| 3,405 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/hellolambda/WorkflowHost.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.examples.hellolambda;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.WorkflowWorker;
import com.amazonaws.services.simpleworkflow.flow.examples.common.ConfigHelper;
public class WorkflowHost {
private static final String DECISION_TASK_LIST = "HelloLambdaWorkflow";
public static void main(String[] args) throws Exception {
ConfigHelper configHelper = ConfigHelper.createConfig();
AmazonSimpleWorkflow swfService = configHelper.createSWFClient();
String domain = configHelper.getDomain();
final WorkflowWorker worker = new WorkflowWorker(swfService, domain, DECISION_TASK_LIST);
worker.addWorkflowImplementationType(HelloLambdaWorkflowImpl.class);
worker.start();
System.out.println("Workflow Host Service Started...");
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
worker.shutdownAndAwaitTermination(1, TimeUnit.MINUTES);
System.out.println("Workflow Host Service Terminated...");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("Please press any key to terminate service.");
try {
System.in.read();
}
catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
}
| 3,406 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/DeploymentInitiator.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.examples.deployment;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DeploymentInitiator {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
URL pUrl = DeploymentHost.class.getResource("/com/amazonaws/services/simpleworkflow/flow/examples/log4j.properties");
PropertyConfigurator.configure(pUrl);
ApplicationContext appContext = new ClassPathXmlApplicationContext(
"/com/amazonaws/services/simpleworkflow/flow/examples/deployment/DeploymentInitiator-context.xml");
DeploymentWorkflowClientExternalFactory workflowFactory = appContext.getBean("workflowFactory",
DeploymentWorkflowClientExternalFactory.class);
String applicationStackConfigFile = args[0];
// Use applicationStackConfig as workflowId to prohibit running multiple deployments of the same stack in parallel
String workflowId = new File(applicationStackConfigFile).getName();
DeploymentWorkflowClientExternal worklfowClient = workflowFactory.getClient(workflowId);
String template = loadFile(applicationStackConfigFile);
worklfowClient.deploy(template);
System.out.println("Initiated deployment from " + applicationStackConfigFile);
}
public static String loadFile(String fileName) throws IOException {
int length = (int) new File(fileName).length();
byte[] buffer = new byte[length];
BufferedInputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(fileName));
is.read(buffer);
}
finally {
if (is != null) {
is.close();
}
}
return new String(buffer);
}
}
| 3,407 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/DeployableBase.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.examples.deployment;
import java.util.ArrayList;
import java.util.List;
import com.amazonaws.services.simpleworkflow.flow.annotations.Asynchronous;
import com.amazonaws.services.simpleworkflow.flow.annotations.Wait;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
import com.amazonaws.services.simpleworkflow.flow.core.Settable;
public abstract class DeployableBase implements Deployable {
private String host;
List<Deployable> dependsOn = new ArrayList<Deployable>();
@Override
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
protected void addDependsOn(List<? extends Deployable> deployable) {
dependsOn.addAll(deployable);
}
private Settable<String> url = new Settable<String>();
@Override
public void deploy() {
List<Promise<?>> dependsOnPromises = new ArrayList<Promise<?>>();
for (Deployable deployable : dependsOn) {
dependsOnPromises.add(deployable.getUrl());
}
deploy(dependsOnPromises);
}
@Asynchronous
private void deploy(@Wait List<Promise<?>> dependsOnPromises) {
// chain links one promise to the result of the other one
url.chain(deploySelf());
}
@Override
public Promise<String> getUrl() {
return url;
}
/**
* Perform actual deployment.
* @return Url used to access this Deployable
*/
protected abstract Promise<String> deploySelf();
}
| 3,408 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/DeploymentWorkflowImpl.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.examples.deployment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
public class DeploymentWorkflowImpl implements DeploymentWorkflow {
@Autowired
private ApplicationContext applicationContext;
@Override
public Promise<String> deploy(String springTemplate) {
Resource templateResource = new ByteArrayResource(springTemplate.getBytes());
GenericXmlApplicationContext appContext = new GenericXmlApplicationContext();
appContext.setParent(applicationContext);
appContext.load(templateResource);
appContext.refresh();
ApplicationStack applicationStack = appContext.getBean("applicationStack", ApplicationStack.class);
applicationStack.deploy();
return applicationStack.getUrl();
}
}
| 3,409 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/LoadBalancer.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.examples.deployment;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import com.amazonaws.services.simpleworkflow.flow.ActivitySchedulingOptions;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
public class LoadBalancer extends DeployableBase {
private List<WebServer> webServers;
@Autowired
private DeploymentActivitiesClient activities;
public List<WebServer> getWebServers() {
return webServers;
}
public void setWebServers(List<WebServer> webServers) {
this.webServers = webServers;
}
@PostConstruct
public void init() {
addDependsOn(webServers);
}
@Override
protected Promise<String> deploySelf() {
List<String> urls = new ArrayList<String>();
for (WebServer webServer : webServers) {
// It is safe to call Promise.get() here as deploySelf is called after
// all components WebServer depends on are already deployed
urls.add(webServer.getUrl().get());
}
// Use host name as taskList to route request to appropriate host
ActivitySchedulingOptions options = new ActivitySchedulingOptions();
options.setTaskList(getHost());
return activities.deployLoadBalancer(urls, options);
}
}
| 3,410 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/Database.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.examples.deployment;
import org.springframework.beans.factory.annotation.Autowired;
import com.amazonaws.services.simpleworkflow.flow.ActivitySchedulingOptions;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
public class Database extends DeployableBase {
@Autowired
private DeploymentActivitiesClient activities;
@Override
protected Promise<String> deploySelf() {
// Use host name as taskList to route request to appropriate host
ActivitySchedulingOptions options = new ActivitySchedulingOptions();
options.setTaskList(getHost());
return activities.deployDatabase(options);
}
}
| 3,411 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/DeploymentActivities.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.examples.deployment;
import java.util.List;
import com.amazonaws.services.simpleworkflow.flow.annotations.Activities;
import com.amazonaws.services.simpleworkflow.flow.annotations.ActivityRegistrationOptions;
import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants;
@Activities(version = "1.0")
// NO_DEFAULT_TASK_LIST mandates that task list is specified when activity is called
@ActivityRegistrationOptions(defaultTaskList = FlowConstants.NO_DEFAULT_TASK_LIST,
defaultTaskScheduleToStartTimeoutSeconds = 300, defaultTaskStartToCloseTimeoutSeconds = 300)
public interface DeploymentActivities {
/**
* @return dataSource
*/
public String deployDatabase();
/**
* @param dataSources
* used to access database
* @return URL used to access appserver
*/
public String deployAppServer(List<String> dataSources);
/**
* @param dataSource
* dataSources used to access database
* @param appServerUrls
* URLs used to access appservers
* @return URL used to access webserver
*/
public String deployWebServer(List<String> appServerUrls, List<String> dataSources);
/**
* @param frontendUrls URLs used to acccess frontends
* @return URL for the load balancer
*/
public String deployLoadBalancer(List<String> frontendUrls);
}
| 3,412 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/Deployable.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.examples.deployment;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
public interface Deployable {
/**
* @return Destination host.
*/
public String getHost();
/**
* Initiate deployment. Actual deployment is expected to happen after all
* dependencies of the current Deployable are deployed.
*/
public void deploy();
/**
* Url used to access deployed component
* @return promise the Url which becomes ready after successful deployment.
*/
public Promise<String> getUrl();
}
| 3,413 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/DeploymentActivitiesImpl.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.examples.deployment;
import java.util.List;
public class DeploymentActivitiesImpl implements DeploymentActivities {
@Override
public String deployDatabase() {
return "jdbc:foo/bar";
}
@Override
public String deployAppServer(List<String> dataSources) {
return "http://baz";
}
@Override
public String deployWebServer(List<String> appServerUrls, List<String> dataSources) {
return "http://webserver";
}
@Override
public String deployLoadBalancer(List<String> frontendUrls) {
return "http://myweb.com";
}
}
| 3,414 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/DeploymentHost.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.examples.deployment;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DeploymentHost {
/**
* @param args
* @throws MalformedURLException
*/
public static void main(String[] args) {
new ClassPathXmlApplicationContext(
"/com/amazonaws/services/simpleworkflow/flow/examples/deployment/DeploymentHost-context.xml");
}
}
| 3,415 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/AppServer.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.examples.deployment;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import com.amazonaws.services.simpleworkflow.flow.ActivitySchedulingOptions;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
public class AppServer extends DeployableBase {
private List<Database> databases;
@Autowired
private DeploymentActivitiesClient activities;
public List<Database> getDatabases() {
return databases;
}
public void setDatabases(List<Database> databases) {
this.databases = databases;
}
@PostConstruct
public void init() {
addDependsOn(databases);
}
@Override
protected Promise<String> deploySelf() {
List<String> dataSources = new ArrayList<String>();
for (Database db : databases) {
// It is safe to call Promise.get() here as deploySelf is called after
// all Databases AppServer depends on are already deployed
dataSources.add(db.getUrl().get());
}
// Use host name as taskList to route request to appropriate host
ActivitySchedulingOptions options = new ActivitySchedulingOptions();
options.setTaskList(getHost());
return activities.deployAppServer(dataSources, options);
}
}
| 3,416 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/ApplicationStack.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.examples.deployment;
import java.util.List;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
public class ApplicationStack {
private List<Deployable> components;
private Deployable frontendComponent;
public List<Deployable> getComponents() {
return components;
}
public void setComponents(List<Deployable> components) {
this.components = components;
}
public Deployable getFrontendComponent() {
return frontendComponent;
}
public void setFrontendComponent(Deployable frontendComponent) {
this.frontendComponent = frontendComponent;
}
public void deploy() {
// Note that order in which components are iterated doesn't matter.
// The component.deploy() initiates deployment but actual component deployment
// happens only when all downstream dependencies are satisfied.
for (Deployable component : components) {
component.deploy();
}
}
public Promise<String> getUrl() {
return frontendComponent.getUrl();
}
}
| 3,417 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/DeploymentTest.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.examples.deployment;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import junit.framework.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally;
import com.amazonaws.services.simpleworkflow.flow.junit.WorkflowTestBase;
import com.amazonaws.services.simpleworkflow.flow.junit.spring.FlowSpringJUnit4ClassRunner;
@RunWith(FlowSpringJUnit4ClassRunner.class)
@ContextConfiguration("DeploymentTest-context.xml")
public class DeploymentTest {
public static class TestDeploymentActivities implements DeploymentActivities {
private final String host;
public TestDeploymentActivities(String host) {
this.host = host;
}
@Override
public String deployDatabase() {
trace.add("Database-" + host);
return "dbUrl-" + host;
}
@Override
public String deployAppServer(List<String> dataSources) {
trace.add("appServer-" + host);
return "appServerUrl-" + host;
}
@Override
public String deployWebServer(List<String> appServerUrls, List<String> dataSources) {
trace.add("WebServer-" + host);
return "webServerUrl-" + host;
}
@Override
public String deployLoadBalancer(List<String> frontendUrls) {
trace.add("LoadBalancer-" + host);
return "loadBalancerUrl-" + host;
}
}
@Rule
@Autowired
public WorkflowTestBase workflowTest;
@Autowired
public DeploymentWorkflowClientFactory workflowClientFactory;
private static final List<String> trace = new ArrayList<String>();
@Test
public void test() throws IOException {
new TryCatchFinally() {
Throwable failure;
@Override
protected void doTry() throws Throwable {
String template = getTemplate("AppStack1.xml");
DeploymentWorkflowClient workflow = workflowClientFactory.getClient("AppStack1");
workflow.deploy(template);
}
@Override
protected void doCatch(Throwable e) throws Throwable {
failure = e;
throw e;
}
@Override
protected void doFinally() throws Throwable {
// Without this check assertEquals fails overwriting
// original exception
if (failure == null) {
List<String> expected = new ArrayList<String>();
expected.add("Database-host1");
expected.add("Database-host2");
expected.add("appServer-host3");
expected.add("appServer-host2");
expected.add("appServer-host3");
expected.add("WebServer-host2");
expected.add("WebServer-host1");
expected.add("LoadBalancer-host2");
Assert.assertEquals(expected, trace);
}
}
};
}
private String getTemplate(String resourceName) throws IOException {
URL resource = DeploymentTest.class.getResource(resourceName);
String template = new Scanner(resource.openStream()).useDelimiter("\\A").next();
return template;
}
}
| 3,418 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/WebServer.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.examples.deployment;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import com.amazonaws.services.simpleworkflow.flow.ActivitySchedulingOptions;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
/**
* For the sake of the example WebServer depends on both AppServers and Databases.
*
* @author fateev
*/
public class WebServer extends DeployableBase {
private List<Database> databases;
private List<AppServer> appServers;
@Autowired
private DeploymentActivitiesClient activities;
public List<Database> getDatabases() {
return databases;
}
public void setDatabases(List<Database> databases) {
this.databases = databases;
}
public List<AppServer> getAppServers() {
return appServers;
}
public void setAppServers(List<AppServer> appServers) {
this.appServers = appServers;
}
@PostConstruct
public void init() {
addDependsOn(databases);
addDependsOn(appServers);
}
@Override
protected Promise<String> deploySelf() {
List<String> dataSources = new ArrayList<String>();
for (Database db : databases) {
// It is safe to call Promise.get() here as deploySelf is called after
// all components WebServer depends on are already deployed
dataSources.add(db.getUrl().get());
}
List<String> appServerUrls = new ArrayList<String>();
for (AppServer appServer : appServers) {
// It is safe to call Promise.get() here as deploySelf is called after
// all components WebServer depends on are already deployed
appServerUrls.add(appServer.getUrl().get());
}
// Use host name as taskList to route request to appropriate host
ActivitySchedulingOptions options = new ActivitySchedulingOptions();
options.setTaskList(getHost());
return activities.deployWebServer(appServerUrls, dataSources, options);
}
}
| 3,419 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/deployment/DeploymentWorkflow.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.examples.deployment;
import com.amazonaws.services.simpleworkflow.flow.annotations.Execute;
import com.amazonaws.services.simpleworkflow.flow.annotations.Workflow;
import com.amazonaws.services.simpleworkflow.flow.annotations.WorkflowRegistrationOptions;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
@Workflow
@WorkflowRegistrationOptions(defaultExecutionStartToCloseTimeoutSeconds = 3600)
public interface DeploymentWorkflow {
/**
* deploy the whole stack
* @return Url of the stack webserver
*/
@Execute(version="1.0")
public Promise<String> deploy(String springTemplate);
}
| 3,420 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cronwithretry/CronWithRetryWorkflowImpl.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.examples.cronwithretry;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import com.amazonaws.services.simpleworkflow.flow.DecisionContextProviderImpl;
import com.amazonaws.services.simpleworkflow.flow.DynamicActivitiesClient;
import com.amazonaws.services.simpleworkflow.flow.DynamicActivitiesClientImpl;
import com.amazonaws.services.simpleworkflow.flow.WorkflowClock;
import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally;
import com.amazonaws.services.simpleworkflow.flow.interceptors.AsyncRetryingExecutor;
import com.amazonaws.services.simpleworkflow.flow.interceptors.AsyncRunnable;
import com.amazonaws.services.simpleworkflow.flow.interceptors.AsyncScheduledExecutor;
import com.amazonaws.services.simpleworkflow.flow.interceptors.ExponentialRetryPolicy;
import com.amazonaws.services.simpleworkflow.flow.spring.CronInvocationSchedule;
/**
* Demonstrates how to create workflow that executes an activity on schedule
* specified as a "cron" string. Activity name and version are passed as input
* arguments of the workflow. In case of activity failures it is retried
* according to retry options passed as arguments of the workflow.
*
* @author fateev
*/
public class CronWithRetryWorkflowImpl implements CronWithRetryWorkflow {
private static final int SECOND = 1000;
/**
* This is needed to keep the decider logic deterministic as using
* System.currentTimeMillis() in your decider logic is not.
* WorkflowClock.currentTimeMillis() should be used instead.
*/
private final WorkflowClock clock;
private final DynamicActivitiesClient activities;
/**
* Used to create new run of the Cron workflow to reset history. This allows
* "infinite" workflows.
*/
private final CronWithRetryWorkflowSelfClient selfClient;
private final StringBuilder invocationHistory = new StringBuilder();
private TimeZone tz;
public CronWithRetryWorkflowImpl() {
this(new DecisionContextProviderImpl().getDecisionContext().getWorkflowClock(), new DynamicActivitiesClientImpl(),
new CronWithRetryWorkflowSelfClientImpl());
}
/**
* Constructor used for unit testing or configuration through IOC container
*/
public CronWithRetryWorkflowImpl(WorkflowClock clock, DynamicActivitiesClient activities,
CronWithRetryWorkflowSelfClient selfClient) {
this.clock = clock;
this.activities = activities;
this.selfClient = selfClient;
}
@Override
public void startCron(final CronWithRetryWorkflowOptions options) {
Date expiration = new Date(clock.currentTimeMillis() + options.getContinueAsNewAfterSeconds() * SECOND);
tz = TimeZone.getTimeZone(options.getTimeZone());
// Activities client could be decorated directly using CronDecorator and RetryDecorator.
// But executors are used instead to enable updates to invocationHistory.
CronInvocationSchedule cronSchedule = new CronInvocationSchedule(options.getCronExpression(), expiration, tz);
AsyncScheduledExecutor scheduledExecutor = new AsyncScheduledExecutor(cronSchedule, clock);
ExponentialRetryPolicy retryPolicy = createRetryPolicyFromOptions(options);
final AsyncRetryingExecutor retryExecutor = new AsyncRetryingExecutor(retryPolicy, clock);
scheduledExecutor.execute(new AsyncRunnable() {
@Override
public void run() throws Throwable {
retryExecutor.execute(new AsyncRunnable() {
@Override
public void run() throws Throwable {
executeActivityUpdatingInvocationHistory(options);
}
});
}
});
// Start new workflow run as soon as cron decorator exits due to expiration.
// The call to self client indicates the desire to start the new run.
// It is started only after all other tasks in the given run are completed.
selfClient.startCron(options);
}
@Override
public String getInvocationHistory() {
return invocationHistory.toString();
}
private void appendToInvocationHistory(String entry) {
if (invocationHistory.length() > 0) {
invocationHistory.append('\n');
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(tz);
invocationHistory.append(dateFormat.format(new Date(clock.currentTimeMillis())));
invocationHistory.append(" ");
invocationHistory.append(entry);
}
private void executeActivityUpdatingInvocationHistory(final CronWithRetryWorkflowOptions options) {
new TryCatchFinally() {
boolean failed;
@Override
protected void doTry() throws Throwable {
appendToInvocationHistory("starting");
activities.scheduleActivity(options.getActivity(), options.getActivityArguments(), null, Void.class);
}
@Override
protected void doCatch(Throwable e) throws Throwable {
failed = true;
appendToInvocationHistory("failure:" + e.getMessage());
throw e;
}
@Override
protected void doFinally() throws Throwable {
if (!failed) {
appendToInvocationHistory("completed");
}
}
};
}
@SuppressWarnings("unchecked")
private ExponentialRetryPolicy createRetryPolicyFromOptions(CronWithRetryWorkflowOptions options) {
ExponentialRetryPolicy retryPolicy = new ExponentialRetryPolicy(options.getInitialRetryIntervalSeconds());
retryPolicy.setBackoffCoefficient(options.getBackoffCoefficient());
try {
List<String> exceptionsToRetryClasses = options.getExceptionsToRetry();
if (exceptionsToRetryClasses != null) {
List<Class<? extends Throwable>> exceptionsToRetry = new ArrayList<Class<? extends Throwable>>();
for (String exceptionType : exceptionsToRetryClasses) {
exceptionsToRetry.add((Class<? extends Throwable>) Class.forName(exceptionType));
}
retryPolicy.setExceptionsToRetry(exceptionsToRetry);
}
List<String> exceptionsToExcludeClasses = options.getExceptionsToExclude();
if (exceptionsToExcludeClasses != null) {
List<Class<? extends Throwable>> exceptionsToExclude = new ArrayList<Class<? extends Throwable>>();
for (String exceptionType : exceptionsToExcludeClasses) {
exceptionsToExclude.add((Class<? extends Throwable>) Class.forName(exceptionType));
}
retryPolicy.setExceptionsToExclude(exceptionsToExclude);
}
}
catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Invalid options: " + options, e);
}
retryPolicy.setMaximumAttempts(options.getMaximumAttempts());
retryPolicy.setMaximumRetryIntervalSeconds(options.getMaximumRetryIntervalSeconds());
retryPolicy.setRetryExpirationIntervalSeconds(options.getRetryExpirationIntervalSeconds());
return retryPolicy;
}
}
| 3,421 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cronwithretry/CronWithRetryWorkflowTest.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.examples.cronwithretry;
import java.util.concurrent.CancellationException;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContext;
import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContextProvider;
import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContextProviderImpl;
import com.amazonaws.services.simpleworkflow.flow.WorkflowClock;
import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally;
import com.amazonaws.services.simpleworkflow.flow.junit.FlowBlockJUnit4ClassRunner;
import com.amazonaws.services.simpleworkflow.flow.junit.WorkflowTest;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
@RunWith(FlowBlockJUnit4ClassRunner.class)
public class CronWithRetryWorkflowTest {
private final class TestCronWithRetryWorkflowActivities implements CronWithRetryExampleActivities {
private final ActivityExecutionContextProvider contextProvider = new ActivityExecutionContextProviderImpl();
private int workCount;
private int runCount;
private String runId;
@Override
public void doSomeWork(String parameter) {
// Reset counter on the new run which changes when workflow continues as new
ActivityExecutionContext activityExecutionContext = contextProvider.getActivityExecutionContext();
WorkflowExecution workflowExecution = activityExecutionContext.getWorkflowExecution();
String runId = workflowExecution.getRunId();
if (this.runId == null || !runId.equals(this.runId)) {
runCount++;
}
this.runId = runId;
workCount++;
if (workCount % 2 != 0) {
throw new RuntimeException("simulated failure to cause retry");
}
}
public int getWorkCount() {
return workCount;
}
public int getRunCount() {
return runCount;
}
}
private static final int SECONDS_HOUR = 3600;
@Rule
public WorkflowTest workflowTest = new WorkflowTest();
private CronWithRetryWorkflowClientFactory workflowClientFactory = new CronWithRetryWorkflowClientFactoryImpl();
private TestCronWithRetryWorkflowActivities cronActivitiesImplementation;
@Before
public void setUp() throws Exception {
cronActivitiesImplementation = new TestCronWithRetryWorkflowActivities();
workflowTest.addActivitiesImplementation(cronActivitiesImplementation);
workflowTest.addWorkflowImplementationType(CronWithRetryWorkflowImpl.class);
workflowTest.setDisableOutstandingTasksCheck(true);
}
@After
public void tearDown() throws Exception {
}
@Test(timeout = 2000)
public void testCronWithFailures() {
workflowTest.setClockAccelerationCoefficient(SECONDS_HOUR * 24 * 7 * 2);
final CronWithRetryWorkflowClient workflow = workflowClientFactory.getClient();
final ActivityType activityType = new ActivityType();
activityType.setName("CronWithRetryExampleActivities.doSomeWork");
activityType.setVersion("1.0");
final Object[] activityArguments = new Object[] { "parameter1" };
final CronWithRetryWorkflowOptions cronOptions = new CronWithRetryWorkflowOptions();
cronOptions.setActivity(activityType);
cronOptions.setActivityArguments(activityArguments);
cronOptions.setContinueAsNewAfterSeconds(SECONDS_HOUR * 24 + 300);
cronOptions.setTimeZone("PST");
cronOptions.setInitialRetryIntervalSeconds(30);
cronOptions.setMaximumRetryIntervalSeconds(600);
cronOptions.setRetryExpirationIntervalSeconds(3500);
final String cronExpression = "0 0 * * * *";
cronOptions.setCronExpression(cronExpression);
WorkflowClock clock = workflowTest.getDecisionContext().getWorkflowClock();
clock.createTimer(SECONDS_HOUR * 24 * 7 + 1000);
// true constructor argument makes TryCatchFinally a daemon which causes it get cancelled after above timer firing
new TryCatchFinally(true) {
Throwable failure;
@Override
protected void doTry() throws Throwable {
workflow.startCron(cronOptions);
}
@Override
protected void doCatch(Throwable e) throws Throwable {
failure = e;
throw e;
}
@Override
protected void doFinally() throws Throwable {
// Skip assertions as their failure masks original exception
if (failure == null || failure instanceof CancellationException) {
// Note the 2 activity invocations for each cron invocation as half of the
// invocations failed and were retried.
Assert.assertEquals(24 * 7 * 2, cronActivitiesImplementation.getWorkCount());
Assert.assertEquals(7, cronActivitiesImplementation.getRunCount());
}
}
};
}
}
| 3,422 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cronwithretry/ActivityHost.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.examples.cronwithretry;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.ActivityWorker;
import com.amazonaws.services.simpleworkflow.flow.examples.common.ConfigHelper;
/**
* This is the process which hosts all Activities in this sample
*/
public class ActivityHost {
private static final String ACTIVITIES_TASK_LIST = "Periodic";
public static void main(String[] args) throws Exception {
ConfigHelper configHelper = ConfigHelper.createConfig();
AmazonSimpleWorkflow swfService = configHelper.createSWFClient();
String domain = configHelper.getDomain();
final ActivityWorker worker = new ActivityWorker(swfService, domain, ACTIVITIES_TASK_LIST);
// Create activity implementations
CronWithRetryExampleActivities periodicActivitiesImpl = new CronExampleActivitiesImpl();
worker.addActivitiesImplementation(periodicActivitiesImpl);
worker.start();
System.out.println("Activity Worker Started for Task List: " + worker.getTaskListToPoll());
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
worker.shutdownAndAwaitTermination(1, TimeUnit.MINUTES);
System.out.println("Activity Worker Exited.");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("Please press any key to terminate service.");
try {
System.in.read();
}
catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
}
| 3,423 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cronwithretry/CronWithRetryWorkflow.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.examples.cronwithretry;
import com.amazonaws.services.simpleworkflow.flow.annotations.Execute;
import com.amazonaws.services.simpleworkflow.flow.annotations.GetState;
import com.amazonaws.services.simpleworkflow.flow.annotations.Workflow;
import com.amazonaws.services.simpleworkflow.flow.annotations.WorkflowRegistrationOptions;
@Workflow
@WorkflowRegistrationOptions(defaultExecutionStartToCloseTimeoutSeconds = 300, defaultTaskStartToCloseTimeoutSeconds = 10)
public interface CronWithRetryWorkflow {
/**
* Start workflow that executes activity according to options.
*
* @param activity
* activity type to execute
* @param activityArguments
* arguments passed to activity
* @param cronExpression
* time pattern in unix cron format.
* @param continueAsNewAfterSeconds
* frequency of a new workflow run creation
*/
@Execute(name = "CronWorkflow", version = "1.1")
void startCron(CronWithRetryWorkflowOptions options);
@GetState
String getInvocationHistory();
}
| 3,424 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cronwithretry/CronWithRetryWorkflowOptions.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.examples.cronwithretry;
import java.util.List;
import com.amazonaws.services.simpleworkflow.flow.common.FlowConstants;
import com.amazonaws.services.simpleworkflow.flow.interceptors.ExponentialRetryPolicy;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
/**
* See {@link ExponentialRetryPolicy} for description of retry related
* properties.
*
* @author fateev
*/
public class CronWithRetryWorkflowOptions {
private ActivityType activity;
private Object[] activityArguments;
private String cronExpression;
private String timeZone;
private int continueAsNewAfterSeconds;
private List<String> exceptionsToRetry;
private List<String> exceptionsToExclude;
private long initialRetryIntervalSeconds = 60;
private long maximumRetryIntervalSeconds = 3600;
private long retryExpirationIntervalSeconds = FlowConstants.NONE;
private double backoffCoefficient = 2.0;
private int maximumAttempts = FlowConstants.NONE;
public ActivityType getActivity() {
return activity;
}
public void setActivity(ActivityType activity) {
this.activity = activity;
}
public Object[] getActivityArguments() {
return activityArguments;
}
public void setActivityArguments(Object[] activityArguments) {
this.activityArguments = activityArguments;
}
public String getCronExpression() {
return cronExpression;
}
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
public int getContinueAsNewAfterSeconds() {
return continueAsNewAfterSeconds;
}
public void setContinueAsNewAfterSeconds(int continueAsNewAfterSeconds) {
this.continueAsNewAfterSeconds = continueAsNewAfterSeconds;
}
public List<String> getExceptionsToRetry() {
return exceptionsToRetry;
}
public void setExceptionsToRetry(List<String> exceptionsToRetry) {
this.exceptionsToRetry = exceptionsToRetry;
}
public List<String> getExceptionsToExclude() {
return exceptionsToExclude;
}
public void setExceptionsToExclude(List<String> exceptionsToExclude) {
this.exceptionsToExclude = exceptionsToExclude;
}
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 getRetryExpirationIntervalSeconds() {
return retryExpirationIntervalSeconds;
}
public void setRetryExpirationIntervalSeconds(long retryExpirationIntervalSeconds) {
this.retryExpirationIntervalSeconds = retryExpirationIntervalSeconds;
}
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;
}
}
| 3,425 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cronwithretry/CronWithRetryWorkflowExecutionStarter.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.examples.cronwithretry;
import java.util.ArrayList;
import java.util.List;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.examples.common.ConfigHelper;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecutionAlreadyStartedException;
public class CronWithRetryWorkflowExecutionStarter {
private static AmazonSimpleWorkflow swfService;
private static String domain;
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.err.println("Usage:\njava com.amazonaws.services.simpleworkflow.flow.examples.cron.CronWithRetryWorkflowExecutionStarter CRON_PATTERN TIME_ZONE CONTINUE_AS_NEW_AFTER_SECONDS");
System.exit(1);
}
String cronPattern = args[0];
String timeZone = args[1];
int continueAsNewAfterSeconds = 0;
try {
continueAsNewAfterSeconds = Integer.parseInt(args[2]);
}
catch (NumberFormatException e) {
System.err.println("Value of CONTINUE_AS_NEW_AFTER_SECONDS is not int: " + args[2]);
System.exit(1);
}
// Load configuration
ConfigHelper configHelper = ConfigHelper.createConfig();
// Create the client for Simple Workflow Service
swfService = configHelper.createSWFClient();
domain = configHelper.getDomain();
// Name and versions are hardcoded here but they can be passed as args or loaded from configuration file.
ActivityType activity = new ActivityType();
activity.setName("CronWithRetryExampleActivities.doSomeWork");
activity.setVersion("1.0");
Object[] arguments = new Object[] { "parameter1" };
// Start Workflow execution
CronWithRetryWorkflowClientExternalFactory clientFactory = new CronWithRetryWorkflowClientExternalFactoryImpl(swfService,
domain);
// Use Activity + cronPattern as instance id to ensure that only one workflow per pattern for a given activity is active at a time.
CronWithRetryWorkflowClientExternal workflow = clientFactory.getClient(activity.getName() + ": " + cronPattern);
try {
CronWithRetryWorkflowOptions cronOptions = new CronWithRetryWorkflowOptions();
cronOptions.setActivity(activity);
cronOptions.setActivityArguments(arguments);
cronOptions.setContinueAsNewAfterSeconds(continueAsNewAfterSeconds);
cronOptions.setTimeZone(timeZone);
cronOptions.setInitialRetryIntervalSeconds(1);
cronOptions.setMaximumRetryIntervalSeconds(60);
cronOptions.setRetryExpirationIntervalSeconds(300);
List<String> exceptionsToRetry = new ArrayList<String>();
exceptionsToRetry.add(Throwable.class.getName());
cronOptions.setExceptionsToRetry(exceptionsToRetry);
// Every 10 seconds
cronOptions.setCronExpression(cronPattern);
workflow.startCron(cronOptions);
// WorkflowExecution is available after workflow creation
WorkflowExecution workflowExecution = workflow.getWorkflowExecution();
System.out.println("Started Cron workflow with workflowId=\"" + workflowExecution.getWorkflowId() + "\" and runId=\""
+ workflowExecution.getRunId() + "\" with cron pattern=" + cronPattern);
}
catch (WorkflowExecutionAlreadyStartedException e) {
// It is expected to get this exception if start is called before workflow run is completed.
System.out.println("Cron workflow with workflowId=\"" + workflow.getWorkflowExecution().getWorkflowId()
+ " is already running for the pattern=" + cronPattern);
}
// This is to demonstrate the @GetState annotated method getInvocationHistory
System.out.println("Sleeping for 60 seconds...");
Thread.sleep(60000);
System.out.println("Invocation history after 60 seconds: \n" + workflow.getInvocationHistory());
System.exit(0);
}
}
| 3,426 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cronwithretry/CronExampleActivitiesImpl.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.examples.cronwithretry;
import java.util.Random;
import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContext;
import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContextProvider;
import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContextProviderImpl;
import com.amazonaws.services.simpleworkflow.model.ActivityTask;
public class CronExampleActivitiesImpl implements CronWithRetryExampleActivities {
final ActivityExecutionContextProvider contextProvider;
public CronExampleActivitiesImpl() {
this(new ActivityExecutionContextProviderImpl());
}
/**
* Useful for unit testing activities.
*/
public CronExampleActivitiesImpl(ActivityExecutionContextProvider contextProvider) {
this.contextProvider = contextProvider;
}
/**
* Fail in 20% of invocations to demonstrate retry logic
*/
@Override
public void doSomeWork(String parameter) {
Random r = new Random();
if (r.nextInt(100) < 20) {
throw new RuntimeException("simulated exception to force retry");
}
ActivityExecutionContext context = contextProvider.getActivityExecutionContext();
ActivityTask task = context.getTask();
String taskid = task.getActivityId();
System.out.println("Processed activity task with id: " + taskid);
}
}
| 3,427 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cronwithretry/CronWithRetryExampleActivities.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.examples.cronwithretry;
import com.amazonaws.services.simpleworkflow.flow.annotations.Activities;
import com.amazonaws.services.simpleworkflow.flow.annotations.ActivityRegistrationOptions;
@Activities(version="1.0")
@ActivityRegistrationOptions(
defaultTaskScheduleToStartTimeoutSeconds = 100,
defaultTaskStartToCloseTimeoutSeconds = 10)
public interface CronWithRetryExampleActivities {
void doSomeWork(String parameter);
}
| 3,428 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cronwithretry/WorkflowHost.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.examples.cronwithretry;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.WorkflowWorker;
import com.amazonaws.services.simpleworkflow.flow.examples.common.ConfigHelper;
public class WorkflowHost {
public static final String DECISION_TASK_LIST = "PeriodicWorkflow";
public static void main(String[] args) throws Exception {
ConfigHelper configHelper = ConfigHelper.createConfig();
AmazonSimpleWorkflow swfService = configHelper.createSWFClient();
String domain = configHelper.getDomain();
final WorkflowWorker worker = new WorkflowWorker(swfService, domain, DECISION_TASK_LIST);
worker.addWorkflowImplementationType(CronWithRetryWorkflowImpl.class);
worker.setRegisterDomain(true);
worker.setDomainRetentionPeriodInDays(1);
worker.start();
System.out.println("Workflow Host Service Started...");
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
worker.shutdownAndAwaitTermination(1, TimeUnit.MINUTES);
System.out.println("Workflow Host Service Terminated...");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("Please press any key to terminate service.");
try {
System.in.read();
}
catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
}
| 3,429 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cron/CronWorkflowOptions.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.examples.cron;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
/**
* See {@link ExponentialRetryPolicy} for description of retry related
* properties.
*
* @author fateev
*/
public class CronWorkflowOptions {
private ActivityType activity;
private Object[] activityArguments;
private String cronExpression;
private String timeZone;
private int continueAsNewAfterSeconds;
public ActivityType getActivity() {
return activity;
}
public void setActivity(ActivityType activity) {
this.activity = activity;
}
public Object[] getActivityArguments() {
return activityArguments;
}
public void setActivityArguments(Object[] activityArguments) {
this.activityArguments = activityArguments;
}
public String getCronExpression() {
return cronExpression;
}
public void setCronExpression(String cronExpression) {
this.cronExpression = cronExpression;
}
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
public int getContinueAsNewAfterSeconds() {
return continueAsNewAfterSeconds;
}
public void setContinueAsNewAfterSeconds(int continueAsNewAfterSeconds) {
this.continueAsNewAfterSeconds = continueAsNewAfterSeconds;
}
}
| 3,430 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cron/CronWorkflowTest.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.examples.cron;
import java.util.concurrent.CancellationException;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContext;
import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContextProvider;
import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContextProviderImpl;
import com.amazonaws.services.simpleworkflow.flow.WorkflowClock;
import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally;
import com.amazonaws.services.simpleworkflow.flow.junit.FlowBlockJUnit4ClassRunner;
import com.amazonaws.services.simpleworkflow.flow.junit.WorkflowTest;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
@RunWith(FlowBlockJUnit4ClassRunner.class)
public class CronWorkflowTest {
private static final int SECONDS_HOUR = 3600;
private final class TestCronWorkflowActivities implements CronExampleActivities {
private final ActivityExecutionContextProvider contextProvider = new ActivityExecutionContextProviderImpl();
private int workCount;
private int runCount;
private String runId;
@Override
public void doSomeWork(String parameter) {
// Reset counter on the new run which changes when workflow continues as new
ActivityExecutionContext activityExecutionContext = contextProvider.getActivityExecutionContext();
WorkflowExecution workflowExecution = activityExecutionContext.getWorkflowExecution();
String runId = workflowExecution.getRunId();
if (this.runId == null || !runId.equals(this.runId)) {
runCount++;
}
this.runId = runId;
workCount++;
}
public int getWorkCount() {
return workCount;
}
public int getRunCount() {
return runCount;
}
}
@Rule
public WorkflowTest workflowTest = new WorkflowTest();
private CronWorkflowClientFactory workflowClientFactory = new CronWorkflowClientFactoryImpl();
private TestCronWorkflowActivities cronActivitiesImplementation;
@Before
public void setUp() throws Exception {
cronActivitiesImplementation = new TestCronWorkflowActivities();
workflowTest.addActivitiesImplementation(cronActivitiesImplementation);
workflowTest.addWorkflowImplementationType(CronWorkflowImpl.class);
workflowTest.setDisableOutstandingTasksCheck(true);
}
@After
public void tearDown() throws Exception {
}
@Test(timeout = 2000)
public void testCron() {
workflowTest.setClockAccelerationCoefficient(SECONDS_HOUR * 24 * 7 * 2);
final CronWorkflowClient workflow = workflowClientFactory.getClient();
final ActivityType activityType = new ActivityType();
activityType.setName("CronExampleActivities.doSomeWork");
activityType.setVersion("1.0");
final Object[] activityArguments = new Object[] { "parameter1" };
final CronWorkflowOptions cronOptions = new CronWorkflowOptions();
cronOptions.setActivity(activityType);
cronOptions.setActivityArguments(activityArguments);
cronOptions.setContinueAsNewAfterSeconds(SECONDS_HOUR * 24 + 300);
cronOptions.setTimeZone("PST");
final String cronExpression = "0 0 * * * *";
cronOptions.setCronExpression(cronExpression);
WorkflowClock clock = workflowTest.getDecisionContext().getWorkflowClock();
clock.createTimer(SECONDS_HOUR * 24 * 7 + 1000);
// true constructor argument makes TryCatchFinally a daemon which causes it get cancelled after above timer firing
new TryCatchFinally(true) {
Throwable failure;
@Override
protected void doTry() throws Throwable {
workflow.startCron(cronOptions);
}
@Override
protected void doCatch(Throwable e) throws Throwable {
failure = e;
throw e;
}
@Override
protected void doFinally() throws Throwable {
// Skip assertions as their failure masks original exception
if (failure == null || failure instanceof CancellationException) {
Assert.assertEquals(24 * 7, cronActivitiesImplementation.getWorkCount());
Assert.assertEquals(7, cronActivitiesImplementation.getRunCount());
}
}
};
}
}
| 3,431 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cron/ActivityHost.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.examples.cron;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.ActivityWorker;
import com.amazonaws.services.simpleworkflow.flow.examples.common.ConfigHelper;
/**
* This is the process which hosts all Activities in this sample
*/
public class ActivityHost {
private static final String ACTIVITIES_TASK_LIST = "Periodic";
public static void main(String[] args) throws Exception {
ConfigHelper configHelper = ConfigHelper.createConfig();
AmazonSimpleWorkflow swfService = configHelper.createSWFClient();
String domain = configHelper.getDomain();
final ActivityWorker worker = new ActivityWorker(swfService, domain, ACTIVITIES_TASK_LIST);
// Create activity implementations
CronExampleActivities periodicActivitiesImpl = new CronExampleActivitiesImpl();
worker.addActivitiesImplementation(periodicActivitiesImpl);
worker.start();
System.out.println("Activity Worker Started for Task List: " + worker.getTaskListToPoll());
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
worker.shutdownAndAwaitTermination(1, TimeUnit.MINUTES);
System.out.println("Activity Worker Exited.");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("Please press any key to terminate service.");
try {
System.in.read();
}
catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
}
| 3,432 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cron/CronWorkflowImpl.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.examples.cron;
import java.util.Date;
import java.util.TimeZone;
import com.amazonaws.services.simpleworkflow.flow.DecisionContextProviderImpl;
import com.amazonaws.services.simpleworkflow.flow.DynamicActivitiesClient;
import com.amazonaws.services.simpleworkflow.flow.DynamicActivitiesClientImpl;
import com.amazonaws.services.simpleworkflow.flow.WorkflowClock;
import com.amazonaws.services.simpleworkflow.flow.spring.CronDecorator;
/**
* Demonstrates how to create workflow that executes an activity on schedule
* specified as a "cron" string. Activity name and version are passed as input
* arguments of the workflow. In case of activity failures it is retried
* according to retry options passed as arguments of the workflow.
*
* @author fateev
*/
public class CronWorkflowImpl implements CronWorkflow {
private static final int SECOND = 1000;
/**
* This is needed to keep the decider logic deterministic as using
* System.currentTimeMillis() in your decider logic is not.
* WorkflowClock.currentTimeMillis() should be used instead.
*/
private final WorkflowClock clock;
private final DynamicActivitiesClient activities;
/**
* Used to create new run of the Cron workflow to reset history. This allows
* "infinite" workflows.
*/
private final CronWorkflowSelfClient selfClient;
public CronWorkflowImpl() {
this(new DecisionContextProviderImpl().getDecisionContext().getWorkflowClock(), new DynamicActivitiesClientImpl(),
new CronWorkflowSelfClientImpl());
}
/**
* Constructor used for unit testing or configuration through IOC container
*/
public CronWorkflowImpl(WorkflowClock clock, DynamicActivitiesClient activities, CronWorkflowSelfClient selfClient) {
this.clock = clock;
this.activities = activities;
this.selfClient = selfClient;
}
@Override
public void startCron(final CronWorkflowOptions options) {
long startTime = clock.currentTimeMillis();
Date expiration = new Date(startTime + options.getContinueAsNewAfterSeconds() * SECOND);
TimeZone tz = TimeZone.getTimeZone(options.getTimeZone());
CronDecorator cronDecorator = new CronDecorator(options.getCronExpression(), expiration, tz, clock);
DynamicActivitiesClient cronDecoratedActivities = cronDecorator.decorate(DynamicActivitiesClient.class, activities);
cronDecoratedActivities.scheduleActivity(options.getActivity(), options.getActivityArguments(), null, Void.class);
// Start new workflow run as soon as cron decorator exits due to expiration.
// The call to self client indicates the desire to start the new run.
// It is started only after all other tasks in the given run are completed.
selfClient.startCron(options);
}
}
| 3,433 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cron/CronExampleActivities.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.examples.cron;
import com.amazonaws.services.simpleworkflow.flow.annotations.Activities;
import com.amazonaws.services.simpleworkflow.flow.annotations.ActivityRegistrationOptions;
@Activities(version="1.0")
@ActivityRegistrationOptions(
defaultTaskScheduleToStartTimeoutSeconds = 100,
defaultTaskStartToCloseTimeoutSeconds = 10)
public interface CronExampleActivities {
void doSomeWork(String parameter);
}
| 3,434 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cron/CronExampleActivitiesImpl.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.examples.cron;
import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContext;
import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContextProvider;
import com.amazonaws.services.simpleworkflow.flow.ActivityExecutionContextProviderImpl;
import com.amazonaws.services.simpleworkflow.model.ActivityTask;
public class CronExampleActivitiesImpl implements CronExampleActivities {
final ActivityExecutionContextProvider contextProvider;
public CronExampleActivitiesImpl() {
this(new ActivityExecutionContextProviderImpl());
}
/**
* Useful for unit testing activities.
*/
public CronExampleActivitiesImpl(ActivityExecutionContextProvider contextProvider) {
this.contextProvider = contextProvider;
}
/**
*
*/
@Override
public void doSomeWork(String parameter) {
ActivityExecutionContext context = contextProvider.getActivityExecutionContext();
ActivityTask task = context.getTask();
String taskid = task.getActivityId();
System.out.println("Processed activity task with id: " + taskid);
}
}
| 3,435 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cron/CronWorkflowExecutionStarter.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.examples.cron;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.examples.common.ConfigHelper;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecutionAlreadyStartedException;
public class CronWorkflowExecutionStarter {
private static AmazonSimpleWorkflow swfService;
private static String domain;
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.err.println("Usage:\njava com.amazonaws.services.simpleworkflow.flow.examples.cron.CronWorkflowExecutionStarter CRON_PATTERN TIME_ZONE CONTINUE_AS_NEW_AFTER_SECONDS");
System.exit(1);
}
String cronPattern = args[0];
String timeZone = args[1];
int continueAsNewAfterSeconds = 0;
try {
continueAsNewAfterSeconds = Integer.parseInt(args[2]);
}
catch (NumberFormatException e) {
System.err.println("Value of CONTINUE_AS_NEW_AFTER_SECONDS is not int: " + args[2]);
System.exit(1);
}
// Load configuration
ConfigHelper configHelper = ConfigHelper.createConfig();
// Create the client for Simple Workflow Service
swfService = configHelper.createSWFClient();
domain = configHelper.getDomain();
// Name and versions are hardcoded here but they can be passed as args or loaded from configuration file.
ActivityType activity = new ActivityType();
activity.setName("CronExampleActivities.doSomeWork");
activity.setVersion("1.0");
Object[] arguments = new Object[] { "parameter1" };
// Start Workflow execution
CronWorkflowClientExternalFactory clientFactory = new CronWorkflowClientExternalFactoryImpl(swfService, domain);
// Use Activity + cronPattern as instance id to ensure that only one workflow per pattern for a given activity is active at a time.
CronWorkflowClientExternal workflow = clientFactory.getClient(activity.getName() + ": " + cronPattern);
try {
CronWorkflowOptions cronOptions = new CronWorkflowOptions();
cronOptions.setActivity(activity);
cronOptions.setActivityArguments(arguments);
cronOptions.setContinueAsNewAfterSeconds(continueAsNewAfterSeconds);
cronOptions.setTimeZone(timeZone);
// Every 10 seconds
cronOptions.setCronExpression(cronPattern);
workflow.startCron(cronOptions);
// WorkflowExecution is available after workflow creation
WorkflowExecution workflowExecution = workflow.getWorkflowExecution();
System.out.println("Started Cron workflow with workflowId=\"" + workflowExecution.getWorkflowId() + "\" and runId=\""
+ workflowExecution.getRunId() + "\" with cron pattern=" + cronPattern);
}
catch (WorkflowExecutionAlreadyStartedException e) {
// It is expected to get this exception if start is called before workflow run is completed.
System.out.println("Cron workflow with workflowId=\"" + workflow.getWorkflowExecution().getWorkflowId()
+ " is already running for the pattern=" + cronPattern);
}
System.exit(0);
}
}
| 3,436 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cron/CronWorkflow.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.examples.cron;
import com.amazonaws.services.simpleworkflow.flow.annotations.Execute;
import com.amazonaws.services.simpleworkflow.flow.annotations.Workflow;
import com.amazonaws.services.simpleworkflow.flow.annotations.WorkflowRegistrationOptions;
@Workflow
@WorkflowRegistrationOptions(defaultExecutionStartToCloseTimeoutSeconds = 300, defaultTaskStartToCloseTimeoutSeconds = 10)
public interface CronWorkflow {
/**
* Start workflow that executes activity according to options.
*/
@Execute(name = "CronWorkflow", version = "1.0")
void startCron(CronWorkflowOptions options);
}
| 3,437 |
0 | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples | Create_ds/aws-swf-flow-library/src/samples/AwsFlowFramework/src/com/amazonaws/services/simpleworkflow/flow/examples/cron/WorkflowHost.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.examples.cron;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.WorkflowWorker;
import com.amazonaws.services.simpleworkflow.flow.examples.common.ConfigHelper;
public class WorkflowHost {
public static final String DECISION_TASK_LIST = "PeriodicWorkflow";
public static void main(String[] args) throws Exception {
ConfigHelper configHelper = ConfigHelper.createConfig();
AmazonSimpleWorkflow swfService = configHelper.createSWFClient();
String domain = configHelper.getDomain();
final WorkflowWorker worker = new WorkflowWorker(swfService, domain, DECISION_TASK_LIST);
worker.addWorkflowImplementationType(CronWorkflowImpl.class);
worker.setRegisterDomain(true);
worker.setDomainRetentionPeriodInDays(1);
worker.start();
System.out.println("Workflow Host Service Started...");
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
worker.shutdownAndAwaitTermination(1, TimeUnit.MINUTES);
System.out.println("Workflow Host Service Terminated...");
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("Please press any key to terminate service.");
try {
System.in.read();
}
catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
}
| 3,438 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ScheduleActivityTaskFailedException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
import com.amazonaws.services.simpleworkflow.model.ScheduleActivityTaskFailedCause;
/**
* Exception used to communicate that activity wasn't scheduled due to some
* cause
*/
@SuppressWarnings("serial")
public class ScheduleActivityTaskFailedException extends ActivityTaskException {
private ScheduleActivityTaskFailedCause failureCause;
public ScheduleActivityTaskFailedException(String message) {
super(message);
}
public ScheduleActivityTaskFailedException(String message, Throwable cause) {
super(message, cause);
}
public ScheduleActivityTaskFailedException(long eventId, ActivityType activityType, String activityId, String cause) {
super(cause, eventId, activityType, activityId);
failureCause = ScheduleActivityTaskFailedCause.fromValue(cause);
}
/**
* @return enumeration that contains the cause of the failure
*/
public ScheduleActivityTaskFailedCause getFailureCause() {
return failureCause;
}
public void setFailureCause(ScheduleActivityTaskFailedCause failureCause) {
this.failureCause = failureCause;
}
}
| 3,439 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowWorker.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig;
import com.amazonaws.services.simpleworkflow.flow.pojo.POJOWorkflowDefinitionFactoryFactory;
import com.amazonaws.services.simpleworkflow.flow.worker.GenericWorkflowWorker;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
public class WorkflowWorker implements WorkerBase {
private final GenericWorkflowWorker genericWorker;
private final POJOWorkflowDefinitionFactoryFactory factoryFactory ;
private final Collection<Class<?>> workflowImplementationTypes = new ArrayList<Class<?>>();
public WorkflowWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll) {
this(new GenericWorkflowWorker(service, domain, taskListToPoll));
}
public WorkflowWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll, SimpleWorkflowClientConfig config) {
this(new GenericWorkflowWorker(service, domain, taskListToPoll, config));
}
public WorkflowWorker(GenericWorkflowWorker genericWorker) {
Objects.requireNonNull(genericWorker,"the workflow worker is required");
this.genericWorker = genericWorker;
this.factoryFactory = new POJOWorkflowDefinitionFactoryFactory();
this.genericWorker.setWorkflowDefinitionFactoryFactory(factoryFactory);
}
@Override
public SimpleWorkflowClientConfig getClientConfig() {
return genericWorker.getClientConfig();
}
@Override
public AmazonSimpleWorkflow getService() {
return genericWorker.getService();
}
@Override
public String getDomain() {
return genericWorker.getDomain();
}
@Override
public boolean isRegisterDomain() {
return genericWorker.isRegisterDomain();
}
@Override
public void setRegisterDomain(boolean registerDomain) {
genericWorker.setRegisterDomain(registerDomain);
}
@Override
public long getDomainRetentionPeriodInDays() {
return genericWorker.getDomainRetentionPeriodInDays();
}
@Override
public void setDomainRetentionPeriodInDays(long domainRetentionPeriodInDays) {
genericWorker.setDomainRetentionPeriodInDays(domainRetentionPeriodInDays);
}
@Override
public String getTaskListToPoll() {
return genericWorker.getTaskListToPoll();
}
@Override
public double getMaximumPollRatePerSecond() {
return genericWorker.getMaximumPollRatePerSecond();
}
/**
* Maximum rate of polling and executing decisions (as they are done by the
* same thread synchronously) by this WorkflowWorker.
*/
@Override
public void setMaximumPollRatePerSecond(double maximumPollRatePerSecond) {
genericWorker.setMaximumPollRatePerSecond(maximumPollRatePerSecond);
}
@Override
public int getMaximumPollRateIntervalMilliseconds() {
return genericWorker.getMaximumPollRateIntervalMilliseconds();
}
/**
* Time interval used to measure the polling rate. For example if
* {@link #setMaximumPollRatePerSecond(double)} is 100 and interval is 1000
* milliseconds then if first 100 requests take 10 milliseconds polling is
* suspended for 990 milliseconds. If poll interval is changed to 100
* milliseconds then polling is suspended for 90 milliseconds.
*/
@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 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 registerTypesToPoll() {
genericWorker.registerTypesToPoll();
}
@Override
public void start() {
genericWorker.start();
}
@Override
public void shutdown() {
genericWorker.shutdown();
}
@Override
public void shutdownNow() {
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);
}
@Override
public boolean isRunning() {
return genericWorker.isRunning();
}
@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 void setWorkflowImplementationTypes(Collection<Class<?>> workflowImplementationTypes)
throws InstantiationException, IllegalAccessException {
for (Class<?> workflowImplementationType : workflowImplementationTypes) {
addWorkflowImplementationType(workflowImplementationType);
}
}
public Collection<Class<?>> getWorkflowImplementationTypes() {
return workflowImplementationTypes;
}
public void addWorkflowImplementationType(Class<?> workflowImplementationType) throws InstantiationException, IllegalAccessException {
factoryFactory.addWorkflowImplementationType(workflowImplementationType);
}
public void addWorkflowImplementationType(Class<?> workflowImplementationType, DataConverter converter) throws InstantiationException, IllegalAccessException {
factoryFactory.addWorkflowImplementationType(workflowImplementationType, converter);
}
public void addWorkflowImplementationType(Class<?> workflowImplementationType, DataConverter converter, Object[] constructorArgs) throws InstantiationException, IllegalAccessException {
factoryFactory.addWorkflowImplementationType(workflowImplementationType, converter, constructorArgs, null);
}
@Override
public String toString() {
return this.getClass().getSimpleName() + "[genericWorker=" + genericWorker + ", wokflowImplementationTypes="
+ workflowImplementationTypes + "]";
}
@Override
public boolean shutdownAndAwaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return genericWorker.shutdownAndAwaitTermination(timeout, unit);
}
public DataConverter getDataConverter() {
return factoryFactory.getDataConverter();
}
public void setDefaultConverter(DataConverter converter) {
factoryFactory.setDataConverter(converter);
}
public void addWorkflowImplementationType(Class<?> workflowImplementationType,
Map<String, Integer> maximumAllowedComponentImplementationVersions)
throws InstantiationException, IllegalAccessException {
factoryFactory.addWorkflowImplementationType(workflowImplementationType, maximumAllowedComponentImplementationVersions);
}
@Override
public void setDisableTypeRegistrationOnStart(boolean disableTypeRegistrationOnStart) {
genericWorker.setDisableTypeRegistrationOnStart(disableTypeRegistrationOnStart);
}
@Override
public boolean isDisableTypeRegistrationOnStart() {
return genericWorker.isDisableTypeRegistrationOnStart();
}
public void addWorkflowImplementationType(Class<?> workflowImplementationType, DataConverter converter,
Map<String, Integer> maximumAllowedComponentImplementationVersions)
throws InstantiationException, IllegalAccessException {
factoryFactory.addWorkflowImplementationType(workflowImplementationType, converter,
null, maximumAllowedComponentImplementationVersions);
}
/**
* @see com.amazonaws.services.simpleworkflow.flow.annotations.WorkflowComponentImplementationVersion
* @param maximumAllowedImplementationVersions
* {key->WorkflowType, value->{key->componentName,
* value->maximumAllowedVersion}}
*/
public void setMaximumAllowedComponentImplementationVersions(
Map<WorkflowType, Map<String, Integer>> maximumAllowedImplementationVersions) {
factoryFactory.setMaximumAllowedComponentImplementationVersions(maximumAllowedImplementationVersions);
}
public Map<WorkflowType, Map<String, Integer>> getMaximumAllowedComponentImplementationVersions() {
return factoryFactory.getMaximumAllowedComponentImplementationVersions();
}
}
| 3,440 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/SuspendableWorker.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;
public interface SuspendableWorker extends Suspendable, WorkerLifecycle {
}
| 3,441 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowReplayer.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.common.WorkflowExecutionUtils;
import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig;
import com.amazonaws.services.simpleworkflow.flow.core.AsyncTaskInfo;
import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinition;
import com.amazonaws.services.simpleworkflow.flow.generic.WorkflowDefinitionFactoryFactory;
import com.amazonaws.services.simpleworkflow.flow.pojo.POJOWorkflowDefinition;
import com.amazonaws.services.simpleworkflow.flow.pojo.POJOWorkflowDefinitionFactoryFactory;
import com.amazonaws.services.simpleworkflow.flow.pojo.POJOWorkflowImplementationFactory;
import com.amazonaws.services.simpleworkflow.flow.replaydeserializer.TimeStampMixin;
import com.amazonaws.services.simpleworkflow.flow.worker.AsyncDecisionTaskHandler;
import com.amazonaws.services.simpleworkflow.model.DecisionTask;
import com.amazonaws.services.simpleworkflow.model.EventType;
import com.amazonaws.services.simpleworkflow.model.History;
import com.amazonaws.services.simpleworkflow.model.HistoryEvent;
import com.amazonaws.services.simpleworkflow.model.RespondDecisionTaskCompletedRequest;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecutionInfo;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecutionStartedEventAttributes;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
public class WorkflowReplayer<T> {
private final class WorkflowReplayerPOJOFactoryFactory extends POJOWorkflowDefinitionFactoryFactory {
private final T workflowImplementation;
private WorkflowReplayerPOJOFactoryFactory(T workflowImplementation) throws InstantiationException, IllegalAccessException {
this.workflowImplementation = workflowImplementation;
super.addWorkflowImplementationType(workflowImplementation.getClass());
}
@Override
protected POJOWorkflowImplementationFactory getImplementationFactory(Class<?> workflowImplementationType,
Class<?> workflowInteface, WorkflowType workflowType) {
return new POJOWorkflowImplementationFactory() {
@Override
public Object newInstance(DecisionContext decisionContext) throws Exception {
return workflowImplementation;
}
@Override
public Object newInstance(DecisionContext decisionContext, Object[] constructorArgs) throws Exception {
return workflowImplementation;
}
@Override
public void deleteInstance(Object instance) {
}
};
}
}
private abstract class DecisionTaskIterator implements Iterator<DecisionTask> {
private DecisionTask next;
private boolean initialized;
protected void initNext() {
initialized = true;
next = getNextHistoryTask(null);
}
@Override
public boolean hasNext() {
if (!initialized) {
initNext();
}
if (next == null) {
return false;
}
List<HistoryEvent> events = next.getEvents();
if (events.size() == 0) {
return false;
}
if (replayUpToEventId == 0) {
return true;
}
HistoryEvent firstEvent = next.getEvents().get(0);
return firstEvent.getEventId() <= replayUpToEventId;
}
@Override
public DecisionTask next() {
if (!hasNext()) {
throw new IllegalStateException("hasNext() == false");
}
DecisionTask result = next;
if (next.getNextPageToken() == null) {
next = null;
}
else {
next = getNextHistoryTask(next.getNextPageToken());
}
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
protected List<HistoryEvent> truncateHistory(List<HistoryEvent> events) {
if (events.size() == 0) {
return null;
}
if (replayUpToEventId == 0) {
return events;
}
HistoryEvent lastEvent = events.get(events.size() - 1);
if (lastEvent.getEventId() <= replayUpToEventId) {
return events;
}
List<HistoryEvent> truncated = new ArrayList<HistoryEvent>();
for (HistoryEvent event : events) {
if (event.getEventId() > replayUpToEventId) {
break;
}
truncated.add(event);
}
if (truncated.size() == 0) {
return null;
}
return truncated;
}
protected abstract DecisionTask getNextHistoryTask(String nextPageToken);
}
private class ServiceDecisionTaskIterator extends DecisionTaskIterator {
private final AmazonSimpleWorkflow service;
private final String domain;
private final WorkflowExecution workflowExecution;
private final SimpleWorkflowClientConfig config;
public ServiceDecisionTaskIterator(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution) {
this(service, domain, workflowExecution, null);
}
public ServiceDecisionTaskIterator(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution, SimpleWorkflowClientConfig config) {
this.service = service;
this.domain = domain;
this.workflowExecution = workflowExecution;
this.config = config;
}
protected DecisionTask getNextHistoryTask(String nextPageToken) {
WorkflowExecutionInfo executionInfo = WorkflowExecutionUtils.describeWorkflowInstance(service, domain,
workflowExecution, config);
History history = WorkflowExecutionUtils.getHistoryPage(nextPageToken, service, domain, workflowExecution, config);
DecisionTask task = new DecisionTask();
List<HistoryEvent> events = history.getEvents();
events = truncateHistory(events);
if (events == null) {
return null;
}
task.setEvents(events);
task.setWorkflowExecution(workflowExecution);
task.setWorkflowType(executionInfo.getWorkflowType());
task.setNextPageToken(history.getNextPageToken());
return task;
}
}
private class HistoryIterableDecisionTaskIterator extends DecisionTaskIterator {
private final WorkflowExecution workflowExecution;
private final Iterable<HistoryEvent> history;
public HistoryIterableDecisionTaskIterator(WorkflowExecution workflowExecution, Iterable<HistoryEvent> history) {
this.workflowExecution = workflowExecution;
this.history = history;
}
@Override
protected DecisionTask getNextHistoryTask(String nextPageToken) {
DecisionTask result = new DecisionTask();
Iterator<HistoryEvent> iterator = history.iterator();
if (!iterator.hasNext()) {
throw new IllegalStateException("empty history");
}
HistoryEvent startEvent = iterator.next();
WorkflowExecutionStartedEventAttributes startedAttributes = startEvent.getWorkflowExecutionStartedEventAttributes();
if (startedAttributes == null) {
throw new IllegalStateException("first event is not WorkflowExecutionStarted: " + startEvent);
}
List<HistoryEvent> events = new ArrayList<HistoryEvent>();
events.add(startEvent);
EventType eventType = null;
int lastStartedIndex = 0;
int index = 1;
long previousStartedEventId = 0;
long startedEventId = 0;
while (iterator.hasNext()) {
HistoryEvent event = iterator.next();
eventType = EventType.fromValue(event.getEventType());
events.add(event);
if (eventType == EventType.DecisionTaskStarted) {
previousStartedEventId = startedEventId;
startedEventId = event.getEventId();
lastStartedIndex = index;
}
index++;
}
if (events.size() > lastStartedIndex + 1) {
events = events.subList(0, lastStartedIndex + 1);
}
result.setEvents(events);
result.setPreviousStartedEventId(previousStartedEventId);
result.setStartedEventId(startedEventId);
result.setWorkflowExecution(workflowExecution);
WorkflowType workflowType = startedAttributes.getWorkflowType();
result.setWorkflowType(workflowType);
return result;
}
}
private final Iterator<DecisionTask> taskIterator;
private final AsyncDecisionTaskHandler taskHandler;
private int replayUpToEventId;
private final AtomicBoolean replayed = new AtomicBoolean();
public WorkflowReplayer(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution,
Class<T> workflowImplementationType) throws InstantiationException, IllegalAccessException {
this(service, domain, workflowExecution, workflowImplementationType, null);
}
public WorkflowReplayer(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution,
Class<T> workflowImplementationType, SimpleWorkflowClientConfig config) throws InstantiationException, IllegalAccessException {
this(service, domain, workflowExecution, workflowImplementationType, config, null);
}
public WorkflowReplayer(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution,
Class<T> workflowImplementationType, SimpleWorkflowClientConfig config, ChildWorkflowIdHandler childWorkflowIdHandler) throws InstantiationException, IllegalAccessException {
POJOWorkflowDefinitionFactoryFactory ff = new POJOWorkflowDefinitionFactoryFactory();
ff.addWorkflowImplementationType(workflowImplementationType);
taskIterator = new ServiceDecisionTaskIterator(service, domain, workflowExecution, config);
taskHandler = new AsyncDecisionTaskHandler(ff, childWorkflowIdHandler);
}
public WorkflowReplayer(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution,
final T workflowImplementation) throws InstantiationException, IllegalAccessException {
this(service, domain, workflowExecution, workflowImplementation, null);
}
public WorkflowReplayer(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution,
final T workflowImplementation, SimpleWorkflowClientConfig config) throws InstantiationException, IllegalAccessException {
this(service, domain, workflowExecution, workflowImplementation, null, null);
}
public WorkflowReplayer(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution,
final T workflowImplementation, SimpleWorkflowClientConfig config, ChildWorkflowIdHandler childWorkflowIdHandler) throws InstantiationException, IllegalAccessException {
WorkflowDefinitionFactoryFactory ff = new WorkflowReplayerPOJOFactoryFactory(workflowImplementation);
taskIterator = new ServiceDecisionTaskIterator(service, domain, workflowExecution, config);
taskHandler = new AsyncDecisionTaskHandler(ff, childWorkflowIdHandler);
}
public WorkflowReplayer(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution,
WorkflowDefinitionFactoryFactory workflowDefinitionFactoryFactory)
throws InstantiationException, IllegalAccessException {
this(service, domain, workflowExecution, workflowDefinitionFactoryFactory, null);
}
public WorkflowReplayer(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution,
WorkflowDefinitionFactoryFactory workflowDefinitionFactoryFactory, SimpleWorkflowClientConfig config)
throws InstantiationException, IllegalAccessException {
this(service, domain, workflowExecution, workflowDefinitionFactoryFactory, config, null);
}
public WorkflowReplayer(AmazonSimpleWorkflow service, String domain, WorkflowExecution workflowExecution,
WorkflowDefinitionFactoryFactory workflowDefinitionFactoryFactory, SimpleWorkflowClientConfig config,
ChildWorkflowIdHandler childWorkflowIdHandler)
throws InstantiationException, IllegalAccessException {
taskIterator = new ServiceDecisionTaskIterator(service, domain, workflowExecution, config);
taskHandler = new AsyncDecisionTaskHandler(workflowDefinitionFactoryFactory, childWorkflowIdHandler);
}
public WorkflowReplayer(Iterable<HistoryEvent> history, WorkflowExecution workflowExecution,
Class<T> workflowImplementationType) throws InstantiationException, IllegalAccessException {
this(history, workflowExecution, workflowImplementationType, false);
}
public WorkflowReplayer(Iterable<HistoryEvent> history, WorkflowExecution workflowExecution,
Class<T> workflowImplementationType, boolean skipFailedCheck) throws InstantiationException, IllegalAccessException {
this(history, workflowExecution, workflowImplementationType, skipFailedCheck, null);
}
public WorkflowReplayer(Iterable<HistoryEvent> history, WorkflowExecution workflowExecution,
Class<T> workflowImplementationType, boolean skipFailedCheck, ChildWorkflowIdHandler childWorkflowIdHandler) throws InstantiationException, IllegalAccessException {
POJOWorkflowDefinitionFactoryFactory ff = new POJOWorkflowDefinitionFactoryFactory();
ff.addWorkflowImplementationType(workflowImplementationType);
taskIterator = new HistoryIterableDecisionTaskIterator(workflowExecution, history);
taskHandler = new AsyncDecisionTaskHandler(ff, skipFailedCheck, childWorkflowIdHandler);
}
public WorkflowReplayer(Iterable<HistoryEvent> history, WorkflowExecution workflowExecution, final T workflowImplementation)
throws InstantiationException, IllegalAccessException {
this(history, workflowExecution, workflowImplementation, null);
}
public WorkflowReplayer(Iterable<HistoryEvent> history, WorkflowExecution workflowExecution, final T workflowImplementation, ChildWorkflowIdHandler childWorkflowIdHandler)
throws InstantiationException, IllegalAccessException {
WorkflowDefinitionFactoryFactory ff = new WorkflowReplayerPOJOFactoryFactory(workflowImplementation);
taskIterator = new HistoryIterableDecisionTaskIterator(workflowExecution, history);
taskHandler = new AsyncDecisionTaskHandler(ff, childWorkflowIdHandler);
}
public WorkflowReplayer(Iterable<HistoryEvent> history, WorkflowExecution workflowExecution,
WorkflowDefinitionFactoryFactory workflowDefinitionFactoryFactory)
throws InstantiationException, IllegalAccessException {
this(history, workflowExecution, workflowDefinitionFactoryFactory, null);
}
public WorkflowReplayer(Iterable<HistoryEvent> history, WorkflowExecution workflowExecution,
WorkflowDefinitionFactoryFactory workflowDefinitionFactoryFactory, ChildWorkflowIdHandler childWorkflowIdHandler)
throws InstantiationException, IllegalAccessException {
taskIterator = new HistoryIterableDecisionTaskIterator(workflowExecution, history);
taskHandler = new AsyncDecisionTaskHandler(workflowDefinitionFactoryFactory, childWorkflowIdHandler);
}
public WorkflowReplayer(String historyEvents, WorkflowExecution workflowExecution,
Class<T> workflowImplementationType) throws InstantiationException, IllegalAccessException, IOException {
this(historyEvents, workflowExecution, workflowImplementationType, false);
}
public WorkflowReplayer(String historyEvents, WorkflowExecution workflowExecution,
Class<T> workflowImplementationType, boolean skipFailedCheck) throws InstantiationException, IllegalAccessException, IOException {
this(historyEvents, workflowExecution, workflowImplementationType, skipFailedCheck, null);
}
public WorkflowReplayer(String historyEvents, WorkflowExecution workflowExecution,
Class<T> workflowImplementationType, boolean skipFailedCheck, ChildWorkflowIdHandler childWorkflowIdHandler) throws InstantiationException, IllegalAccessException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(HistoryEvent.class, TimeStampMixin.class);
ObjectReader reader = mapper.readerFor(new TypeReference<List<HistoryEvent>>() {}).withRootName("events");
List<HistoryEvent> history = reader.readValue(historyEvents);
POJOWorkflowDefinitionFactoryFactory ff = new POJOWorkflowDefinitionFactoryFactory();
ff.addWorkflowImplementationType(workflowImplementationType);
taskIterator = new HistoryIterableDecisionTaskIterator(workflowExecution, history);
taskHandler = new AsyncDecisionTaskHandler(ff, skipFailedCheck, childWorkflowIdHandler);
}
public WorkflowReplayer(String historyEvents, WorkflowExecution workflowExecution, final T workflowImplementation)
throws InstantiationException, IllegalAccessException, IOException {
this(historyEvents, workflowExecution, workflowImplementation, null);
}
public WorkflowReplayer(String historyEvents, WorkflowExecution workflowExecution, final T workflowImplementation, ChildWorkflowIdHandler childWorkflowIdHandler)
throws InstantiationException, IllegalAccessException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(HistoryEvent.class, TimeStampMixin.class);
ObjectReader reader = mapper.readerFor(new TypeReference<List<HistoryEvent>>() {}).withRootName("events");
List<HistoryEvent> history = reader.readValue(historyEvents);
WorkflowDefinitionFactoryFactory ff = new WorkflowReplayerPOJOFactoryFactory(workflowImplementation);
taskIterator = new HistoryIterableDecisionTaskIterator(workflowExecution, history);
taskHandler = new AsyncDecisionTaskHandler(ff, childWorkflowIdHandler);
}
public WorkflowReplayer(String historyEvents, WorkflowExecution workflowExecution,
WorkflowDefinitionFactoryFactory workflowDefinitionFactoryFactory) throws IOException {
this(historyEvents, workflowExecution, workflowDefinitionFactoryFactory, null);
}
public WorkflowReplayer(String historyEvents, WorkflowExecution workflowExecution,
WorkflowDefinitionFactoryFactory workflowDefinitionFactoryFactory, ChildWorkflowIdHandler childWorkflowIdHandler) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(HistoryEvent.class, TimeStampMixin.class);
ObjectReader reader = mapper.readerFor(new TypeReference<List<HistoryEvent>>() {}).withRootName("events");
List<HistoryEvent> history = reader.readValue(historyEvents);
taskIterator = new HistoryIterableDecisionTaskIterator(workflowExecution, history);
taskHandler = new AsyncDecisionTaskHandler(workflowDefinitionFactoryFactory, childWorkflowIdHandler);
}
public WorkflowReplayer(Iterator<DecisionTask> decisionTasks, Class<T> workflowImplementationType)
throws InstantiationException, IllegalAccessException {
this(decisionTasks, workflowImplementationType, null);
}
public WorkflowReplayer(Iterator<DecisionTask> decisionTasks, Class<T> workflowImplementationType, ChildWorkflowIdHandler childWorkflowIdHandler)
throws InstantiationException, IllegalAccessException {
POJOWorkflowDefinitionFactoryFactory ff = new POJOWorkflowDefinitionFactoryFactory();
ff.addWorkflowImplementationType(workflowImplementationType);
taskIterator = decisionTasks;
taskHandler = new AsyncDecisionTaskHandler(ff, childWorkflowIdHandler);
}
public WorkflowReplayer(Iterator<DecisionTask> decisionTasks, final T workflowImplementation)
throws InstantiationException, IllegalAccessException {
this(decisionTasks, workflowImplementation, null);
}
public WorkflowReplayer(Iterator<DecisionTask> decisionTasks, final T workflowImplementation, ChildWorkflowIdHandler childWorkflowIdHandler)
throws InstantiationException, IllegalAccessException {
WorkflowDefinitionFactoryFactory ff = new WorkflowReplayerPOJOFactoryFactory(workflowImplementation);
taskIterator = decisionTasks;
taskHandler = new AsyncDecisionTaskHandler(ff, childWorkflowIdHandler);
}
public WorkflowReplayer(Iterator<DecisionTask> decisionTasks,
WorkflowDefinitionFactoryFactory workflowDefinitionFactoryFactory)
throws InstantiationException, IllegalAccessException {
this(decisionTasks, workflowDefinitionFactoryFactory, null);
}
public WorkflowReplayer(Iterator<DecisionTask> decisionTasks,
WorkflowDefinitionFactoryFactory workflowDefinitionFactoryFactory, ChildWorkflowIdHandler childWorkflowIdHandler)
throws InstantiationException, IllegalAccessException {
taskIterator = decisionTasks;
taskHandler = new AsyncDecisionTaskHandler(workflowDefinitionFactoryFactory, childWorkflowIdHandler);
}
public int getReplayUpToEventId() {
return replayUpToEventId;
}
/**
* The replay stops at the event with the given eventId. Default is 0.
*
* @param replayUpToEventId
* 0 means the whole history.
*/
public void setReplayUpToEventId(int replayUpToEventId) {
this.replayUpToEventId = replayUpToEventId;
}
public RespondDecisionTaskCompletedRequest replay() throws Exception {
checkReplayed();
return taskHandler.handleDecisionTask(taskIterator);
}
@SuppressWarnings("unchecked")
public T loadWorkflow() throws Exception {
checkReplayed();
WorkflowDefinition definition = taskHandler.loadWorkflowThroughReplay(taskIterator);
POJOWorkflowDefinition pojoDefinition = (POJOWorkflowDefinition) definition;
return (T) pojoDefinition.getImplementationInstance();
}
public List<AsyncTaskInfo> getAsynchronousThreadDump() throws Exception {
checkReplayed();
return taskHandler.getAsynchronousThreadDump(taskIterator);
}
public String getAsynchronousThreadDumpAsString() throws Exception {
checkReplayed();
return taskHandler.getAsynchronousThreadDumpAsString(taskIterator);
}
private void checkReplayed() {
if (!replayed.compareAndSet(false, true)) {
throw new IllegalStateException("WorkflowReplayer instance can be used only once.");
}
}
}
| 3,442 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowClientExternalBase.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.util.Map;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClientExternal;
import com.amazonaws.services.simpleworkflow.model.ChildPolicy;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
public abstract class WorkflowClientExternalBase implements WorkflowClientExternal {
private static boolean BOOLEAN_DEFAULT = false;
private static byte BYTE_DEFAULT = 0;
private static char CHARACTER_DEFAULT = '\u0000';
private static short SHORT_DEFAULT = 0;
private static int INTEGER_DEFAULT = 0;
private static long LONG_DEFAULT = 0L;
private static float FLOAT_DEFAULT = 0.0f;
private static double DOUBLE_DEFAULT = 0.0d;
protected final DynamicWorkflowClientExternal dynamicWorkflowClient;
public WorkflowClientExternalBase(WorkflowExecution workflowExecution, WorkflowType workflowType,
StartWorkflowOptions options, DataConverter dataConverter, GenericWorkflowClientExternal genericClient) {
this.dynamicWorkflowClient = new DynamicWorkflowClientExternalImpl(workflowExecution, workflowType, options,
dataConverter, genericClient);
}
@Override
public void requestCancelWorkflowExecution() {
dynamicWorkflowClient.requestCancelWorkflowExecution();
}
@Override
public void terminateWorkflowExecution(String reason, String details, ChildPolicy childPolicy) {
dynamicWorkflowClient.terminateWorkflowExecution(reason, details, childPolicy);
}
@Override
public DataConverter getDataConverter() {
return dynamicWorkflowClient.getDataConverter();
}
@Override
public StartWorkflowOptions getSchedulingOptions() {
return dynamicWorkflowClient.getSchedulingOptions();
}
@Override
public GenericWorkflowClientExternal getGenericClient() {
return dynamicWorkflowClient.getGenericClient();
}
@Override
public WorkflowExecution getWorkflowExecution() {
return dynamicWorkflowClient.getWorkflowExecution();
}
@Override
public WorkflowType getWorkflowType() {
return dynamicWorkflowClient.getWorkflowType();
}
public Map<String, Integer> getImplementationVersions() {
return dynamicWorkflowClient.getImplementationVersions();
}
protected void startWorkflowExecution(Object[] arguments, StartWorkflowOptions startOptionsOverride) {
dynamicWorkflowClient.startWorkflowExecution(arguments, startOptionsOverride);
}
protected void startWorkflowExecution(Object[] arguments) {
dynamicWorkflowClient.startWorkflowExecution(arguments);
}
protected void signalWorkflowExecution(String signalName, Object[] arguments) {
dynamicWorkflowClient.signalWorkflowExecution(signalName, arguments);
}
@SuppressWarnings({ "unchecked" })
protected<T> T defaultPrimitiveValue(Class<T> clazz) {
Object returnValue = null;
if (clazz.equals(Boolean.TYPE)) {
returnValue = BOOLEAN_DEFAULT;
} else if (clazz.equals(Byte.TYPE)) {
returnValue = BYTE_DEFAULT;
} else if (clazz.equals(Character.TYPE)) {
returnValue = CHARACTER_DEFAULT;
} else if (clazz.equals(Short.TYPE)) {
returnValue = SHORT_DEFAULT;
} else if (clazz.equals(Integer.TYPE)) {
returnValue = INTEGER_DEFAULT;
} else if (clazz.equals(Long.TYPE)) {
returnValue = LONG_DEFAULT;
} else if (clazz.equals(Float.TYPE)) {
returnValue = FLOAT_DEFAULT;
} else if (clazz.equals(Double.TYPE)) {
returnValue = DOUBLE_DEFAULT;
} else {
throw new IllegalArgumentException("Type not supported: " + clazz);
}
return (T)returnValue;
}
}
| 3,443 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowSelfClientBase.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClient;
public abstract class WorkflowSelfClientBase implements WorkflowSelfClient {
protected DataConverter dataConverter;
protected StartWorkflowOptions schedulingOptions;
protected GenericWorkflowClient genericClient;
protected final DecisionContextProvider decisionContextProvider = new DecisionContextProviderImpl();
public WorkflowSelfClientBase(GenericWorkflowClient genericClient,
DataConverter dataConverter, StartWorkflowOptions schedulingOptions) {
this.genericClient = genericClient;
if (dataConverter == null) {
this.dataConverter = new JsonDataConverter();
}
else {
this.dataConverter = dataConverter;
}
if (schedulingOptions == null) {
this.schedulingOptions = new StartWorkflowOptions();
}
else {
this.schedulingOptions = schedulingOptions;
}
}
@Override
public DataConverter getDataConverter() {
return dataConverter;
}
@Override
public void setDataConverter(DataConverter converter) {
this.dataConverter = converter;
}
@Override
public StartWorkflowOptions getSchedulingOptions() {
return schedulingOptions;
}
@Override
public void setSchedulingOptions(StartWorkflowOptions schedulingOptions) {
this.schedulingOptions = schedulingOptions;
}
@Override
public GenericWorkflowClient getGenericClient() {
return genericClient;
}
@Override
public void setGenericClient(GenericWorkflowClient genericClient) {
this.genericClient = genericClient;
}
}
| 3,444 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ActivityTaskFailedException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
/**
* Exception used to communicate failure of remote activity.
*/
@SuppressWarnings("serial")
public class ActivityTaskFailedException extends ActivityTaskException {
private String details;
public ActivityTaskFailedException(String message, Throwable cause) {
super(message, cause);
}
public ActivityTaskFailedException(String message) {
super(message);
}
public ActivityTaskFailedException(long eventId, ActivityType activityType, String activityId, String reason, String details) {
super(reason, eventId, activityType, activityId);
this.details = details;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
| 3,445 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowClientFactoryExternalBase.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClientExternal;
import com.amazonaws.services.simpleworkflow.flow.worker.GenericWorkflowClientExternalImpl;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
public abstract class WorkflowClientFactoryExternalBase<T> implements WorkflowClientFactoryExternal<T> {
private GenericWorkflowClientExternal genericClient;
private DataConverter dataConverter = new com.amazonaws.services.simpleworkflow.flow.JsonDataConverter();
private StartWorkflowOptions startWorkflowOptions = new StartWorkflowOptions();
public WorkflowClientFactoryExternalBase(AmazonSimpleWorkflow service, String domain) {
this(new GenericWorkflowClientExternalImpl(service, domain));
}
public WorkflowClientFactoryExternalBase(AmazonSimpleWorkflow service, String domain, SimpleWorkflowClientConfig config) {
this(new GenericWorkflowClientExternalImpl(service, domain, config));
}
public WorkflowClientFactoryExternalBase() {
this(null);
}
public WorkflowClientFactoryExternalBase(GenericWorkflowClientExternal genericClient) {
this.genericClient = genericClient;
}
@Override
public GenericWorkflowClientExternal getGenericClient() {
return genericClient;
}
public void setGenericClient(GenericWorkflowClientExternal genericClient) {
this.genericClient = genericClient;
}
@Override
public DataConverter getDataConverter() {
return dataConverter;
}
public void setDataConverter(DataConverter dataConverter) {
this.dataConverter = dataConverter;
}
@Override
public StartWorkflowOptions getStartWorkflowOptions() {
return startWorkflowOptions;
}
public void setStartWorkflowOptions(StartWorkflowOptions startWorkflowOptions) {
this.startWorkflowOptions = startWorkflowOptions;
}
@Override
public T getClient() {
checkGenericClient();
String workflowId = genericClient.generateUniqueId();
WorkflowExecution workflowExecution = new WorkflowExecution().withWorkflowId(workflowId);
return getClient(workflowExecution, startWorkflowOptions, dataConverter, genericClient);
}
@Override
public T getClient(String workflowId) {
if (workflowId == null || workflowId.isEmpty()) {
throw new IllegalArgumentException("workflowId");
}
WorkflowExecution workflowExecution = new WorkflowExecution().withWorkflowId(workflowId);
return getClient(workflowExecution, startWorkflowOptions, dataConverter, genericClient);
}
@Override
public T getClient(WorkflowExecution workflowExecution) {
return getClient(workflowExecution, startWorkflowOptions, dataConverter, genericClient);
}
@Override
public T getClient(WorkflowExecution workflowExecution, StartWorkflowOptions options) {
return getClient(workflowExecution, options, dataConverter, genericClient);
}
@Override
public T getClient(WorkflowExecution workflowExecution, StartWorkflowOptions options, DataConverter dataConverter) {
return getClient(workflowExecution, options, dataConverter, genericClient);
}
@Override
public T getClient(WorkflowExecution workflowExecution, StartWorkflowOptions options, DataConverter dataConverter,
GenericWorkflowClientExternal genericClient) {
checkGenericClient();
return createClientInstance(workflowExecution, options, dataConverter, genericClient);
}
private void checkGenericClient() {
if (genericClient == null) {
throw new IllegalStateException("The required property genericClient is null. "
+ "It could be caused by instantiating the factory through the default constructor instead of the one "
+ "that takes service and domain arguments.");
}
}
protected abstract T createClientInstance(WorkflowExecution workflowExecution, StartWorkflowOptions options,
DataConverter dataConverter, GenericWorkflowClientExternal genericClient);
}
| 3,446 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ActivityExecutionContextProviderImpl.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.worker.CurrentActivityExecutionContext;
/**
* The default implementation of the ActivityExecutionContextProvider. Can be
* shared across any number of activity implementation instances.
*
* @author fateev
*/
public class ActivityExecutionContextProviderImpl implements ActivityExecutionContextProvider {
@Override
public ActivityExecutionContext getActivityExecutionContext() {
return CurrentActivityExecutionContext.get();
}
}
| 3,447 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DynamicWorkflowClientExternal.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;
public interface DynamicWorkflowClientExternal extends WorkflowClientExternal {
void startWorkflowExecution(Object[] arguments, StartWorkflowOptions startOptionsOverride);
void startWorkflowExecution(Object[] arguments);
void signalWorkflowExecution(String signalName, Object[] arguments);
<T> T getWorkflowExecutionState(Class<T> returnType) throws Throwable;
}
| 3,448 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowClientExternal.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.util.Map;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClientExternal;
import com.amazonaws.services.simpleworkflow.model.ChildPolicy;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
public interface WorkflowClientExternal {
public void requestCancelWorkflowExecution();
public void terminateWorkflowExecution(String reason, String details, ChildPolicy childPolicy);
public DataConverter getDataConverter();
public StartWorkflowOptions getSchedulingOptions();
public GenericWorkflowClientExternal getGenericClient();
public WorkflowExecution getWorkflowExecution();
public WorkflowType getWorkflowType();
/**
* @see WorkflowContext#isImplementationVersion(String, int)
*/
public Map<String, Integer> getImplementationVersions();
}
| 3,449 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/JsonDataConverter.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.io.IOException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Implements conversion through Jackson JSON processor. Consult its
* documentation on how to ensure that classes are serializable, configure their
* serialization through annotations and {@link ObjectMapper} parameters.
*
* <p>
* Note that default configuration used by this class includes class name of the
* every serialized value into the produced JSON. It is done to support
* polymorphic types out of the box. But in some cases it might be beneficial to
* disable polymorphic support as it produces much more concise and portable
* output.
*
* @author fateev
*/
public class JsonDataConverter extends DataConverter {
private static final Log log = LogFactory.getLog(JsonDataConverter.class);
protected final ObjectMapper mapper;
/**
* Create instance of the converter that uses ObjectMapper with
* {@link DeserializationFeature#FAIL_ON_UNKNOWN_PROPERTIES} set to <code>false</code> and
* default typing set to {@link DefaultTyping#NON_FINAL}.
*/
public JsonDataConverter() {
this(new ObjectMapper());
// ignoring unknown properties makes us more robust to changes in the schema
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// This will allow including type information all non-final types. This allows correct
// serialization/deserialization of generic collections, for example List<MyType>.
mapper.activateDefaultTyping(
BasicPolymorphicTypeValidator.builder()
.allowIfBaseType(Object.class)
.build(),
DefaultTyping.NON_FINAL);
}
/**
* Create instance of the converter that uses {@link ObjectMapper}
* configured externally.
*/
public JsonDataConverter(ObjectMapper mapper) {
this.mapper = mapper;
}
@Override
public String toData(Object value) throws DataConverterException {
try {
return mapper.writeValueAsString(value);
} catch (IOException e) {
log.error("Unable to serialize data", e);
throwDataConverterException(e, value);
}
throw new IllegalStateException("not reachable");
}
private void throwDataConverterException(Throwable e, Object value) {
if (value == null) {
throw new DataConverterException("Failure serializing null value", e);
}
throw new DataConverterException("Failure serializing \"" + value + "\" of type \"" + value.getClass() + "\"", e);
}
@Override
public <T> T fromData(String serialized, Class<T> valueType) throws DataConverterException {
try {
return mapper.readValue(serialized, valueType);
} catch (IOException e) {
log.error("Unable to deserialize data", e);
throw new DataConverterException(e);
}
}
}
| 3,450 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/TimerException.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;
/**
* Exception used to communicate failure of a timer.
*/
@SuppressWarnings("serial")
public abstract class TimerException extends DecisionException {
private String timerId;
private Object createTimerUserContext;
public TimerException(String message) {
super(message);
}
public TimerException(String message, Throwable cause) {
super(message, cause);
}
public TimerException(String message, long eventId, String timerId, Object createTimerUserContext) {
super(message, eventId);
this.timerId = timerId;
this.createTimerUserContext = createTimerUserContext;
}
public String getTimerId() {
return timerId;
}
public void setTimerId(String timerId) {
this.timerId = timerId;
}
public Object getCreateTimerUserContext() {
return createTimerUserContext;
}
public void setCreateTimerUserContext(Object createTimerUserContext) {
this.createTimerUserContext = createTimerUserContext;
}
}
| 3,451 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ManualActivityCompletionClientFactoryImpl.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig;
public class ManualActivityCompletionClientFactoryImpl extends ManualActivityCompletionClientFactory {
private AmazonSimpleWorkflow service;
private DataConverter dataConverter = new JsonDataConverter();
private SimpleWorkflowClientConfig config;
public ManualActivityCompletionClientFactoryImpl(AmazonSimpleWorkflow service) {
this(service, null);
}
public ManualActivityCompletionClientFactoryImpl(AmazonSimpleWorkflow service, SimpleWorkflowClientConfig config) {
this.service = service;
this.config = config;
}
public AmazonSimpleWorkflow getService() {
return service;
}
public void setService(AmazonSimpleWorkflow service) {
this.service = service;
}
public DataConverter getDataConverter() {
return dataConverter;
}
public void setDataConverter(DataConverter dataConverter) {
this.dataConverter = dataConverter;
}
public SimpleWorkflowClientConfig getClientConfig() {
return config;
}
public void setClientConfig(SimpleWorkflowClientConfig config) {
this.config = config;
}
@Override
public ManualActivityCompletionClient getClient(String taskToken) {
if (service == null) {
throw new IllegalStateException("required property service is null");
}
if (dataConverter == null) {
throw new IllegalStateException("required property dataConverter is null");
}
return new ManualActivityCompletionClientImpl(service, taskToken, dataConverter, config);
}
}
| 3,452 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/LambdaFunctionFailedException.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;
@SuppressWarnings("serial")
public class LambdaFunctionFailedException extends LambdaFunctionException {
private String detail;
public LambdaFunctionFailedException(String message, Throwable cause) {
super(message, cause);
}
public LambdaFunctionFailedException(String message) {
super(message);
}
public LambdaFunctionFailedException(long eventId, String name, String id, String detail) {
super("failed", eventId, name, id);
this.detail = detail;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
}
| 3,453 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ScheduleLambdaFunctionFailedException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.ScheduleLambdaFunctionFailedCause;
/**
* Exception used to communicate that lambda function wasn't scheduled due to some
* cause
*/
@SuppressWarnings("serial")
public class ScheduleLambdaFunctionFailedException extends LambdaFunctionException {
private ScheduleLambdaFunctionFailedCause failureCause;
public ScheduleLambdaFunctionFailedException(String message) {
super(message);
}
public ScheduleLambdaFunctionFailedException(String message, Throwable cause) {
super(message, cause);
}
public ScheduleLambdaFunctionFailedException(long eventId, String functionName, String functionId, String cause) {
super(cause, eventId, functionName, functionId);
failureCause = ScheduleLambdaFunctionFailedCause.fromValue(cause);
}
/**
* @return enumeration that contains the cause of the failure
*/
public ScheduleLambdaFunctionFailedCause getFailureCause() {
return failureCause;
}
public void setFailureCause(ScheduleLambdaFunctionFailedCause failureCause) {
this.failureCause = failureCause;
}
}
| 3,454 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/Suspendable.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;
public interface Suspendable {
/**
* Alias to setPollingSuspended(true)
*/
void suspendPolling();
/**
* Alias to setPollingSuspended(false)
*/
void resumePolling();
/**
* Check suspention status
*/
boolean isPollingSuspended();
/**
* If set to <code>true</code> stop making any poll requests. Outstanding long polls still can return
* tasks after this method was called. Setting to <code>false</code> enables polling.
*/
void setPollingSuspended(boolean flag);
}
| 3,455 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/StartLambdaFunctionFailedException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.StartLambdaFunctionFailedCause;
public class StartLambdaFunctionFailedException extends LambdaFunctionException {
private StartLambdaFunctionFailedCause failureCause;
public StartLambdaFunctionFailedException(String message) {
super(message);
}
public StartLambdaFunctionFailedException(String message, Throwable cause) {
super(message, cause);
}
public StartLambdaFunctionFailedException(long eventId, String functionName, String functionId, String cause) {
super(cause, eventId, functionName, functionId);
failureCause = StartLambdaFunctionFailedCause.fromValue(cause);
}
/**
* @return enumeration that contains the cause of the failure
*/
public StartLambdaFunctionFailedCause getFailureCause() {
return failureCause;
}
public void setFailureCause(StartLambdaFunctionFailedCause failureCause) {
this.failureCause = failureCause;
}
}
| 3,456 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowException.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;
/**
* Exception that is thrown from generic workflow implementation to indicate
* that workflow execution should be failed with the given reason and details.
*/
@SuppressWarnings("serial")
public class WorkflowException extends Exception {
private final String details;
public WorkflowException(String reason, String details) {
super(reason);
this.details = details;
}
public String getReason() {
return getMessage();
}
public String getDetails() {
return details;
}
}
| 3,457 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ManualActivityCompletionClient.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.util.concurrent.CancellationException;
public abstract class ManualActivityCompletionClient {
public abstract void complete(Object result);
public abstract void fail(Throwable failure);
public abstract void recordHeartbeat(String details) throws CancellationException;
public abstract void reportCancellation(String details);
}
| 3,458 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DataConverterException.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;
/**
* @see DataConverter
*
* @author fateev
*/
@SuppressWarnings("serial")
public class DataConverterException extends RuntimeException {
private String key;
public DataConverterException() {
}
public DataConverterException(String message, Throwable cause) {
super(message, cause);
}
public DataConverterException(String message) {
super(message);
}
public DataConverterException(Throwable cause) {
super(cause);
}
public void setKey(String key) {
this.key = key;
}
@Override
public String getMessage() {
return super.getMessage() + " when mapping key \"" + key + "\"";
}
}
| 3,459 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/LambdaFunctionException.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;
@SuppressWarnings("serial")
public class LambdaFunctionException extends DecisionException {
private String functionName;
private String functionId;
public LambdaFunctionException(String message) {
super(message);
}
public LambdaFunctionException(String message, Throwable cause) {
super(message, cause);
}
public LambdaFunctionException(String message, long eventId, String name, String id) {
super(message + " for functionId=\"" + id + "\" of functionName=" + name, eventId);
this.functionName = name;
this.functionId = id;
}
public String getFunctionName() {
return functionName;
}
public void setFunctionName(String functionName) {
this.functionName = functionName;
}
public String getFunctionId() {
return functionId;
}
public void setFunctionId(String functionId) {
this.functionId = functionId;
}
}
| 3,460 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/StartChildWorkflowFailedException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.StartChildWorkflowExecutionFailedCause;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
@SuppressWarnings("serial")
public class StartChildWorkflowFailedException extends ChildWorkflowException {
private StartChildWorkflowExecutionFailedCause failureCause;
public StartChildWorkflowFailedException(String message) {
super(message);
}
public StartChildWorkflowFailedException(String message, Throwable cause) {
super(message, cause);
}
public StartChildWorkflowFailedException(long eventId, WorkflowExecution workflowExecution, WorkflowType workflowType,
String cause) {
super(cause, eventId, workflowExecution, workflowType);
this.failureCause = StartChildWorkflowExecutionFailedCause.fromValue(cause);
}
/**
* @return enumeration that contains the cause of the failure
*/
public StartChildWorkflowExecutionFailedCause getFailureCause() {
return failureCause;
}
public void setFailureCause(StartChildWorkflowExecutionFailedCause failureCause) {
this.failureCause = failureCause;
}
}
| 3,461 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DynamicWorkflowClient.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
public interface DynamicWorkflowClient extends WorkflowClient {
<T> Promise<T> startWorkflowExecution(final Promise<Object>[] arguments,
final StartWorkflowOptions startOptionsOverride, final Class<T> returnType, final Promise<?>... waitFor);
<T> Promise<T> startWorkflowExecution(final Object[] arguments, final StartWorkflowOptions startOptionsOverride,
final Class<T> returnType, Promise<?>... waitFor);
void signalWorkflowExecution(String signalName, Object[] arguments, Promise<?>... waitFor);
}
| 3,462 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkerLifecycle.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.util.concurrent.TimeUnit;
public interface WorkerLifecycle {
public abstract void start();
public abstract void shutdown();
public abstract void shutdownNow();
public abstract boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
public abstract boolean gracefulShutdown(long timeout, TimeUnit unit) throws InterruptedException;
public abstract boolean shutdownAndAwaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
}
| 3,463 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ChildWorkflowTimedOutException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
@SuppressWarnings("serial")
public class ChildWorkflowTimedOutException extends ChildWorkflowException {
public ChildWorkflowTimedOutException(String message) {
super(message);
}
public ChildWorkflowTimedOutException(String message, Throwable cause) {
super(message, cause);
}
public ChildWorkflowTimedOutException(long eventId, WorkflowExecution workflowExecution, WorkflowType workflowType) {
super("Time Out", eventId, workflowExecution, workflowType);
}
}
| 3,464 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/StartWorkflowOptions.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.util.List;
import com.amazonaws.services.simpleworkflow.model.ChildPolicy;
public class StartWorkflowOptions {
private Long executionStartToCloseTimeoutSeconds;
private Long taskStartToCloseTimeoutSeconds;
private List<String> tagList;
private String taskList;
private Integer taskPriority;
private String lambdaRole;
private ChildPolicy childPolicy;
public ChildPolicy getChildPolicy() {
return childPolicy;
}
public void setChildPolicy(ChildPolicy childPolicy) {
this.childPolicy = childPolicy;
}
public StartWorkflowOptions withChildPolicy(ChildPolicy childPolicy) {
this.childPolicy = childPolicy;
return this;
}
public Long getExecutionStartToCloseTimeoutSeconds() {
return executionStartToCloseTimeoutSeconds;
}
public void setExecutionStartToCloseTimeoutSeconds(Long executionStartToCloseTimeoutSeconds) {
this.executionStartToCloseTimeoutSeconds = executionStartToCloseTimeoutSeconds;
}
public StartWorkflowOptions withExecutionStartToCloseTimeoutSeconds(Long executionStartToCloseTimeoutSeconds) {
this.executionStartToCloseTimeoutSeconds = executionStartToCloseTimeoutSeconds;
return this;
}
public Long getTaskStartToCloseTimeoutSeconds() {
return taskStartToCloseTimeoutSeconds;
}
public void setTaskStartToCloseTimeoutSeconds(Long taskStartToCloseTimeoutSeconds) {
this.taskStartToCloseTimeoutSeconds = taskStartToCloseTimeoutSeconds;
}
public StartWorkflowOptions withTaskStartToCloseTimeoutSeconds(Long taskStartToCloseTimeoutSeconds) {
this.taskStartToCloseTimeoutSeconds = taskStartToCloseTimeoutSeconds;
return this;
}
public List<String> getTagList() {
return tagList;
}
public void setTagList(List<String> tagList) {
this.tagList = tagList;
}
public StartWorkflowOptions withTagList(List<String> tagList) {
this.tagList = tagList;
return this;
}
public String getTaskList() {
return taskList;
}
public void setTaskList(String taskList) {
this.taskList = taskList;
}
public StartWorkflowOptions withTaskList(String taskList) {
this.taskList = taskList;
return this;
}
public Integer getTaskPriority() {
return taskPriority;
}
public void setTaskPriority(Integer taskPriority) {
this.taskPriority = taskPriority;
}
public StartWorkflowOptions withTaskPriority(Integer taskPriority) {
this.taskPriority = taskPriority;
return this;
}
public String getLambdaRole() {
return lambdaRole;
}
public void setLambdaRole(String lambdaRole) {
this.lambdaRole = lambdaRole;
}
public StartWorkflowOptions withLambdaRole(String lambdaRole) {
this.lambdaRole = lambdaRole;
return this;
}
}
| 3,465 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ActivityWorker.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig;
import com.amazonaws.services.simpleworkflow.flow.generic.ActivityImplementation;
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 ActivityWorker implements WorkerBase {
private final GenericActivityWorker genericWorker;
private final POJOActivityImplementationFactory factory;
public ActivityWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll) {
this(service, domain, taskListToPoll, null);
}
public ActivityWorker(AmazonSimpleWorkflow service, String domain, String taskListToPoll, SimpleWorkflowClientConfig config) {
this(new GenericActivityWorker(service, domain, taskListToPoll, config));
}
public ActivityWorker(GenericActivityWorker genericWorker) {
Objects.requireNonNull(genericWorker,"the activity worker is required");
this.genericWorker = genericWorker;
this.factory = new POJOActivityImplementationFactory();
genericWorker.setActivityImplementationFactory(factory);
}
public void setActivitiesImplementations(Iterable<Object> activitiesImplementations)
throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException {
factory.setActivitiesImplementations(activitiesImplementations);
}
public Iterable<Object> getActivitiesImplementations() {
return factory.getActivitiesImplementations();
}
public List<ActivityType> addActivitiesImplementations(Iterable<Object> activitiesImplementations)
throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException {
return factory.addActivitiesImplementations(activitiesImplementations);
}
public List<ActivityType> addActivitiesImplementations(Iterable<Object> activitiesImplementations, DataConverter dataConverter)
throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException {
return factory.addActivitiesImplementations(activitiesImplementations, dataConverter);
}
public List<ActivityType> addActivitiesImplementation(Object activitiesImplementation)
throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException {
return factory.addActivitiesImplementation(activitiesImplementation);
}
public List<ActivityType> addActivitiesImplementation(Object activitiesImplementation, DataConverter converter)
throws InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException {
return factory.addActivitiesImplementation(activitiesImplementation, converter);
}
public Iterable<ActivityType> getActivityTypesToRegister() {
return factory.getActivityTypesToRegister();
}
public ActivityImplementation getActivityImplementation(ActivityType activityType) {
return factory.getActivityImplementation(activityType);
}
public DataConverter getDataConverter() {
return factory.getDataConverter();
}
public void setDataConverter(DataConverter dataConverter) {
factory.setDataConverter(dataConverter);
}
@Override
public boolean shutdownAndAwaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return genericWorker.shutdownAndAwaitTermination(timeout, unit);
}
@Override
public void shutdownNow() {
genericWorker.shutdownNow();
}
@Override
public SimpleWorkflowClientConfig getClientConfig() {
return genericWorker.getClientConfig();
}
@Override
public AmazonSimpleWorkflow getService() {
return genericWorker.getService();
}
@Override
public String getDomain() {
return genericWorker.getDomain();
}
@Override
public boolean isRegisterDomain() {
return genericWorker.isRegisterDomain();
}
@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);
}
@Override
public void setRegisterDomain(boolean registerDomain) {
genericWorker.setRegisterDomain(registerDomain);
}
@Override
public long getDomainRetentionPeriodInDays() {
return genericWorker.getDomainRetentionPeriodInDays();
}
@Override
public void setDomainRetentionPeriodInDays(long days) {
genericWorker.setDomainRetentionPeriodInDays(days);
}
@Override
public String getTaskListToPoll() {
return genericWorker.getTaskListToPoll();
}
@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 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);
}
@Override
public void setDisableTypeRegistrationOnStart(boolean disableTypeRegistrationOnStart) {
genericWorker.setDisableTypeRegistrationOnStart(disableTypeRegistrationOnStart);
}
@Override
public boolean isDisableTypeRegistrationOnStart() {
return genericWorker.isDisableTypeRegistrationOnStart();
}
@Override
public void registerTypesToPoll() {
genericWorker.registerTypesToPoll();
}
@Override
public void start() {
genericWorker.start();
}
@Override
public void shutdown() {
genericWorker.shutdown();
}
@Override
public boolean isRunning() {
return genericWorker.isRunning();
}
@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 String toString() {
return this.getClass().getSimpleName() + "[genericWorker=" + genericWorker + ", factory=" + factory + "]";
}
}
| 3,466 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DynamicClient.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.util.Map;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
import com.amazonaws.services.simpleworkflow.flow.generic.ContinueAsNewWorkflowExecutionParameters;
import com.amazonaws.services.simpleworkflow.flow.generic.ExecuteActivityParameters;
import com.amazonaws.services.simpleworkflow.flow.generic.SignalExternalWorkflowParameters;
import com.amazonaws.services.simpleworkflow.flow.generic.StartChildWorkflowExecutionParameters;
/**
*/
public interface DynamicClient {
/**
* 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 Promise<Map<String, Object>> scheduleActivityTask(final String activity, final String version,
final Promise<Object[]> input);
/**
* 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
* A Value which contains a Map of results returned by the activity
*/
public abstract Promise<Map<String, Object>> scheduleActivityTask(String activity, String version, Object[] input);
/**
* 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
* An object which can be used to cancel the activity or retrieve the Value
* containing the result for 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
* @param converter
* Data converter to use for serialization of input parameters and deserialization of
* output result
* @return
* A Value which contains a Map of results returned by the activity
*/
public abstract Promise<Map<String, Object>> scheduleActivityTask(String activity, String version,
Object[] input, DataConverter converter);
public abstract Promise<String> startChildWorkflow(StartChildWorkflowExecutionParameters parameters);
public abstract Promise<Map<String, Object>> startChildWorkflow(String workflow, String version, Object[] input);
public abstract Promise<Map<String, Object>> startChildWorkflow(String workflow, String version,
Object[] input, DataConverter converter);
public abstract Promise<Map<String, Object>> startChildWorkflow(final String workflow, final String version,
final Promise<Object[]> input);
public abstract Promise<Void> signalWorkflowExecution(SignalExternalWorkflowParameters parameters);
/**
* Start a new generation of the workflow instance.
*
* @param input
* Map containing input parameters to the workflow
*/
public abstract void continueAsNewOnCompletion(Object[] input);
public abstract void continueAsNewOnCompletion(ContinueAsNewWorkflowExecutionParameters parameters);
}
| 3,467 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ChildWorkflowException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
/**
* Exception used to communicate failure of remote activity.
*/
@SuppressWarnings("serial")
public abstract class ChildWorkflowException extends DecisionException {
private WorkflowExecution workflowExecution;
private WorkflowType workflowType;
public ChildWorkflowException(String message) {
super(message);
}
public ChildWorkflowException(String message, Throwable cause) {
super(message, cause);
}
public ChildWorkflowException(String message, long eventId, WorkflowExecution workflowExecution, WorkflowType workflowType) {
super(message + " for workflowExecution=\"" + workflowExecution + "\" of workflowType=" + workflowType, eventId);
this.workflowExecution = workflowExecution;
this.workflowType = workflowType;
}
public WorkflowExecution getWorkflowExecution() {
return workflowExecution;
}
public void setWorkflowExecution(WorkflowExecution workflowExecution) {
this.workflowExecution = workflowExecution;
}
public WorkflowType getWorkflowType() {
return workflowType;
}
public void setWorkflowType(WorkflowType workflowType) {
this.workflowType = workflowType;
}
}
| 3,468 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ChildWorkflowIdHandler.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import java.util.function.Supplier;
public interface ChildWorkflowIdHandler {
/**
* Generate a workflow id for a new child workflow.
*
* @param currentWorkflow The current (i.e. parent) workflow execution
* @param nextId Can be called to get a replay-safe id that is unique in the
* context of the current workflow.
*
* @return A new child workflow id
*/
String generateWorkflowId(WorkflowExecution currentWorkflow, Supplier<String> nextId);
/**
* Extract the child workflow id that was provided when
* making a decision to start a child workflow.
*
* @param childWorkflowId The actual child workflow id
* @return The original requested child workflow id (may be the same as the actual child workflow id)
*/
String extractRequestedWorkflowId(String childWorkflowId);
}
| 3,469 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ManualActivityCompletionClientFactory.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;
public abstract class ManualActivityCompletionClientFactory {
public abstract ManualActivityCompletionClient getClient(String taskToken);
}
| 3,470 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowContext.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.util.List;
import com.amazonaws.services.simpleworkflow.flow.annotations.WorkflowComponentImplementationVersions;
import com.amazonaws.services.simpleworkflow.flow.generic.ContinueAsNewWorkflowExecutionParameters;
import com.amazonaws.services.simpleworkflow.model.ChildPolicy;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
public interface WorkflowContext {
WorkflowExecution getWorkflowExecution();
WorkflowExecution getParentWorkflowExecution();
WorkflowType getWorkflowType();
boolean isCancelRequested();
ContinueAsNewWorkflowExecutionParameters getContinueAsNewOnCompletion();
void setContinueAsNewOnCompletion(ContinueAsNewWorkflowExecutionParameters continueParameters);
List<String> getTagList();
ChildPolicy getChildPolicy();
String getContinuedExecutionRunId();
long getExecutionStartToCloseTimeout();
String getTaskList();
int getTaskPriority();
String getLambdaRole();
/**
* Is the component current version greater or equal to the passed
* parameter? Increases the current version if it is newly executed workflow
* code (not replay) and the version passed as a parameter is bigger then
* the current version.
* <p>
* This method is created to enable workflow updates without changing their
* type version. The code changes should follow the following pattern:
*
* <pre>
* if (workflowContext.isImplementationVersion(COMPONENT_NAME, 5)) {
* // New code path
* }
* else if (workflowContext.isImplementationVersion(COMPONENT_NAME, 4)) {
* // Old version 4 code path
* }
* else if (workflowContext.isImplementationVersion(COMPONENT_NAME, 3)) {
* // Even older version 3 code path
* }
* else {
* // Code path for version 2 and below was already removed
* throw new IncompatibleWorkflowDefinition("Implementation version below 3 is not supported for " + COMPONENT_NAME);
* }
* </pre>
* <p>
* The "old code path" branches are used to reconstruct through replay the
* state of workflows that already executed it. The "new code path" branch
* is executed for workflows that haven't reached it before the update. As
* soon as all workflows for the old code path are closed the condition as
* well as the old path can be removed. Conditions should start from higher
* version and finish with the lowest supported one as
* <code>isVersion</code> returns true for any version that is lower then
* the current one.
* <p>
* <code>componentName</code> parameter links multiple such conditions
* together. All conditions that share the same component value return the
* same result for the same version. In the following example as the first
* call to isVersion happens in the part of the workflow that has already
* executed the second call to isVersion returns <code>false</code> even if
* it is executed for the first time.
*
* <pre>
* if (workflowContext.isImplementationVersion("comp1", 1)) {
* // New code path 1
* }
* else {
* // Old code path 1
* }
*
* // Location of the workflow execution when upgrade was deployed.
*
* if (workflowContext.isImplementationVersion("comp1", 1)) {
* // New code path 2
* }
* else {
* // Old code path 2
* }
* </pre>
* <p>
* If all updates are independent then they should use different component
* names which allows them to take a new code path independently of other
* components.
* <p>
* Use {@link WorkflowComponentImplementationVersions} annotation to specify
* maximum and minimum supported as well as allowed version for each
* component.
* <p>
* Maximum and minimum supported versions define valid range of version
* values that given component used in a workflow implementation supports.
* Call to <code>isImplementationVersion</code> with value out of this range
* causes decision failure. Failed decisions are retried after a configured
* decision task timeout. So "bad deployment" that starts workers that are
* not compatible with currently open workflow histories results in a few
* decision falures, but doesn't affect open workflows correctness. Another
* situation is rolling deployment when both new and old workers are active.
* During such deployment histories processed by the new version fail to be
* processed by the old workers. If such deployment is not very long running
* it might be acceptable to fail and retry (after a timeout) a few
* decisions.
* <p>
* Maximum allowed version enables version upgrades without any decision
* failures. When it is set to a lower value then maximum supported version
* the worklfow implementation takes code path that corresponds to it for
* the newly executed code. When performing replay the newer code path (up
* to the maximum supported version) can be taken. The decision failure free
* upgrades are done by the following steps:
* <ol>
* <li>It is expected that the currently running workers have the same
* allowed and supported versions.</li>
* <li>New workers are deployed with maximum allowed version set to the same
* version as the currently running workers. Even if rolling deployment is
* used no decisions should fail.</li>
* <li>Second deployment of the new workers is done with maximum allowed
* version set to the same as their maximum supported version. To avoid code
* change for the second deployment instead of
* {@link WorkflowComponentImplementationVersions} annotation use
* {@link WorkflowWorker#setMaximumAllowedComponentImplementationVersions(java.util.Map)}
* to specify the maximum allowed version.</li>
* </ol>
*
*
* @param componentName
* name of the versioned component
* @param internalVersion
* internal component version
* @return if the code path of the specified version should be taken.
*/
boolean isImplementationVersion(String componentName, int internalVersion);
/**
* The current version of the component.
*
* @param component
* name of the component to version
* @return <code>null</code> if no version found for the component.
*/
Integer getVersion(String component);
}
| 3,471 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DecisionContextProviderImpl.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.worker.CurrentDecisionContext;
public class DecisionContextProviderImpl implements DecisionContextProvider {
@Override
public DecisionContext getDecisionContext() {
return CurrentDecisionContext.get();
}
}
| 3,472 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DataConverter.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;
/**
* Used by the framework to serialize/deserialize method parameters that need to
* be sent over the wire.
*
* @author fateev
*/
public abstract class DataConverter {
/**
* Implements conversion of the single value.
*
* @param value
* Java value to convert to String.
* @return converted value
* @throws DataConverterException
* if conversion of the value passed as parameter failed for any
* reason.
*/
public abstract String toData(Object value) throws DataConverterException;
/**
* Implements conversion of the single value.
* @param content
* Simple Workflow Data value to convert to a Java object.
* @return converted Java object
* @throws DataConverterException
* if conversion of the data passed as parameter failed for any
* reason.
*/
public abstract <T> T fromData(String content, Class<T> valueType) throws DataConverterException;
}
| 3,473 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DynamicActivitiesClientImpl.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.core.Functor;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
import com.amazonaws.services.simpleworkflow.flow.core.Settable;
import com.amazonaws.services.simpleworkflow.flow.core.TryCatchFinally;
import com.amazonaws.services.simpleworkflow.flow.generic.ExecuteActivityParameters;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericActivityClient;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
public class DynamicActivitiesClientImpl implements DynamicActivitiesClient {
protected DataConverter dataConverter;
protected ActivitySchedulingOptions schedulingOptions;
protected GenericActivityClient genericClient;
protected DecisionContextProvider decisionContextProvider = new DecisionContextProviderImpl();
public DynamicActivitiesClientImpl() {
this(null, null, null);
}
public DynamicActivitiesClientImpl(ActivitySchedulingOptions schedulingOptions) {
this(schedulingOptions, null, null);
}
public DynamicActivitiesClientImpl(ActivitySchedulingOptions schedulingOptions, DataConverter dataConverter) {
this(schedulingOptions, dataConverter, null);
}
public DynamicActivitiesClientImpl(ActivitySchedulingOptions schedulingOptions, DataConverter dataConverter,
GenericActivityClient genericClient) {
this.genericClient = genericClient;
if (schedulingOptions == null) {
this.schedulingOptions = new ActivitySchedulingOptions();
}
else {
this.schedulingOptions = schedulingOptions;
}
if (dataConverter == null) {
this.dataConverter = new JsonDataConverter();
}
else {
this.dataConverter = dataConverter;
}
}
@Override
public DataConverter getDataConverter() {
return dataConverter;
}
public void setDataConverter(DataConverter dataConverter) {
this.dataConverter = dataConverter;
}
@Override
public ActivitySchedulingOptions getSchedulingOptions() {
return schedulingOptions;
}
public void setSchedulingOptions(ActivitySchedulingOptions schedulingOptions) {
this.schedulingOptions = schedulingOptions;
}
@Override
public GenericActivityClient getGenericClient() {
return genericClient;
}
public void setGenericClient(GenericActivityClient genericClient) {
this.genericClient = genericClient;
}
public <T> Promise<T> scheduleActivity(final ActivityType activityType, final Promise<?>[] arguments,
final ActivitySchedulingOptions optionsOverride, final Class<T> returnType, final Promise<?>... waitFor) {
return new Functor<T>(arguments) {
@Override
protected Promise<T> doExecute() throws Throwable {
Object[] input = new Object[arguments.length];
for (int i = 0; i < arguments.length; i++) {
Promise<?> argument = arguments[i];
input[i] = argument.get();
}
return scheduleActivity(activityType, input, optionsOverride, returnType, waitFor);
}
};
}
public <T> Promise<T> scheduleActivity(final ActivityType activityType, final Object[] arguments,
final ActivitySchedulingOptions optionsOverride, final Class<T> returnType, Promise<?>... waitFor) {
final Settable<T> result = new Settable<T>();
new TryCatchFinally(waitFor) {
Promise<String> stringOutput;
@Override
protected void doTry() throws Throwable {
ExecuteActivityParameters parameters = new ExecuteActivityParameters();
parameters.setActivityType(activityType);
final String stringInput = dataConverter.toData(arguments);
parameters.setInput(stringInput);
final ExecuteActivityParameters _scheduleParameters_ = parameters.createExecuteActivityParametersFromOptions(
schedulingOptions, optionsOverride);
GenericActivityClient client;
if (genericClient == null) {
client = decisionContextProvider.getDecisionContext().getActivityClient();
} else {
client = genericClient;
}
stringOutput = client.scheduleActivityTask(_scheduleParameters_);
result.setDescription(stringOutput.getDescription());
}
@Override
protected void doCatch(Throwable e) throws Throwable {
if (e instanceof ActivityTaskFailedException) {
ActivityTaskFailedException taskFailedException = (ActivityTaskFailedException) e;
try {
String details = taskFailedException.getDetails();
if (details != null) {
Throwable cause = dataConverter.fromData(details, Throwable.class);
if (cause != null && taskFailedException.getCause() == null) {
taskFailedException.initCause(cause);
}
}
}
catch (DataConverterException dataConverterException) {
if (dataConverterException.getCause() == null) {
dataConverterException.initCause(taskFailedException);
}
throw dataConverterException;
}
}
throw e;
}
@Override
protected void doFinally() throws Throwable {
if (stringOutput != null && stringOutput.isReady()) {
if (returnType.equals(Void.class)) {
result.set(null);
}
else {
T output = dataConverter.fromData(stringOutput.get(), returnType);
result.set(output);
}
}
}
};
return result;
}
}
| 3,474 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowClientFactoryExternal.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClientExternal;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
public interface WorkflowClientFactoryExternal<T> {
GenericWorkflowClientExternal getGenericClient();
DataConverter getDataConverter();
StartWorkflowOptions getStartWorkflowOptions();
T getClient();
T getClient(String workflowId);
T getClient(WorkflowExecution workflowExecution);
T getClient(WorkflowExecution workflowExecution, StartWorkflowOptions options);
T getClient(WorkflowExecution workflowExecution, StartWorkflowOptions options, DataConverter dataConverter);
T getClient(WorkflowExecution workflowExecution, StartWorkflowOptions options, DataConverter dataConverter,
GenericWorkflowClientExternal genericClient);
}
| 3,475 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ActivitySchedulingOptions.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;
public class ActivitySchedulingOptions {
private Long heartbeatTimeoutSeconds;
private Long scheduleToCloseTimeoutSeconds;
private Long scheduleToStartTimeoutSeconds;
private Long startToCloseTimeoutSeconds;
private String taskList;
private Integer taskPriority;
public Long getHeartbeatTimeoutSeconds() {
return heartbeatTimeoutSeconds;
}
public void setHeartbeatTimeoutSeconds(Long heartbeatTimeoutSeconds) {
this.heartbeatTimeoutSeconds = heartbeatTimeoutSeconds;
}
public ActivitySchedulingOptions withHeartbeatTimeoutSeconds(Long heartbeatTimeoutSeconds) {
this.heartbeatTimeoutSeconds = heartbeatTimeoutSeconds;
return this;
}
public Long getScheduleToCloseTimeoutSeconds() {
return scheduleToCloseTimeoutSeconds;
}
public void setScheduleToCloseTimeoutSeconds(Long scheduleToCloseTimeoutSeconds) {
this.scheduleToCloseTimeoutSeconds = scheduleToCloseTimeoutSeconds;
}
public ActivitySchedulingOptions withScheduleToCloseTimeoutSeconds(Long scheduleToCloseTimeoutSeconds) {
this.scheduleToCloseTimeoutSeconds = scheduleToCloseTimeoutSeconds;
return this;
}
public Long getScheduleToStartTimeoutSeconds() {
return scheduleToStartTimeoutSeconds;
}
public void setScheduleToStartTimeoutSeconds(Long scheduleToStartTimeoutSeconds) {
this.scheduleToStartTimeoutSeconds = scheduleToStartTimeoutSeconds;
}
public ActivitySchedulingOptions withScheduleToStartTimeoutSeconds(Long scheduleToStartTimeoutSeconds) {
this.scheduleToStartTimeoutSeconds = scheduleToStartTimeoutSeconds;
return this;
}
public Long getStartToCloseTimeoutSeconds() {
return startToCloseTimeoutSeconds;
}
public void setStartToCloseTimeoutSeconds(Long startToCloseTimeoutSeconds) {
this.startToCloseTimeoutSeconds = startToCloseTimeoutSeconds;
}
public ActivitySchedulingOptions withStartToCloseTimeoutSeconds(Long startToCloseTimeoutSeconds) {
this.startToCloseTimeoutSeconds = startToCloseTimeoutSeconds;
return this;
}
public String getTaskList() {
return taskList;
}
public void setTaskList(String taskList) {
this.taskList = taskList;
}
public ActivitySchedulingOptions withTaskList(String taskList) {
this.taskList = taskList;
return this;
}
public Integer getTaskPriority() {
return taskPriority;
}
public void setTaskPriority(Integer taskPriority) {
this.taskPriority = taskPriority;
}
public ActivitySchedulingOptions withTaskPriority(Integer taskPriority) {
this.taskPriority = taskPriority;
return this;
}
}
| 3,476 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DynamicWorkflowClientImpl.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.core.Functor;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
import com.amazonaws.services.simpleworkflow.flow.core.Settable;
import com.amazonaws.services.simpleworkflow.flow.core.Task;
import com.amazonaws.services.simpleworkflow.flow.core.TryFinally;
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.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
public class DynamicWorkflowClientImpl implements DynamicWorkflowClient {
protected WorkflowType workflowType;
protected GenericWorkflowClient genericClient;
protected StartWorkflowOptions schedulingOptions;
protected DataConverter dataConverter;
protected WorkflowExecution workflowExecution;
protected String requestedWorkflowId;
protected boolean startAttempted;
protected Settable<String> runId = new Settable<String>();
protected DecisionContextProvider decisionContextProvider = new DecisionContextProviderImpl();
public DynamicWorkflowClientImpl() {
this(null, null, null, null, null);
}
public DynamicWorkflowClientImpl(WorkflowExecution workflowExecution) {
this(workflowExecution, null, null, null, null);
}
public DynamicWorkflowClientImpl(WorkflowExecution workflowExecution, WorkflowType workflowType) {
this(workflowExecution, workflowType, null, null, null);
}
public DynamicWorkflowClientImpl(WorkflowExecution workflowExecution, WorkflowType workflowType, StartWorkflowOptions options) {
this(workflowExecution, workflowType, options, null, null);
}
public DynamicWorkflowClientImpl(WorkflowExecution workflowExecution, WorkflowType workflowType,
StartWorkflowOptions options, DataConverter dataConverter) {
this(workflowExecution, workflowType, options, dataConverter, null);
}
public DynamicWorkflowClientImpl(WorkflowExecution workflowExecution, WorkflowType workflowType,
StartWorkflowOptions options, DataConverter dataConverter, GenericWorkflowClient genericClient) {
this.workflowType = workflowType;
this.workflowExecution = workflowExecution;
if (workflowExecution.getRunId() != null) {
this.runId.set(workflowExecution.getRunId());
}
if (dataConverter == null) {
this.dataConverter = new JsonDataConverter();
}
else {
this.dataConverter = dataConverter;
}
this.schedulingOptions = options;
this.genericClient = genericClient;
}
@Override
public DataConverter getDataConverter() {
return dataConverter;
}
@Override
public StartWorkflowOptions getSchedulingOptions() {
return schedulingOptions;
}
@Override
public GenericWorkflowClient getGenericClient() {
return genericClient;
}
@Override
public Promise<String> getRunId() {
return runId;
}
@Override
public WorkflowExecution getWorkflowExecution() {
return workflowExecution;
}
@Override
public WorkflowType getWorkflowType() {
return workflowType;
}
public void setWorkflowType(WorkflowType workflowType) {
this.workflowType = workflowType;
}
public void setGenericClient(GenericWorkflowClient genericClient) {
this.genericClient = genericClient;
}
public void setSchedulingOptions(StartWorkflowOptions schedulingOptions) {
this.schedulingOptions = schedulingOptions;
}
public void setDataConverter(DataConverter dataConverter) {
this.dataConverter = dataConverter;
}
@Override
public void requestCancelWorkflowExecution(Promise<?>... waitFor) {
checkWorkflowExecution();
new Task(waitFor) {
@Override
protected void doExecute() throws Throwable {
GenericWorkflowClient client = getGenericClientToUse();
client.requestCancelWorkflowExecution(workflowExecution);
}
};
}
private void checkWorkflowExecution() {
if (workflowExecution == null) {
throw new IllegalStateException("required property workflowExecution is null");
}
}
public <T> Promise<T> startWorkflowExecution(final Promise<Object>[] arguments,
final StartWorkflowOptions startOptionsOverride, final Class<T> returnType, final Promise<?>... waitFor) {
checkState();
if (runId.isReady()) {
runId = new Settable<String>();
workflowExecution.setRunId(null);
}
return new Functor<T>(arguments) {
@Override
protected Promise<T> doExecute() throws Throwable {
Object[] input = new Object[arguments.length];
for (int i = 0; i < arguments.length; i++) {
Promise<Object> argument = arguments[i];
input[i] = argument.get();
}
return startWorkflowExecution(input, startOptionsOverride, returnType, waitFor);
}
};
}
public <T> Promise<T> startWorkflowExecution(final Object[] arguments, final StartWorkflowOptions startOptionsOverride,
final Class<T> returnType, Promise<?>... waitFor) {
checkState();
final Settable<T> result = new Settable<T>();
if (runId.isReady()) {
runId = new Settable<String>();
workflowExecution.setRunId(null);
}
new TryFinally(waitFor) {
Promise<StartChildWorkflowReply> reply;
@Override
protected void doTry() throws Throwable {
StartChildWorkflowExecutionParameters parameters = new StartChildWorkflowExecutionParameters();
parameters.setWorkflowType(workflowType);
final String convertedArguments = dataConverter.toData(arguments);
parameters.setInput(convertedArguments);
if (!startAttempted) {
parameters.setWorkflowId(workflowExecution.getWorkflowId());
requestedWorkflowId = workflowExecution.getWorkflowId();
startAttempted = true;
} else {
// Subsequent attempts (e.g. on retry) use the same workflow id as the initial attempt
parameters.setWorkflowId(requestedWorkflowId);
workflowExecution.setWorkflowId(requestedWorkflowId);
}
final StartChildWorkflowExecutionParameters startParameters = parameters.createStartChildWorkflowExecutionParametersFromOptions(
schedulingOptions, startOptionsOverride);
GenericWorkflowClient client = getGenericClientToUse();
reply = client.startChildWorkflow(startParameters);
runId.setDescription("runId of " + reply.getDescription());
result.setDescription(reply.getDescription());
new Task(reply) {
@Override
protected void doExecute() throws Throwable {
StartChildWorkflowReply r = reply.get();
if (!runId.isReady()) {
runId.set(r.getRunId());
workflowExecution.setRunId(r.getRunId());
workflowExecution.setWorkflowId(r.getWorkflowId());
}
}
};
}
@Override
protected void doCatch(Throwable e) throws Throwable {
if (e instanceof ChildWorkflowFailedException) {
ChildWorkflowFailedException taskFailedException = (ChildWorkflowFailedException) e;
try {
String details = taskFailedException.getDetails();
if (details != null) {
Throwable cause = dataConverter.fromData(details, Throwable.class);
if (cause != null && taskFailedException.getCause() == null) {
taskFailedException.initCause(cause);
}
}
}
catch (DataConverterException dataConverterException) {
if (dataConverterException.getCause() == null) {
dataConverterException.initCause(taskFailedException);
}
throw dataConverterException;
}
}
throw e;
}
@Override
protected void doFinally() throws Throwable {
if (reply != null && reply.isReady() && reply.get().getResult().isReady()) {
if (returnType.equals(Void.class)) {
result.set(null);
}
else {
T output = dataConverter.fromData(reply.get().getResult().get(), returnType);
result.set(output);
}
}
}
};
return result;
}
@Override
public void signalWorkflowExecution(final String signalName, final Object[] arguments, Promise<?>... waitFor) {
checkWorkflowExecution();
new Task(waitFor) {
@Override
protected void doExecute() throws Throwable {
SignalExternalWorkflowParameters parameters = new SignalExternalWorkflowParameters();
parameters.setSignalName(signalName);
String input = dataConverter.toData(arguments);
parameters.setInput(input);
parameters.setWorkflowId(workflowExecution.getWorkflowId());
parameters.setRunId(workflowExecution.getRunId());
GenericWorkflowClient client = getGenericClientToUse();
client.signalWorkflowExecution(parameters);
}
};
}
private void checkState() {
if (workflowType == null) {
throw new IllegalStateException("required property workflowType is null");
}
checkWorkflowExecution();
}
private GenericWorkflowClient getGenericClientToUse() {
GenericWorkflowClient client;
if (genericClient == null) {
client = decisionContextProvider.getDecisionContext().getWorkflowClient();
} else {
client = genericClient;
}
return client;
}
}
| 3,477 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowClient.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClient;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
public interface WorkflowClient {
WorkflowExecution getWorkflowExecution();
Promise<String> getRunId();
GenericWorkflowClient getGenericClient();
StartWorkflowOptions getSchedulingOptions();
DataConverter getDataConverter();
void requestCancelWorkflowExecution(Promise<?>... waitFor);
WorkflowType getWorkflowType();
}
| 3,478 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DecisionContext.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericActivityClient;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClient;
import com.amazonaws.services.simpleworkflow.flow.worker.LambdaFunctionClient;
/**
* Represents the context for decider. Should only be used within the scope of
* workflow definition code, meaning any code which is not part of activity
* implementations.
*/
public abstract class DecisionContext {
public abstract GenericActivityClient getActivityClient();
public abstract GenericWorkflowClient getWorkflowClient();
public abstract WorkflowClock getWorkflowClock();
public abstract WorkflowContext getWorkflowContext();
public abstract LambdaFunctionClient getLambdaFunctionClient();
}
| 3,479 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DecisionContextProvider.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;
public interface DecisionContextProvider {
public DecisionContext getDecisionContext();
}
| 3,480 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowTypeRegistrationOptions.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.ChildPolicy;
public class WorkflowTypeRegistrationOptions {
private ChildPolicy defaultChildPolicy = ChildPolicy.TERMINATE;
private long defaultExecutionStartToCloseTimeoutSeconds;
private long defaultTaskStartToCloseTimeoutSeconds;
private String defaultTaskList;
private String description;
private int defaultTaskPriority;
private String defaultLambdaRole;
public ChildPolicy getDefaultChildPolicy() {
return defaultChildPolicy;
}
public void setDefaultChildPolicy(ChildPolicy defaultChildPolicy) {
this.defaultChildPolicy = defaultChildPolicy;
}
public long getDefaultExecutionStartToCloseTimeoutSeconds() {
return defaultExecutionStartToCloseTimeoutSeconds;
}
public void setDefaultExecutionStartToCloseTimeoutSeconds(long defaultExecutionStartToCloseTimeoutSeconds) {
this.defaultExecutionStartToCloseTimeoutSeconds = defaultExecutionStartToCloseTimeoutSeconds;
}
/**
* Default Workflow TaskList. <code>null</code> means to use {@link WorkflowWorker} task list.
* TaskList with "NO_DEFAULT_TASK_LIST" name means that no default task list is registered.
* @return
*/
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 getDefaultTaskStartToCloseTimeoutSeconds() {
return defaultTaskStartToCloseTimeoutSeconds;
}
public void setDefaultTaskStartToCloseTimeoutSeconds(long defaultTaskStartToCloseTimeoutSeconds) {
this.defaultTaskStartToCloseTimeoutSeconds = defaultTaskStartToCloseTimeoutSeconds;
}
public int getDefaultTaskPriority() {
return defaultTaskPriority;
}
public void setDefaultTaskPriority(int defaultTaskPriority) {
this.defaultTaskPriority = defaultTaskPriority;
}
public String getDefaultLambdaRole() {
return defaultLambdaRole;
}
public void setDefaultLambdaRole(String defaultLambdaRole) {
this.defaultLambdaRole = defaultLambdaRole;
}
@Override
public String toString() {
return "WorkflowVersionRegistrationOptions [defaultTaskList=" + defaultTaskList
+ ", defaultExecutionStartToCloseTimeoutSeconds=" + defaultExecutionStartToCloseTimeoutSeconds
+ ", defaultTaskList=" + defaultTaskList
+ ", description=" + description
+ ", defaultTaskStartToCloseTimeoutSeconds=" + defaultTaskStartToCloseTimeoutSeconds
+ ", defaultTaskPriority=" + defaultTaskPriority
+ ", defaultLambdaRole=" + defaultLambdaRole
+ "]";
}
}
| 3,481 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ChildWorkflowTerminatedException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
@SuppressWarnings("serial")
public class ChildWorkflowTerminatedException extends ChildWorkflowException {
public ChildWorkflowTerminatedException(String message) {
super(message);
}
public ChildWorkflowTerminatedException(String message, Throwable cause) {
super(message, cause);
}
public ChildWorkflowTerminatedException(long eventId, WorkflowExecution workflowExecution, WorkflowType workflowType) {
super("Terminate", eventId, workflowExecution, workflowType);
}
}
| 3,482 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ActivityFailureException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.generic.ActivityImplementation;
/**
* This exception is expected to be thrown from
* {@link ActivityImplementation#execute(ActivityExecutionContext)}
* as it contains details property in the format that the activity client code
* in the decider understands.
* <p>
* It is not expected to be thrown by the application level code.
*
* @author fateev
*/
@SuppressWarnings("serial")
public class ActivityFailureException extends RuntimeException {
private String details;
public ActivityFailureException(String reason) {
super(reason);
}
/**
* Construct exception with given arguments.
*
* @param reason
* the detail message of the original exception
* @param details
* application specific failure details
*/
public ActivityFailureException(String reason, String details) {
this(reason);
this.details = details;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getReason() {
return getMessage();
}
@Override
public String toString() {
return super.toString() + " : " + getDetails();
}
}
| 3,483 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowClientBase.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClient;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
public abstract class WorkflowClientBase implements WorkflowClient {
protected final DynamicWorkflowClientImpl dynamicWorkflowClient;
protected WorkflowClientBase(WorkflowExecution workflowExecution, WorkflowType workflowType, StartWorkflowOptions options,
DataConverter dataConverter, GenericWorkflowClient genericClient) {
dynamicWorkflowClient = new DynamicWorkflowClientImpl(workflowExecution, workflowType, options, dataConverter,
genericClient);
}
@Override
public DataConverter getDataConverter() {
return dynamicWorkflowClient.getDataConverter();
}
@Override
public StartWorkflowOptions getSchedulingOptions() {
return dynamicWorkflowClient.getSchedulingOptions();
}
@Override
public GenericWorkflowClient getGenericClient() {
return dynamicWorkflowClient.getGenericClient();
}
@Override
public Promise<String> getRunId() {
return dynamicWorkflowClient.getRunId();
}
public WorkflowExecution getWorkflowExecution() {
return dynamicWorkflowClient.getWorkflowExecution();
}
@Override
public WorkflowType getWorkflowType() {
return dynamicWorkflowClient.getWorkflowType();
}
public void requestCancelWorkflowExecution(Promise<?>... waitFor) {
dynamicWorkflowClient.requestCancelWorkflowExecution(waitFor);
}
protected <T> Promise<T> startWorkflowExecution(Promise<Object>[] arguments, StartWorkflowOptions startOptionsOverride,
Class<T> returnType, Promise<?>... waitFor) {
return dynamicWorkflowClient.startWorkflowExecution(arguments, startOptionsOverride, returnType, waitFor);
}
protected <T> Promise<T> startWorkflowExecution(Object[] arguments, StartWorkflowOptions startOptionsOverride,
Class<T> returnType, Promise<?>... waitFor) {
return dynamicWorkflowClient.startWorkflowExecution(arguments, startOptionsOverride, returnType, waitFor);
}
protected void signalWorkflowExecution(String signalName, Object[] arguments, Promise<?>... waitFor) {
dynamicWorkflowClient.signalWorkflowExecution(signalName, arguments, waitFor);
}
}
| 3,484 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DynamicActivitiesClient.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
public interface DynamicActivitiesClient extends ActivitiesClient {
<T> Promise<T> scheduleActivity(final ActivityType activityType, final Promise<?>[] arguments,
final ActivitySchedulingOptions optionsOverride, final Class<T> returnType, final Promise<?>... waitFor);
<T> Promise<T> scheduleActivity(final ActivityType activityType, final Object[] arguments,
final ActivitySchedulingOptions optionsOverride, final Class<T> returnType, Promise<?>... waitFor);
}
| 3,485 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ManualActivityCompletionClientImpl.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.util.concurrent.CancellationException;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
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.model.ActivityTaskStatus;
import com.amazonaws.services.simpleworkflow.model.RecordActivityTaskHeartbeatRequest;
import com.amazonaws.services.simpleworkflow.model.RespondActivityTaskCanceledRequest;
import com.amazonaws.services.simpleworkflow.model.RespondActivityTaskCompletedRequest;
import com.amazonaws.services.simpleworkflow.model.RespondActivityTaskFailedRequest;
/**
* TODO: Add exponential retry to manual activity completion the same way it is
* done for other activities
*/
class ManualActivityCompletionClientImpl extends ManualActivityCompletionClient {
private final AmazonSimpleWorkflow service;
private final String taskToken;
private final DataConverter dataConverter;
private SimpleWorkflowClientConfig config;
public ManualActivityCompletionClientImpl(AmazonSimpleWorkflow service, String taskToken, DataConverter dataConverter) {
this(service, taskToken, dataConverter, null);
}
public ManualActivityCompletionClientImpl(AmazonSimpleWorkflow service, String taskToken, DataConverter dataConverter, SimpleWorkflowClientConfig config) {
this.service = service;
this.taskToken = taskToken;
this.dataConverter = dataConverter;
this.config = config;
}
@Override
public void complete(Object result) {
RespondActivityTaskCompletedRequest request = new RespondActivityTaskCompletedRequest();
String convertedResult = dataConverter.toData(result);
request.setResult(convertedResult);
request.setTaskToken(taskToken);
RequestTimeoutHelper.overrideDataPlaneRequestTimeout(request, config);
service.respondActivityTaskCompleted(request);
}
@Override
public void fail(Throwable failure) {
RespondActivityTaskFailedRequest request = new RespondActivityTaskFailedRequest();
String convertedFailure = dataConverter.toData(failure);
request.setReason(WorkflowExecutionUtils.truncateReason(failure.getMessage()));
request.setDetails(convertedFailure);
request.setTaskToken(taskToken);
RequestTimeoutHelper.overrideDataPlaneRequestTimeout(request, config);
service.respondActivityTaskFailed(request);
}
@Override
public void recordHeartbeat(String details) throws CancellationException {
RecordActivityTaskHeartbeatRequest request = new RecordActivityTaskHeartbeatRequest();
request.setDetails(details);
request.setTaskToken(taskToken);
ActivityTaskStatus status;
RequestTimeoutHelper.overrideDataPlaneRequestTimeout(request, config);
status = service.recordActivityTaskHeartbeat(request);
if (status.isCancelRequested()) {
throw new CancellationException();
}
}
@Override
public void reportCancellation(String details) {
RespondActivityTaskCanceledRequest request = new RespondActivityTaskCanceledRequest();
request.setDetails(details);
request.setTaskToken(taskToken);
RequestTimeoutHelper.overrideDataPlaneRequestTimeout(request, config);
service.respondActivityTaskCanceled(request);
}
}
| 3,486 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowClientFactory.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClient;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
public interface WorkflowClientFactory<T> {
GenericWorkflowClient getGenericClient();
void setGenericClient(GenericWorkflowClient genericClient);
DataConverter getDataConverter();
void setDataConverter(DataConverter dataConverter);
StartWorkflowOptions getStartWorkflowOptions();
void setStartWorkflowOptions(StartWorkflowOptions startWorkflowOptions);
T getClient();
T getClient(String workflowId);
T getClient(WorkflowExecution execution);
T getClient(WorkflowExecution execution, StartWorkflowOptions options);
T getClient(WorkflowExecution execution, StartWorkflowOptions options, DataConverter dataConverter);
}
| 3,487 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/SignalExternalWorkflowException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.SignalExternalWorkflowExecutionFailedCause;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
/**
* Exception used to communicate failure of a signal.
*/
@SuppressWarnings("serial")
public class SignalExternalWorkflowException extends DecisionException {
private SignalExternalWorkflowExecutionFailedCause failureCause;
private WorkflowExecution signaledExecution;
public SignalExternalWorkflowException(String message) {
super(message);
}
public SignalExternalWorkflowException(String message, Throwable cause) {
super(message, cause);
}
public SignalExternalWorkflowException(long eventId, WorkflowExecution signaledExecution, String cause) {
super(cause + " for signaledExecution=\"" + signaledExecution, eventId);
this.signaledExecution = signaledExecution;
this.failureCause = SignalExternalWorkflowExecutionFailedCause.valueOf(cause);
}
public WorkflowExecution getSignaledExecution() {
return signaledExecution;
}
public void setFailureCause(SignalExternalWorkflowExecutionFailedCause failureCause) {
this.failureCause = failureCause;
}
public SignalExternalWorkflowExecutionFailedCause getFailureCause() {
return failureCause;
}
public void setSignaledExecution(WorkflowExecution signaledExecution) {
this.signaledExecution = signaledExecution;
}
}
| 3,488 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowClock.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.core.Promise;
import com.amazonaws.services.simpleworkflow.model.DecisionTask;
/**
* Clock that must be used inside workflow definition code to ensure replay
* determinism.
*/
public interface WorkflowClock {
/**
* @return time of the {@link DecisionTask} start event of the decision
* being processed or replayed.
*/
public long currentTimeMillis();
/**
* <code>true</code> indicates if workflow is replaying already processed
* events to reconstruct it state. <code>false</code> indicates that code is
* making forward process for the first time. For example can be used to
* avoid duplicating log records due to replay.
*/
public boolean isReplaying();
/**
* Create a Value that becomes ready after the specified delay.
*
* @param delaySeconds
* time-interval after which the Value becomes ready in seconds.
* @return Promise that becomes ready after the specified delay.
*/
public abstract Promise<Void> createTimer(long delaySeconds);
/**
* Create a Value that becomes ready after the specified delay.
*
* @param context
* context object that is returned inside the value when it
* becomes ready.
* @return Promise that becomes ready after the specified delay. When ready
* it contains value passed as context parameter.
*/
public abstract <T> Promise<T> createTimer(long delaySeconds, final T context);
/**
* Create a Value that becomes ready after the specified delay and the provided timerId.
*
* @param timerId The Id for the timer.
* @return Promise that becomes ready after the specified delay. When ready
* it contains value passed as context parameter.
*/
public abstract <T> Promise<T> createTimer(long delaySeconds, final T context, String timerId);
}
| 3,489 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowExecutionLocal.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.util.ArrayList;
import java.util.List;
/**
* Contains value that is bound to a currently executing workflow. Has the same
* purpose as {@link ThreadLocal} which bounds value to a particular thread. It
* is subject to the same replay rules as the rest of the workflow definition.
*/
public class WorkflowExecutionLocal<T> {
private static class Wrapper<T> {
public T wrapped;
}
/**
* It is not good idea to rely on the fact that implementation relies on
* ThreadLocal as it is subject to change.
*/
private final ThreadLocal<Wrapper<T>> value = new ThreadLocal<Wrapper<T>>();
private final static List<WorkflowExecutionLocal<?>> locals = new ArrayList<WorkflowExecutionLocal<?>>();
/**
* Must be called before each decision. It is not a good idea to call this
* method from non framework code for non testing scenarios.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void before() {
List<WorkflowExecutionLocal<?>> currentLocals;
synchronized (locals) {
currentLocals = new ArrayList<WorkflowExecutionLocal<?>>(locals);
}
for (WorkflowExecutionLocal local : currentLocals) {
Wrapper w = new Wrapper();
w.wrapped = local.initialValue();
local.set(w);
}
}
/**
* Must be called at the end of each decision. It is not a good idea to call
* this method from non framework code for non testing scenarios.
*/
public static void after() {
List<WorkflowExecutionLocal<?>> currentLocals;
synchronized (locals) {
currentLocals = new ArrayList<WorkflowExecutionLocal<?>>(locals);
}
for (WorkflowExecutionLocal<?> local : currentLocals) {
local.removeAfter();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public WorkflowExecutionLocal() {
Wrapper w = new Wrapper();
w.wrapped = initialValue();
set(w);
synchronized (locals) {
locals.add(this);
}
}
public T get() {
Wrapper<T> w = getWrapped();
return w.wrapped;
}
private Wrapper<T> getWrapped() {
Wrapper<T> w = value.get();
if (w == null) {
throw new IllegalStateException("Called outside of the workflow definition code.");
}
return w;
}
public int hashCode() {
Wrapper<T> w = getWrapped();
return w.wrapped.hashCode();
}
public void remove() {
Wrapper<T> w = getWrapped();
w.wrapped = null;
}
public void set(T v) {
Wrapper<T> w = getWrapped();
w.wrapped = v;
}
private void set(Wrapper<T> w) {
value.set(w);
}
private void removeAfter() {
value.remove();
}
protected T initialValue() {
return null;
}
}
| 3,490 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/LambdaFunctionTimedOutException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.LambdaFunctionTimeoutType;
@SuppressWarnings("serial")
public class LambdaFunctionTimedOutException extends LambdaFunctionException {
private LambdaFunctionTimeoutType timeoutType;
public LambdaFunctionTimedOutException(String message, Throwable cause) {
super(message, cause);
}
public LambdaFunctionTimedOutException(String message) {
super(message);
}
public LambdaFunctionTimedOutException(long eventId, String lambdaFunctionName, String lambdaId, String timeoutType) {
super(timeoutType, eventId, lambdaFunctionName, lambdaId);
this.timeoutType = LambdaFunctionTimeoutType.fromValue(timeoutType);
}
public LambdaFunctionTimeoutType getTimeoutType() {
return timeoutType;
}
public void setTimeoutType(LambdaFunctionTimeoutType timeoutType) {
this.timeoutType = timeoutType;
}
}
| 3,491 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ActivityExecutionContextProvider.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;
/**
* Used to access execution context of the currently executed activity. An
* implementation might rely on thread local storage. So it is guaranteed to
* return current context only in the thread that invoked the activity
* implementation. If activity implementation needs to pass its execution
* context to other threads it has to do it explicitly.
*
* @author fateev
*/
public interface ActivityExecutionContextProvider {
public ActivityExecutionContext getActivityExecutionContext();
}
| 3,492 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DecisionException.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;
/**
* Exception used to communicate failure during fulfillment of a decision sent
* to SWF. This exception and all its subclasses are expected to be thrown by
* the framework. The only reason its constructor is public is so allow unit
* tests that throw it.
*/
@SuppressWarnings("serial")
public abstract class DecisionException extends RuntimeException {
private long eventId;
public DecisionException(String message) {
super(message);
}
public DecisionException(String message, Throwable cause) {
super(message, cause);
}
public DecisionException(String message, long eventId) {
super(message);
this.eventId = eventId;
}
public long getEventId() {
return eventId;
}
public void setEventId(long eventId) {
this.eventId = eventId;
}
}
| 3,493 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ActivitiesClient.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericActivityClient;
public interface ActivitiesClient {
public DataConverter getDataConverter();
public ActivitySchedulingOptions getSchedulingOptions();
public GenericActivityClient getGenericClient();
}
| 3,494 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkerBase.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.lang.Thread.UncaughtExceptionHandler;
import com.amazonaws.services.simpleworkflow.AmazonSimpleWorkflow;
import com.amazonaws.services.simpleworkflow.flow.annotations.SkipTypeRegistration;
import com.amazonaws.services.simpleworkflow.flow.config.SimpleWorkflowClientConfig;
public interface WorkerBase extends SuspendableWorker {
AmazonSimpleWorkflow getService();
SimpleWorkflowClientConfig getClientConfig();
String getDomain();
boolean isRegisterDomain();
/**
* Should domain be registered on startup. Default is <code>false</code>.
* When enabled {@link #setDomainRetentionPeriodInDays(long)} property is
* required.
*/
void setRegisterDomain(boolean registerDomain);
long getDomainRetentionPeriodInDays();
/**
* Value of DomainRetentionPeriodInDays parameter passed to
* {@link AmazonSimpleWorkflow#registerDomain} call. Required when
* {@link #isRegisterDomain()} is <code>true</code>.
*/
void setDomainRetentionPeriodInDays(long domainRetentionPeriodInDays);
/**
* Task list name that given worker polls for tasks.
*/
String getTaskListToPoll();
double getMaximumPollRatePerSecond();
/**
* Maximum number of poll request to the task list per second allowed.
* Default is 0 which means unlimited.
*
* @see #setMaximumPollRateIntervalMilliseconds(int)
*/
void setMaximumPollRatePerSecond(double maximumPollRatePerSecond);
int getMaximumPollRateIntervalMilliseconds();
/**
* The sliding window interval used to measure the poll rate. Controls
* allowed rate burstiness. For example if allowed rate is 10 per second and
* poll rate interval is 100 milliseconds the poller is not going to allow
* more then one poll per 100 milliseconds. If poll rate interval is 10
* seconds then 100 request can be emitted as fast as possible, but then the
* polling stops until 10 seconds pass.
*
* @see #setMaximumPollRatePerSecond(double)
*/
void setMaximumPollRateIntervalMilliseconds(int maximumPollRateIntervalMilliseconds);
UncaughtExceptionHandler getUncaughtExceptionHandler();
/**
* Handler notified about poll request and other unexpected failures. The
* default implementation logs the failures using ERROR level.
*/
void setUncaughtExceptionHandler(UncaughtExceptionHandler uncaughtExceptionHandler);
String getIdentity();
/**
* Set the identity that worker specifies in the poll requests. This value
* ends up stored in the identity field of the corresponding Start history
* event. Default is "pid"@"host".
*
* @param identity
* maximum size is 256 characters.
*/
void setIdentity(String identity);
long getPollBackoffInitialInterval();
/**
* Failed poll requests are retried after an interval defined by an
* exponential backoff algorithm. See BackoffThrottler for more info.
*
* @param backoffInitialInterval
* the interval between failure and the first retry. Default is
* 100.
*/
void setPollBackoffInitialInterval(long backoffInitialInterval);
long getPollBackoffMaximumInterval();
/**
* @see WorkerBase#setPollBackoffInitialInterval(long)
*
* @param backoffMaximumInterval
* maximum interval between poll request retries. Default is
* 60000 (one minute).
*/
void setPollBackoffMaximumInterval(long backoffMaximumInterval);
double getPollBackoffCoefficient();
/**
* @see WorkerBase#setPollBackoffInitialInterval(long)
*
* @param backoffCoefficient
* coefficient that defines how fast retry interval grows in case
* of poll request failures. Default is 2.0.
*/
void setPollBackoffCoefficient(double backoffCoefficient);
boolean isDisableServiceShutdownOnStop();
/**
* When set to false (which is default) at the beginning of the worker
* shutdown {@link AmazonSimpleWorkflow#shutdown()} is called. It causes all
* outstanding long poll request to disconnect. But also causes all future
* request (for example activity completions) to SWF fail.
*/
void setDisableServiceShutdownOnStop(boolean disableServiceShutdownOnStop);
int getPollThreadCount();
/**
* Defines how many concurrent threads are used by the given worker to poll
* the specified task list. Default is 1. The size of the task execution
* thread pool is defined through {@link #setExecuteThreadCount(int)}.
*/
void setPollThreadCount(int threadCount);
int getExecuteThreadCount();
/**
* Defines how many concurrent threads are used by the given worker to poll
* the specified task list. Default is 1. This will be the actual number of
* threads which execute tasks which are polled from the specified task list
* by Poll threads
*/
void setExecuteThreadCount(int threadCount);
/**
* Try to register every type (activity or workflow depending on worker)
* that are configured with the worker.
*
* @see #setDisableTypeRegistrationOnStart(boolean)
*/
void registerTypesToPoll();
boolean isRunning();
/**
* When set to true disables types registration on start even if
* {@link SkipTypeRegistration} is not specified. Types still can be
* registered by calling {@link #registerTypesToPoll()}.
*/
void setDisableTypeRegistrationOnStart(boolean disableTypeRegistrationOnStart);
boolean isDisableTypeRegistrationOnStart();
/**
* When set to true allows the task execution threads to terminate
* if they have been idle for 1 minute.
*/
void setAllowCoreThreadTimeOut(boolean allowCoreThreadTimeOut);
boolean isAllowCoreThreadTimeOut();
}
| 3,495 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/DynamicWorkflowClientExternalImpl.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import java.util.Map;
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.ChildPolicy;
import com.amazonaws.services.simpleworkflow.model.WorkflowExecution;
import com.amazonaws.services.simpleworkflow.model.WorkflowType;
public class DynamicWorkflowClientExternalImpl implements DynamicWorkflowClientExternal {
protected DataConverter dataConverter;
protected StartWorkflowOptions schedulingOptions;
protected GenericWorkflowClientExternal genericClient;
protected WorkflowExecution workflowExecution;
protected WorkflowType workflowType;
public DynamicWorkflowClientExternalImpl(String workflowId, WorkflowType workflowType) {
this(new WorkflowExecution().withWorkflowId(workflowId), workflowType, null, null);
}
public DynamicWorkflowClientExternalImpl(WorkflowExecution workflowExecution) {
this(workflowExecution, null, null, null);
}
public DynamicWorkflowClientExternalImpl(String workflowId, WorkflowType workflowType, StartWorkflowOptions options) {
this(new WorkflowExecution().withWorkflowId(workflowId), workflowType, options, null, null);
}
public DynamicWorkflowClientExternalImpl(WorkflowExecution workflowExecution, WorkflowType workflowType,
StartWorkflowOptions options) {
this(workflowExecution, workflowType, options, null, null);
}
public DynamicWorkflowClientExternalImpl(WorkflowExecution workflowExecution, WorkflowType workflowType,
StartWorkflowOptions options, DataConverter dataConverter) {
this(workflowExecution, workflowType, options, dataConverter, null);
}
public DynamicWorkflowClientExternalImpl(WorkflowExecution workflowExecution, WorkflowType workflowType,
StartWorkflowOptions options, DataConverter dataConverter, GenericWorkflowClientExternal genericClient) {
this.workflowExecution = workflowExecution;
this.workflowType = workflowType;
this.schedulingOptions = options;
if (dataConverter == null) {
this.dataConverter = new JsonDataConverter();
}
else {
this.dataConverter = dataConverter;
}
this.genericClient = genericClient;
}
public DataConverter getDataConverter() {
return dataConverter;
}
public void setDataConverter(DataConverter dataConverter) {
this.dataConverter = dataConverter;
}
public StartWorkflowOptions getSchedulingOptions() {
return schedulingOptions;
}
public void setSchedulingOptions(StartWorkflowOptions schedulingOptions) {
this.schedulingOptions = schedulingOptions;
}
public GenericWorkflowClientExternal getGenericClient() {
return genericClient;
}
public void setGenericClient(GenericWorkflowClientExternal genericClient) {
this.genericClient = genericClient;
}
public WorkflowExecution getWorkflowExecution() {
return workflowExecution;
}
public void setWorkflowExecution(WorkflowExecution workflowExecution) {
this.workflowExecution = workflowExecution;
}
public WorkflowType getWorkflowType() {
return workflowType;
}
public void setWorkflowType(WorkflowType workflowType) {
this.workflowType = workflowType;
}
@Override
public void terminateWorkflowExecution(String reason, String details, ChildPolicy childPolicy) {
TerminateWorkflowExecutionParameters terminateParameters = new TerminateWorkflowExecutionParameters();
terminateParameters.setReason(reason);
terminateParameters.setDetails(details);
if (childPolicy != null) {
terminateParameters.setChildPolicy(childPolicy);
}
terminateParameters.setWorkflowExecution(workflowExecution);
genericClient.terminateWorkflowExecution(terminateParameters);
}
@Override
public void requestCancelWorkflowExecution() {
genericClient.requestCancelWorkflowExecution(workflowExecution);
}
@Override
public void startWorkflowExecution(Object[] arguments) {
startWorkflowExecution(arguments, null);
}
@Override
public void startWorkflowExecution(Object[] arguments, StartWorkflowOptions startOptionsOverride) {
if (workflowType == null) {
throw new IllegalStateException("Required property workflowType is null");
}
if (workflowExecution == null) {
throw new IllegalStateException("wokflowExecution is null");
}
else if (workflowExecution.getWorkflowId() == null) {
throw new IllegalStateException("wokflowId is null");
}
StartWorkflowExecutionParameters parameters = new StartWorkflowExecutionParameters();
parameters.setWorkflowType(workflowType);
parameters.setWorkflowId(workflowExecution.getWorkflowId());
String input = dataConverter.toData(arguments);
parameters.setInput(input);
parameters = parameters.createStartWorkflowExecutionParametersFromOptions(schedulingOptions, startOptionsOverride);
WorkflowExecution newExecution = genericClient.startWorkflow(parameters);
String runId = newExecution.getRunId();
workflowExecution.setRunId(runId);
}
@Override
public void signalWorkflowExecution(String signalName, Object[] arguments) {
SignalExternalWorkflowParameters signalParameters = new SignalExternalWorkflowParameters();
signalParameters.setRunId(workflowExecution.getRunId());
signalParameters.setWorkflowId(workflowExecution.getWorkflowId());
signalParameters.setSignalName(signalName);
String input = dataConverter.toData(arguments);
signalParameters.setInput(input);
genericClient.signalWorkflowExecution(signalParameters);
}
@Override
public <T> T getWorkflowExecutionState(Class<T> returnType) throws Throwable {
String state = genericClient.getWorkflowState(workflowExecution);
if (state == null)
return null;
try {
Throwable failure = dataConverter.fromData(state, Throwable.class);
if (failure != null) {
throw failure;
}
}
catch (DataConverterException e) {
}
catch (RuntimeException e) {
}
return dataConverter.fromData(state, returnType);
}
@Override
public Map<String, Integer> getImplementationVersions() {
return genericClient.getImplementationVersions(workflowExecution);
}
}
| 3,496 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/ActivityTaskException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.ActivityType;
/**
* Exception used to communicate failure of remote activity.
*/
@SuppressWarnings("serial")
public abstract class ActivityTaskException extends DecisionException {
private ActivityType activityType;
private String activityId;
public ActivityTaskException(String message) {
super(message);
}
public ActivityTaskException(String message, Throwable cause) {
super(message, cause);
}
public ActivityTaskException(String message, long eventId, ActivityType activityType, String activityId) {
super(message + " for activityId=\"" + activityId + "\" of activityType=" + activityType, eventId);
this.activityType = activityType;
this.activityId = activityId;
}
public ActivityType getActivityType() {
return activityType;
}
public void setActivityType(ActivityType activityType) {
this.activityType = activityType;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
}
| 3,497 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/WorkflowSelfClient.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.flow.generic.GenericWorkflowClient;
public interface WorkflowSelfClient {
public DataConverter getDataConverter();
public void setDataConverter(DataConverter converter);
public StartWorkflowOptions getSchedulingOptions();
public void setSchedulingOptions(StartWorkflowOptions schedulingOptions);
public GenericWorkflowClient getGenericClient();
public void setGenericClient(GenericWorkflowClient genericClient);
}
| 3,498 |
0 | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow | Create_ds/aws-swf-flow-library/src/main/java/com/amazonaws/services/simpleworkflow/flow/StartTimerFailedException.java | /**
* Copyright 2012-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.simpleworkflow.flow;
import com.amazonaws.services.simpleworkflow.model.StartTimerFailedCause;
/**
* Exception used to communicate that timer wasn't scheduled due to some cause
*/
@SuppressWarnings("serial")
public class StartTimerFailedException extends TimerException {
private StartTimerFailedCause failureCause;
public StartTimerFailedException(String message) {
super(message);
}
public StartTimerFailedException(String message, Throwable cause) {
super(message, cause);
}
public StartTimerFailedException(long eventId, String timerId, Object createTimerUserContext, String cause) {
super(cause + " for timerId=\"" + timerId, eventId, timerId, createTimerUserContext);
failureCause = StartTimerFailedCause.fromValue(cause);
}
/**
* @return enumeration that contains the cause of the failure
*/
public StartTimerFailedCause getFailureCause() {
return failureCause;
}
public void setFailureCause(StartTimerFailedCause failureCause) {
this.failureCause = failureCause;
}
}
| 3,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.