index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/AbstractResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import junit.framework.TestCase; import org.apache.airavata.persistance.registry.jpa.resources.GatewayResource; import org.apache.airavata.persistance.registry.jpa.resources.UserResource; import org.apache.airavata.persistance.registry.jpa.resources.WorkerResource; import org.apache.airavata.persistance.registry.jpa.util.Initialize; public abstract class AbstractResourceTest extends TestCase { private GatewayResource gatewayResource; private WorkerResource workerResource; private UserResource userResource; private Initialize initialize; @Override public void setUp() throws Exception { initialize = new Initialize(); initialize.initializeDB(); gatewayResource = (GatewayResource)ResourceUtils.getGateway("default"); workerResource = (WorkerResource)ResourceUtils.getWorker(gatewayResource.getGatewayName(), "admin"); userResource = (UserResource)gatewayResource.create(ResourceType.USER); userResource.setUserName("admin"); userResource.setPassword("admin"); } @Override public void tearDown() throws Exception { initialize.stopDerbyServer(); } public GatewayResource getGatewayResource() { return gatewayResource; } public WorkerResource getWorkerResource() { return workerResource; } public UserResource getUserResource() { return userResource; } }
9,400
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/HostDescriptorResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.GatewayResource; import org.apache.airavata.persistance.registry.jpa.resources.HostDescriptorResource; public class HostDescriptorResourceTest extends AbstractResourceTest { private GatewayResource gatewayResource; private HostDescriptorResource hostDescriptorResource; @Override public void setUp() throws Exception { super.setUp(); gatewayResource = super.getGatewayResource(); hostDescriptorResource = gatewayResource.createHostDescriptorResource("testHostDesc"); hostDescriptorResource.setUserName("admin"); hostDescriptorResource.setContent("testContent"); } public void testGetList() throws Exception { assertNotNull("application data being retrieved successfully", hostDescriptorResource.get(ResourceType.APPLICATION_DESCRIPTOR)); } public void testSave() throws Exception { hostDescriptorResource.save(); assertTrue("host descriptor saved successfully", gatewayResource.isHostDescriptorExists("testHostDesc")); //remove host descriptor gatewayResource.removeHostDescriptor("testHostDesc"); } @Override public void tearDown() throws Exception { super.tearDown(); } }
9,401
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/ProjectResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.ExperimentResource; import org.apache.airavata.persistance.registry.jpa.resources.GatewayResource; import org.apache.airavata.persistance.registry.jpa.resources.ProjectResource; import org.apache.airavata.persistance.registry.jpa.resources.WorkerResource; import java.sql.Timestamp; import java.util.Calendar; public class ProjectResourceTest extends AbstractResourceTest { private GatewayResource gatewayResource; private WorkerResource workerResource; private ProjectResource projectResource; private ExperimentResource experimentResource; @Override public void setUp() throws Exception { super.setUp(); gatewayResource = super.getGatewayResource(); workerResource = super.getWorkerResource(); projectResource = workerResource.createProject("testProject"); projectResource.setGateway(gatewayResource); projectResource.setWorker(workerResource); projectResource.save(); experimentResource = projectResource.createExperiment("testExpID"); experimentResource.setGateway(gatewayResource); experimentResource.setWorker(workerResource); Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Timestamp currentTime = new Timestamp(d.getTime()); experimentResource.setSubmittedDate(currentTime); experimentResource.setProject(projectResource); experimentResource.save(); } public void testCreate() throws Exception { assertNotNull("experiment resource created successfully", experimentResource); } public void testGet() throws Exception { ExperimentResource experiment = projectResource.getExperiment("testExpID"); assertNotNull("experiment resource retrieved successfully", experiment); } public void testGetList() throws Exception { assertNotNull("experiment resources retrieved successfully", projectResource.getExperiments()); } public void testSave() throws Exception { projectResource.save(); assertTrue("Project saved successfully", workerResource.isProjectExists("testProject")); //remove project workerResource.removeProject("testProject"); } public void testRemove() throws Exception { projectResource.removeExperiment("testExpID"); assertFalse("experiment removed successfully", projectResource.isExperimentExists("testExpID")); experimentResource = projectResource.createExperiment("testExpID"); experimentResource.setGateway(gatewayResource); experimentResource.setWorker(workerResource); Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Timestamp currentTime = new Timestamp(d.getTime()); experimentResource.setSubmittedDate(currentTime); experimentResource.setProject(projectResource); experimentResource.save(); } @Override public void tearDown() throws Exception { super.tearDown(); } }
9,402
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/GramDataResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.*; import java.sql.Timestamp; import java.util.Calendar; public class GramDataResourceTest extends AbstractResourceTest { private WorkflowDataResource workflowDataResource; @Override public void setUp() throws Exception { super.setUp(); GatewayResource gatewayResource = super.getGatewayResource(); WorkerResource workerResource = super.getWorkerResource(); ExperimentResource experimentResource = (ExperimentResource) gatewayResource.create(ResourceType.EXPERIMENT); experimentResource.setExpID("testExpID"); experimentResource.setWorker(workerResource); experimentResource.setProject(new ProjectResource(workerResource, gatewayResource, "testProject")); experimentResource.save(); ExperimentDataResource experimentDataResource = (ExperimentDataResource) experimentResource.create(ResourceType.EXPERIMENT_DATA); experimentDataResource.setExpName("testExpID"); experimentDataResource.setUserName(workerResource.getUser()); experimentDataResource.save(); workflowDataResource = (WorkflowDataResource) experimentDataResource.create(ResourceType.WORKFLOW_DATA); workflowDataResource.setWorkflowInstanceID("testWFInstance"); workflowDataResource.setTemplateName("testTemplate"); workflowDataResource.setExperimentID("testExpID"); Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Timestamp timestamp = new Timestamp(d.getTime()); workflowDataResource.setLastUpdatedTime(timestamp); workflowDataResource.save(); } public void testSave() throws Exception { GramDataResource gramDataResource = workflowDataResource.createGramData("testNode"); gramDataResource.setWorkflowDataResource(workflowDataResource); gramDataResource.setInvokedHost("testhost"); gramDataResource.setRsl("testRSL"); gramDataResource.save(); assertTrue("gram data saved successfully", workflowDataResource.isGramDataExists("testNode")); } @Override public void tearDown() throws Exception { super.tearDown(); } }
9,403
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/NodeDataResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.*; import java.sql.Timestamp; import java.util.Calendar; public class NodeDataResourceTest extends AbstractResourceTest { private WorkflowDataResource workflowDataResource; @Override public void setUp() throws Exception { super.setUp(); GatewayResource gatewayResource = super.getGatewayResource(); WorkerResource workerResource = super.getWorkerResource(); ExperimentResource experimentResource = (ExperimentResource) gatewayResource.create(ResourceType.EXPERIMENT); experimentResource.setExpID("testExpID"); experimentResource.setWorker(workerResource); experimentResource.setProject(new ProjectResource(workerResource, gatewayResource, "testProject")); experimentResource.save(); ExperimentDataResource experimentDataResource = (ExperimentDataResource) experimentResource.create(ResourceType.EXPERIMENT_DATA); experimentDataResource.setExpName("testExpID"); experimentDataResource.setUserName(workerResource.getUser()); experimentDataResource.save(); workflowDataResource = (WorkflowDataResource) experimentDataResource.create(ResourceType.WORKFLOW_DATA); workflowDataResource.setWorkflowInstanceID("testWFInstance"); workflowDataResource.setTemplateName("testTemplate"); workflowDataResource.setExperimentID("testExpID"); Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Timestamp timestamp = new Timestamp(d.getTime()); workflowDataResource.setLastUpdatedTime(timestamp); workflowDataResource.save(); } public void testSave() throws Exception { NodeDataResource nodeDataResource = workflowDataResource.createNodeData("testNodeID"); nodeDataResource.setInputs("testInput"); nodeDataResource.setStatus("testStatus"); nodeDataResource.setExecutionIndex(0); nodeDataResource.save(); assertTrue("node data resource saved successfully", workflowDataResource.isNodeExists("testNodeID")); } @Override public void tearDown() throws Exception { super.tearDown(); } }
9,404
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/ExperimentDataResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.*; import java.sql.Timestamp; import java.util.Calendar; public class ExperimentDataResourceTest extends AbstractResourceTest { private ExperimentDataResource experimentDataResource; private ExperimentResource experimentResource; private WorkflowDataResource workflowDataResource; private ExperimentMetadataResource experimentMetadataResource; @Override public void setUp() throws Exception { super.setUp(); GatewayResource gatewayResource = super.getGatewayResource(); WorkerResource workerResource = super.getWorkerResource(); experimentResource = (ExperimentResource) gatewayResource.create(ResourceType.EXPERIMENT); experimentResource.setExpID("testExpID"); experimentResource.setWorker(workerResource); experimentResource.setProject(new ProjectResource(workerResource, gatewayResource, "testProject")); experimentResource.save(); experimentDataResource = (ExperimentDataResource) experimentResource.create(ResourceType.EXPERIMENT_DATA); experimentDataResource.setExpName("testExpID"); experimentDataResource.setUserName(workerResource.getUser()); experimentDataResource.save(); experimentMetadataResource = experimentDataResource.createExperimentMetadata(); workflowDataResource = experimentDataResource.createWorkflowInstanceResource("testWorkflowInstance"); experimentMetadataResource.setExpID("testExpID"); experimentMetadataResource.setMetadata("testMetadata"); experimentMetadataResource.save(); workflowDataResource.setExperimentID("testExpID"); workflowDataResource.setStatus("testStatus"); workflowDataResource.setTemplateName("testWorkflowInstance"); Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Timestamp currentTime = new Timestamp(d.getTime()); workflowDataResource.setLastUpdatedTime(currentTime); workflowDataResource.setStartTime(currentTime); workflowDataResource.save(); } public void testCreate() throws Exception { assertNotNull("workflowdata resource created", workflowDataResource); assertNotNull("experimemt metadata resource created", experimentMetadataResource); } public void testGet() throws Exception { assertNotNull("workflow data retrieved successfully", experimentDataResource.getWorkflowInstance("testWorkflowInstance")); assertNotNull("experiment meta data retrieved successfully", experimentDataResource.getExperimentMetadata()); } public void testGetList() throws Exception { assertNotNull("workflow data retrieved successfully", experimentDataResource.get(ResourceType.WORKFLOW_DATA)); assertNotNull("experiment meta data retrieved successfully", experimentDataResource.get(ResourceType.EXPERIMENT_METADATA)); } public void testSave() throws Exception { experimentDataResource.save(); assertTrue("experiment data saved successfully", experimentResource.isExists(ResourceType.EXPERIMENT_DATA, "testExpID")); } public void testRemove() throws Exception { experimentDataResource.remove(ResourceType.WORKFLOW_DATA, "testWFInstanceID"); assertTrue("workflow data resource removed successfully", !experimentResource.isExists(ResourceType.EXPERIMENT_DATA, "testWFInstanceID")); experimentDataResource.remove(ResourceType.EXPERIMENT_METADATA, "testExpID"); assertTrue("experiment meta data resource removed successfully", !experimentDataResource.isExists(ResourceType.EXPERIMENT_METADATA, "testExpID")); } @Override public void tearDown() throws Exception { super.tearDown(); } }
9,405
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/ConfigurationResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.ConfigurationResource; import java.sql.Timestamp; import java.util.Calendar; public class ConfigurationResourceTest extends AbstractResourceTest { @Override public void setUp() throws Exception { super.setUp(); } public void testSave() throws Exception { ConfigurationResource configuration = ResourceUtils.createConfiguration("testConfigKey"); configuration.setConfigVal("testConfigValue"); Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Timestamp currentTime = new Timestamp(d.getTime()); configuration.setExpireDate(currentTime); configuration.setCategoryID("SYSTEM"); configuration.save(); assertTrue("Configuration Save succuessful", ResourceUtils.isConfigurationExist("testConfigKey")); //remove test configuration ResourceUtils.removeConfiguration("testConfigKey"); } @Override public void tearDown() throws Exception { super.tearDown(); } }
9,406
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/PublishWorkflowResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.GatewayResource; import org.apache.airavata.persistance.registry.jpa.resources.PublishWorkflowResource; import java.sql.Timestamp; import java.util.Calendar; public class PublishWorkflowResourceTest extends AbstractResourceTest { private GatewayResource gatewayResource; private PublishWorkflowResource publishWorkflowResource; @Override public void setUp() throws Exception { super.setUp(); gatewayResource = super.getGatewayResource(); publishWorkflowResource = gatewayResource.createPublishedWorkflow("workflow1"); publishWorkflowResource.setCreatedUser("admin"); publishWorkflowResource.setContent("testContent"); Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Timestamp currentTime = new Timestamp(d.getTime()); publishWorkflowResource.setPublishedDate(currentTime); } public void testSave() throws Exception { publishWorkflowResource.save(); assertTrue("published workflow saved successfully", gatewayResource.isPublishedWorkflowExists("workflow1")); //remove workflow gatewayResource.removePublishedWorkflow("workflow1"); } @Override public void tearDown() throws Exception { super.tearDown(); } }
9,407
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/GatewayResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.*; import java.sql.Timestamp; import java.util.Calendar; public class GatewayResourceTest extends AbstractResourceTest { private GatewayResource gatewayResource; private ProjectResource projectResource; private UserResource userResource; private WorkerResource workerResource; private PublishWorkflowResource publishWorkflowResource; private UserWorkflowResource userWorkflowResource; private HostDescriptorResource hostDescriptorResource; private ServiceDescriptorResource serviceDescriptorResource; private ApplicationDescriptorResource applicationDescriptorResource; private ExperimentResource experimentResource; @Override public void setUp() throws Exception { super.setUp(); gatewayResource = super.getGatewayResource(); workerResource = super.getWorkerResource(); userResource = super.getUserResource(); if (gatewayResource == null) { gatewayResource = (GatewayResource) ResourceUtils.getGateway("default"); } projectResource = (ProjectResource) gatewayResource.create(ResourceType.PROJECT); projectResource.setName("testProject"); projectResource.setWorker(workerResource); projectResource.save(); publishWorkflowResource = (PublishWorkflowResource) gatewayResource.create(ResourceType.PUBLISHED_WORKFLOW); userWorkflowResource = (UserWorkflowResource) gatewayResource.create(ResourceType.USER_WORKFLOW); hostDescriptorResource = (HostDescriptorResource) gatewayResource.create(ResourceType.HOST_DESCRIPTOR); serviceDescriptorResource = (ServiceDescriptorResource) gatewayResource.create(ResourceType.SERVICE_DESCRIPTOR); applicationDescriptorResource = (ApplicationDescriptorResource) gatewayResource.create(ResourceType.APPLICATION_DESCRIPTOR); experimentResource = (ExperimentResource) gatewayResource.create(ResourceType.EXPERIMENT); hostDescriptorResource.setUserName(workerResource.getUser()); hostDescriptorResource.setHostDescName("testHostDesc"); hostDescriptorResource.setContent("testContent"); hostDescriptorResource.save(); serviceDescriptorResource.setUserName(workerResource.getUser()); serviceDescriptorResource.setServiceDescName("testServiceDesc"); serviceDescriptorResource.setContent("testContent"); serviceDescriptorResource.save(); applicationDescriptorResource.setHostDescName(hostDescriptorResource.getHostDescName()); applicationDescriptorResource.setServiceDescName(serviceDescriptorResource.getServiceDescName()); applicationDescriptorResource.setUpdatedUser(workerResource.getUser()); applicationDescriptorResource.setName("testAppDesc"); applicationDescriptorResource.setContent("testContent"); applicationDescriptorResource.save(); Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Timestamp currentTime = new Timestamp(d.getTime()); userWorkflowResource.setName("workflow1"); userWorkflowResource.setLastUpdateDate(currentTime); userWorkflowResource.setWorker(workerResource); userWorkflowResource.setContent("testContent"); userWorkflowResource.save(); publishWorkflowResource.setName("pubworkflow1"); publishWorkflowResource.setCreatedUser("admin"); publishWorkflowResource.setContent("testContent"); Calendar c = Calendar.getInstance(); java.util.Date da = c.getTime(); Timestamp time = new Timestamp(da.getTime()); publishWorkflowResource.setPublishedDate(time); publishWorkflowResource.save(); experimentResource.setExpID("testExpID"); experimentResource.setProject(projectResource); experimentResource.setWorker(workerResource); experimentResource.setSubmittedDate(currentTime); experimentResource.save(); } public void testSave() throws Exception { gatewayResource.setOwner("owner1"); gatewayResource.save(); boolean gatewayExist = ResourceUtils.isGatewayExist("default"); assertTrue("The gateway exisits", gatewayExist); } public void testCreate() throws Exception { assertNotNull("project resource cannot be null", projectResource); assertNotNull("user resource cannot be null", userResource); assertNotNull("worker resource cannot be null", workerResource); assertNotNull("publish workflow resource cannot be null", publishWorkflowResource); assertNotNull("user workflow resource cannot be null", userWorkflowResource); assertNotNull("host descriptor resource cannot be null", hostDescriptorResource); assertNotNull("service descriptor resource cannot be null", serviceDescriptorResource); assertNotNull("application descriptor resource cannot be null", applicationDescriptorResource); assertNotNull("experiment resource cannot be null", experimentResource); } public void testIsExists() throws Exception { assertTrue(gatewayResource.isExists(ResourceType.USER, "admin")); assertTrue(gatewayResource.isExists(ResourceType.PUBLISHED_WORKFLOW, "pubworkflow1")); assertTrue(gatewayResource.isExists(ResourceType.HOST_DESCRIPTOR, "testHostDesc")); assertTrue(gatewayResource.isExists(ResourceType.SERVICE_DESCRIPTOR, "testServiceDesc")); assertTrue(gatewayResource.isExists(ResourceType.APPLICATION_DESCRIPTOR, "testAppDesc")); assertTrue(gatewayResource.isExists(ResourceType.EXPERIMENT, "testExpID")); } public void testGet() throws Exception { assertNotNull(gatewayResource.get(ResourceType.USER, "admin")); assertNotNull(gatewayResource.get(ResourceType.PUBLISHED_WORKFLOW, "pubworkflow1")); assertNotNull(gatewayResource.get(ResourceType.HOST_DESCRIPTOR, "testHostDesc")); assertNotNull(gatewayResource.get(ResourceType.SERVICE_DESCRIPTOR, "testServiceDesc")); assertNotNull(gatewayResource.get(ResourceType.APPLICATION_DESCRIPTOR, "testAppDesc")); assertNotNull(gatewayResource.get(ResourceType.EXPERIMENT, "testExpID")); } public void testGetList() throws Exception { assertNotNull(gatewayResource.get(ResourceType.GATEWAY_WORKER)); assertNotNull(gatewayResource.get(ResourceType.PROJECT)); assertNotNull(gatewayResource.get(ResourceType.PUBLISHED_WORKFLOW)); assertNotNull(gatewayResource.get(ResourceType.HOST_DESCRIPTOR)); assertNotNull(gatewayResource.get(ResourceType.SERVICE_DESCRIPTOR)); assertNotNull(gatewayResource.get(ResourceType.APPLICATION_DESCRIPTOR)); assertNotNull(gatewayResource.get(ResourceType.EXPERIMENT)); } public void testRemove() throws Exception { gatewayResource.remove(ResourceType.PUBLISHED_WORKFLOW, "pubworkflow1"); boolean exists = gatewayResource.isExists(ResourceType.PUBLISHED_WORKFLOW, "pubworkflow1"); assertFalse(exists); gatewayResource.remove(ResourceType.HOST_DESCRIPTOR, "testHostDesc"); assertFalse(gatewayResource.isExists(ResourceType.HOST_DESCRIPTOR, "testHostDesc")); gatewayResource.remove(ResourceType.SERVICE_DESCRIPTOR, "testServiceDesc"); assertFalse(gatewayResource.isExists(ResourceType.SERVICE_DESCRIPTOR, "testServiceDesc")); gatewayResource.remove(ResourceType.EXPERIMENT, "testExpID"); assertFalse(gatewayResource.isExists(ResourceType.EXPERIMENT, "testExpID")); gatewayResource.remove(ResourceType.APPLICATION_DESCRIPTOR, "testAppDesc"); assertFalse(gatewayResource.isExists(ResourceType.APPLICATION_DESCRIPTOR, "testAppDesc")); } @Override public void tearDown() throws Exception { super.tearDown(); } }
9,408
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/GFacJobStatusResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.*; import java.sql.Timestamp; import java.util.Calendar; import java.util.List; public class GFacJobStatusResourceTest extends AbstractResourceTest { private GFacJobDataResource gFacJobDataResource; @Override public void setUp() throws Exception { super.setUp(); GatewayResource gatewayResource = super.getGatewayResource(); WorkerResource workerResource = super.getWorkerResource(); ExperimentResource experimentResource = (ExperimentResource) gatewayResource.create(ResourceType.EXPERIMENT); experimentResource.setExpID("testExpID"); experimentResource.setWorker(workerResource); experimentResource.setProject(new ProjectResource(workerResource, gatewayResource, "testProject")); experimentResource.save(); ExperimentDataResource experimentDataResource = (ExperimentDataResource) experimentResource.create(ResourceType.EXPERIMENT_DATA); experimentDataResource.setExpName("testExpID"); experimentDataResource.setUserName(workerResource.getUser()); experimentDataResource.save(); WorkflowDataResource workflowDataResource = (WorkflowDataResource) experimentDataResource.create(ResourceType.WORKFLOW_DATA); workflowDataResource.setWorkflowInstanceID("testWFInstance"); workflowDataResource.setTemplateName("testTemplate"); workflowDataResource.setExperimentID("testExpID"); Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Timestamp timestamp = new Timestamp(d.getTime()); workflowDataResource.setLastUpdatedTime(timestamp); workflowDataResource.save(); gFacJobDataResource = (GFacJobDataResource) workflowDataResource.create(ResourceType.GFAC_JOB_DATA); gFacJobDataResource.setLocalJobID("testJobID"); gFacJobDataResource.setApplicationDescID("testApplication"); gFacJobDataResource.setExperimentDataResource(experimentDataResource); gFacJobDataResource.setNodeID("testNode"); gFacJobDataResource.setHostDescID("testHost"); gFacJobDataResource.setServiceDescID("testService"); gFacJobDataResource.setStatus("testStatus"); gFacJobDataResource.setJobData("testJobData"); gFacJobDataResource.save(); } @Override public void tearDown() throws Exception { super.tearDown(); } public void testSave() throws Exception { GFacJobStatusResource resource = (GFacJobStatusResource)gFacJobDataResource.create(ResourceType.GFAC_JOB_STATUS); resource.setStatus("testStatus"); resource.setgFacJobDataResource(gFacJobDataResource); Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Timestamp timestamp = new Timestamp(d.getTime()); resource.setStatusUpdateTime(timestamp); resource.save(); List<Resource> resources = gFacJobDataResource.get(ResourceType.GFAC_JOB_STATUS); assertTrue("GFac job status saved successfully", resources.size() != 0); } }
9,409
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/WorkerResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.*; import java.sql.Timestamp; import java.util.Calendar; public class WorkerResourceTest extends AbstractResourceTest { private GatewayResource gatewayResource; private WorkerResource workerResource; private ProjectResource testProject; private UserWorkflowResource userWorkflowResource; private ExperimentResource experimentResource; @Override public void setUp() throws Exception { super.setUp(); gatewayResource = super.getGatewayResource(); workerResource = super.getWorkerResource(); testProject = workerResource.createProject("testProject"); userWorkflowResource = workerResource.createWorkflowTemplate("workflow1"); experimentResource = (ExperimentResource) workerResource.create(ResourceType.EXPERIMENT); testProject.setGateway(gatewayResource); testProject.save(); userWorkflowResource.setGateway(gatewayResource); userWorkflowResource.setContent("testContent"); userWorkflowResource.save(); experimentResource.setGateway(gatewayResource); experimentResource.setExpID("testExpID"); experimentResource.setProject(testProject); Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Timestamp currentTime = new Timestamp(d.getTime()); experimentResource.setSubmittedDate(currentTime); experimentResource.save(); } public void testCreate() throws Exception { assertNotNull("project resource created successfully", testProject); assertNotNull("user workflow created successfully", userWorkflowResource); } public void testGet() throws Exception { assertNotNull("project resource retrieved successfully", workerResource.get(ResourceType.PROJECT, "testProject")); assertNotNull("user workflow retrieved successfully", workerResource.get(ResourceType.USER_WORKFLOW, "workflow1")); assertNotNull("experiment retrieved successfully", workerResource.get(ResourceType.EXPERIMENT, "testExpID")); } public void testGetList() throws Exception { assertNotNull("project resources retrieved successfully", workerResource.get(ResourceType.PROJECT)); assertNotNull("user workflows retrieved successfully", workerResource.get(ResourceType.USER_WORKFLOW)); assertNotNull("experiments retrieved successfully", workerResource.get(ResourceType.EXPERIMENT)); } public void testSave() throws Exception { workerResource.save(); assertTrue("worker resource saved successfully", gatewayResource.isExists(ResourceType.USER, "admin")); //remove // ResourceUtils.removeGatewayWorker(gatewayResource, userResource); // gatewayResource.remove(ResourceType.USER, "testUser"); } public void testRemove() throws Exception { workerResource.removeProject("testProject"); workerResource.removeWorkflowTemplate("workflow1"); workerResource.removeExperiment("testExpID"); assertTrue("project has been removed successfully", !workerResource.isProjectExists("testProject")); assertTrue("experiment has been removed successfully", !workerResource.isExperimentExists("testExpID")); assertTrue("user workflow has been removed successfully", !workerResource.isWorkflowTemplateExists("workflow1")); testProject.setGateway(gatewayResource); testProject.save(); userWorkflowResource.setGateway(gatewayResource); userWorkflowResource.setContent("testContent"); userWorkflowResource.save(); experimentResource.setGateway(gatewayResource); experimentResource.setExpID("testExpID"); experimentResource.setProject(testProject); Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Timestamp currentTime = new Timestamp(d.getTime()); experimentResource.setSubmittedDate(currentTime); experimentResource.save(); } @Override public void tearDown() throws Exception { super.tearDown(); } }
9,410
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/ApplicationDescriptorResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.ApplicationDescriptorResource; import org.apache.airavata.persistance.registry.jpa.resources.GatewayResource; public class ApplicationDescriptorResourceTest extends AbstractResourceTest { private GatewayResource gatewayResource; @Override public void setUp() throws Exception { super.setUp(); gatewayResource = super.getGatewayResource(); } public void testSave() throws Exception { ApplicationDescriptorResource applicationDescriptorResouce = (ApplicationDescriptorResource) gatewayResource.create(ResourceType.APPLICATION_DESCRIPTOR); applicationDescriptorResouce.setHostDescName("testHostDesc"); applicationDescriptorResouce.setServiceDescName("testServiceDesc"); applicationDescriptorResouce.setName("testAppDesc"); applicationDescriptorResouce.setContent("testContent"); applicationDescriptorResouce.setUpdatedUser("admin"); applicationDescriptorResouce.save(); assertTrue("application descriptor saved successfully", gatewayResource.isExists(ResourceType.APPLICATION_DESCRIPTOR, "testAppDesc")); gatewayResource.remove(ResourceType.APPLICATION_DESCRIPTOR, "testAppDesc"); } @Override public void tearDown() throws Exception { super.tearDown(); } }
9,411
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/ServiceDescriptorResourceTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.GatewayResource; import org.apache.airavata.persistance.registry.jpa.resources.ServiceDescriptorResource; public class ServiceDescriptorResourceTest extends AbstractResourceTest { private GatewayResource gatewayResource; private ServiceDescriptorResource serviceDescriptorResource; @Override public void setUp() throws Exception { super.setUp(); gatewayResource = super.getGatewayResource(); serviceDescriptorResource = gatewayResource.createServiceDescriptorResource("testServiceDesc"); serviceDescriptorResource.setUserName("admin"); serviceDescriptorResource.setContent("testContent"); } public void testGetList() throws Exception { assertNotNull("application data being retrieved successfully", serviceDescriptorResource.get(ResourceType.APPLICATION_DESCRIPTOR)); } public void testSave() throws Exception { serviceDescriptorResource.save(); assertTrue("service descriptor saved successfully", gatewayResource.isServiceDescriptorExists("testServiceDesc")); //remove host descriptor gatewayResource.removeServiceDescriptor("testServiceDesc"); } @Override public void tearDown() throws Exception { super.tearDown(); } }
9,412
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/test/java/org/apache/airavata/persistance/registry/jpa/util/Initialize.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.util; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.resources.GatewayResource; import org.apache.airavata.persistance.registry.jpa.resources.UserResource; import org.apache.airavata.persistance.registry.jpa.resources.Utils; import org.apache.airavata.persistance.registry.jpa.resources.WorkerResource; import org.apache.airavata.registry.api.exception.RegistrySettingsException; import org.apache.airavata.registry.api.util.RegistrySettings; import org.apache.derby.drda.NetworkServerControl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.sql.*; import java.util.StringTokenizer; public class Initialize { private static final Logger logger = LoggerFactory.getLogger(Initialize.class); public static final String DERBY_SERVER_MODE_SYS_PROPERTY = "derby.drda.startNetworkServer"; private NetworkServerControl server; private static final String delimiter = ";"; public static final String PERSISTANT_DATA = "Configuration"; public static boolean checkStringBufferEndsWith(StringBuffer buffer, String suffix) { if (suffix.length() > buffer.length()) { return false; } // this loop is done on purpose to avoid memory allocation performance // problems on various JDKs // StringBuffer.lastIndexOf() was introduced in jdk 1.4 and // implementation is ok though does allocation/copying // StringBuffer.toString().endsWith() does massive memory // allocation/copying on JDK 1.5 // See http://issues.apache.org/bugzilla/show_bug.cgi?id=37169 int endIndex = suffix.length() - 1; int bufferIndex = buffer.length() - 1; while (endIndex >= 0) { if (buffer.charAt(bufferIndex) != suffix.charAt(endIndex)) { return false; } bufferIndex--; endIndex--; } return true; } private static boolean isServerStarted(NetworkServerControl server, int ntries) { for (int i = 1; i <= ntries; i ++) { try { Thread.sleep(500); server.ping(); return true; } catch (Exception e) { if (i == ntries) return false; } } return false; } public void initializeDB() { String jdbcUrl = null; String jdbcDriver = null; String jdbcUser = null; String jdbcPassword = null; try{ jdbcDriver = RegistrySettings.getSetting("registry.jdbc.driver"); jdbcUrl = RegistrySettings.getSetting("registry.jdbc.url"); jdbcUser = RegistrySettings.getSetting("registry.jdbc.user"); jdbcPassword = RegistrySettings.getSetting("registry.jdbc.password"); jdbcUrl = jdbcUrl + "?" + "user=" + jdbcUser + "&" + "password=" + jdbcPassword; } catch (RegistrySettingsException e) { logger.error("Unable to read properties" , e); } startDerbyInServerMode(); if(!isServerStarted(server, 20)){ throw new RuntimeException("Derby server cound not started within five seconds..."); } // startDerbyInEmbeddedMode(); Connection conn = null; try { Class.forName(Utils.getJDBCDriver()).newInstance(); conn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword); if (!isDatabaseStructureCreated(PERSISTANT_DATA, conn)) { executeSQLScript(conn); logger.info("New Database created for Registry"); } else { logger.debug("Database already created for Registry!"); } } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException("Database failure", e); } finally { try { if (conn != null){ if (!conn.getAutoCommit()) { conn.commit(); } conn.close(); } } catch (SQLException e) { logger.error(e.getMessage(), e); e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } try{ GatewayResource gatewayResource = new GatewayResource(); gatewayResource.setGatewayName(RegistrySettings.getSetting("default.registry.gateway")); gatewayResource.setOwner(RegistrySettings.getSetting("default.registry.gateway")); gatewayResource.save(); UserResource userResource = (UserResource) gatewayResource.create(ResourceType.USER); userResource.setUserName(RegistrySettings.getSetting("default.registry.user")); userResource.setPassword(RegistrySettings.getSetting("default.registry.password")); userResource.save(); WorkerResource workerResource = (WorkerResource) gatewayResource.create(ResourceType.GATEWAY_WORKER); workerResource.setUser(userResource.getUserName()); workerResource.save(); } catch (RegistrySettingsException e) { logger.error("Unable to read properties", e); } } public static boolean isDatabaseStructureCreated(String tableName, Connection conn) { try { System.out.println("Running a query to test the database tables existence."); // check whether the tables are already created with a query Statement statement = null; try { statement = conn.createStatement(); ResultSet rs = statement.executeQuery("select * from " + tableName); if (rs != null) { rs.close(); } } finally { try { if (statement != null) { statement.close(); } } catch (SQLException e) { return false; } } } catch (SQLException e) { return false; } return true; } private void executeSQLScript(Connection conn) throws Exception { StringBuffer sql = new StringBuffer(); BufferedReader reader = null; try{ InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("data-derby.sql"); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("//")) { continue; } if (line.startsWith("--")) { continue; } StringTokenizer st = new StringTokenizer(line); if (st.hasMoreTokens()) { String token = st.nextToken(); if ("REM".equalsIgnoreCase(token)) { continue; } } sql.append(" ").append(line); // SQL defines "--" as a comment to EOL // and in Oracle it may contain a hint // so we cannot just remove it, instead we must end it if (line.indexOf("--") >= 0) { sql.append("\n"); } if ((checkStringBufferEndsWith(sql, delimiter))) { executeSQL(sql.substring(0, sql.length() - delimiter.length()), conn); sql.replace(0, sql.length(), ""); } } // Catch any statements not followed by ; if (sql.length() > 0) { executeSQL(sql.toString(), conn); } }catch (IOException e){ logger.error("Error occurred while executing SQL script for creating Airavata database", e); throw new Exception("Error occurred while executing SQL script for creating Airavata database", e); }finally { if (reader != null) { reader.close(); } } } private static void executeSQL(String sql, Connection conn) throws Exception { // Check and ignore empty statements if ("".equals(sql.trim())) { return; } Statement statement = null; try { logger.debug("SQL : " + sql); boolean ret; int updateCount = 0, updateCountTotal = 0; statement = conn.createStatement(); ret = statement.execute(sql); updateCount = statement.getUpdateCount(); do { if (!ret) { if (updateCount != -1) { updateCountTotal += updateCount; } } ret = statement.getMoreResults(); if (ret) { updateCount = statement.getUpdateCount(); } } while (ret); logger.debug(sql + " : " + updateCountTotal + " rows affected"); SQLWarning warning = conn.getWarnings(); while (warning != null) { logger.warn(warning + " sql warning"); warning = warning.getNextWarning(); } conn.clearWarnings(); } catch (SQLException e) { if (e.getSQLState().equals("X0Y32")) { // eliminating the table already exception for the derby // database logger.info("Table Already Exists", e); } else { throw new Exception("Error occurred while executing : " + sql, e); } } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { logger.error("Error occurred while closing result set.", e); } } } } private void startDerbyInServerMode() { try { System.setProperty(DERBY_SERVER_MODE_SYS_PROPERTY, "true"); server = new NetworkServerControl(InetAddress.getByName(Utils.getHost()), 20000, Utils.getJDBCUser(), Utils.getJDBCPassword()); java.io.PrintWriter consoleWriter = new java.io.PrintWriter(System.out, true); server.start(consoleWriter); } catch (IOException e) { logger.error("Unable to start Apache derby in the server mode! Check whether " + "specified port is available"); } catch (Exception e) { logger.error("Unable to start Apache derby in the server mode! Check whether " + "specified port is available"); } } private void startDerbyInEmbeddedMode(){ try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); DriverManager.getConnection("jdbc:derby:memory:unit-testing-jpa;create=true").close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public void stopDerbyServer() { try { server.shutdown(); } catch (Exception e) { e.printStackTrace(); } } }
9,413
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/Resource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import java.util.List; public interface Resource { /** * This method will create associate resource objects for the given resource type. * @param type child resource type * @return associate child resource */ Resource create(ResourceType type); /** * This method will remove the given child resource from the database * @param type child resource type * @param name child resource name */ void remove(ResourceType type, Object name); /** * This method will return the given child resource from the database * @param type child resource type * @param name child resource name * @return associate child resource */ Resource get(ResourceType type, Object name); /** * This method will list all the child resources for the given resource type * @param type child resource type * @return list of child resources of the given child resource type */ List<Resource> get(ResourceType type); /** * This method will save the resource to the database. */ void save(); /** * This method will check whether an entry from the given resource type and resource name * exists in the database * @param type child resource type * @param name child resource name * @return whether the entry exists in the database or not */ boolean isExists(ResourceType type, Object name); }
9,414
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/ResourceType.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; public enum ResourceType { GATEWAY, PROJECT, USER, SERVICE_DESCRIPTOR, PUBLISHED_WORKFLOW, USER_WORKFLOW, HOST_DESCRIPTOR, APPLICATION_DESCRIPTOR, EXPERIMENT, CONFIGURATION, GATEWAY_WORKER, EXPERIMENT_DATA, EXPERIMENT_METADATA, WORKFLOW_DATA, NODE_DATA, GRAM_DATA, EXECUTION_ERROR, GFAC_JOB_DATA, GFAC_JOB_STATUS }
9,415
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/JPAResourceAccessor.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import org.apache.airavata.persistance.registry.jpa.resources.GatewayResource; import org.apache.airavata.persistance.registry.jpa.resources.WorkerResource; import org.apache.airavata.registry.api.AiravataRegistry2; public class JPAResourceAccessor { private AiravataRegistry2 registry=null; private ResourceUtils resourceUtils = new ResourceUtils(); public JPAResourceAccessor(AiravataRegistry2 registry) { this.registry=registry; } public GatewayResource getGateway(){ GatewayResource gatewayResource = new GatewayResource(); gatewayResource.setGatewayName(this.registry.getGateway().getGatewayName()); return gatewayResource; } public ResourceUtils root(){ return resourceUtils; } public WorkerResource getWorker(){ return new WorkerResource(registry.getUser().getUserName(), getGateway()); } }
9,416
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/ResourceUtils.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityNotFoundException; import javax.persistence.Persistence; import javax.persistence.Query; import org.apache.airavata.persistance.registry.jpa.model.Configuration; import org.apache.airavata.persistance.registry.jpa.model.Configuration_PK; import org.apache.airavata.persistance.registry.jpa.model.Gateway; import org.apache.airavata.persistance.registry.jpa.model.Gateway_Worker; import org.apache.airavata.persistance.registry.jpa.model.Gateway_Worker_PK; import org.apache.airavata.persistance.registry.jpa.model.Users; import org.apache.airavata.persistance.registry.jpa.resources.AbstractResource; import org.apache.airavata.persistance.registry.jpa.resources.ConfigurationResource; import org.apache.airavata.persistance.registry.jpa.resources.GatewayResource; import org.apache.airavata.persistance.registry.jpa.resources.UserResource; import org.apache.airavata.persistance.registry.jpa.resources.Utils; import org.apache.airavata.persistance.registry.jpa.resources.WorkerResource; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.apache.airavata.registry.api.exception.AiravataRegistryUninitializedException; import org.apache.airavata.registry.api.exception.RegistryException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ResourceUtils { private final static Logger logger = LoggerFactory.getLogger(ResourceUtils.class); private static final String PERSISTENCE_UNIT_NAME = "airavata_data"; protected static EntityManagerFactory factory; private static Lock lock = new ReentrantLock(); public static void reset(){ factory=null; } public static EntityManager getEntityManager(){ if (factory == null) { String connectionProperties = "DriverClassName=" + Utils.getJDBCDriver() + "," + "Url=" + Utils.getJDBCURL() + "," + "Username=" + Utils.getJDBCUser() + "," + "Password=" + Utils.getJDBCPassword() + ",validationQuery=" + Utils.getValidationQuery() + "," + Utils.getJPAConnectionProperties(); System.out.println(connectionProperties); Map<String, String> properties = new HashMap<String, String>(); properties.put("openjpa.ConnectionDriverName", "org.apache.commons.dbcp.BasicDataSource"); properties.put("openjpa.ConnectionProperties", connectionProperties); properties.put("openjpa.DynamicEnhancementAgent", "true"); properties.put("openjpa.RuntimeUnenhancedClasses", "unsupported"); properties.put("openjpa.Log", "SQL=ERROR"); // properties.put("openjpa.Log","DefaultLevel=WARN, Runtime=INFO, Tool=INFO, SQL=TRACE"); properties.put("openjpa.ReadLockLevel", "none"); properties.put("openjpa.WriteLockLevel", "none"); properties.put("openjpa.LockTimeout", "30000"); properties.put("openjpa.LockManager", "none"); properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)"); properties.put("openjpa.ConnectionFactoryProperties", "PrettyPrint=true, PrettyPrintLineLength=72, PrintParameters=true, MaxActive=10, MaxIdle=5, MinIdle=2, MaxWait=60000"); properties.put("openjpa.jdbc.QuerySQLCache", "false"); factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, properties); } return factory.createEntityManager(); } /** * @param gatewayName * @return */ public static Resource createGateway(String gatewayName){ if (!isGatewayExist(gatewayName)) { GatewayResource gatewayResource = new GatewayResource(); gatewayResource.setGatewayName(gatewayName); return gatewayResource; } return null; } public static Resource getGateway(String gatewayName){ if (isGatewayExist(gatewayName)) { EntityManager em = getEntityManager(); Gateway gateway = em.find(Gateway.class, gatewayName); GatewayResource gatewayResource = (GatewayResource)Utils.getResource(ResourceType.GATEWAY, gateway); em.close(); return gatewayResource; } return null; } public static Resource getWorker(String gatewayName, String userName){ EntityManager em = getEntityManager(); Gateway_Worker gatewayWorker = em.find(Gateway_Worker.class, new Gateway_Worker_PK(gatewayName, userName)); WorkerResource workerResource = (WorkerResource) Utils.getResource(ResourceType.GATEWAY_WORKER, gatewayWorker); em.close(); return workerResource; } /** * @param gatewayName * @return */ public static boolean isGatewayExist(String gatewayName){ EntityManager em = getEntityManager(); em.getTransaction().begin(); QueryGenerator generator = new QueryGenerator(AbstractResource.GATEWAY); generator.setParameter(AbstractResource.GatewayConstants.GATEWAY_NAME, gatewayName); Query q = generator.selectQuery(em); int size = q.getResultList().size(); em.getTransaction().commit(); em.close(); return size>0; } /** * @param gatewayName * @return */ public static boolean removeGateway(String gatewayName) { try { EntityManager em = getEntityManager(); em.getTransaction().begin(); QueryGenerator generator = new QueryGenerator(AbstractResource.GATEWAY); generator.setParameter(AbstractResource.GatewayConstants.GATEWAY_NAME, gatewayName); Query q = generator.deleteQuery(em); q.executeUpdate(); em.getTransaction().commit(); em.close(); return true; } catch (Exception e) { logger.error(e.getMessage(), e); return false; } } /** * @param gatewayResource * @param userResource */ public static void addGatewayWorker(GatewayResource gatewayResource, UserResource userResource) { try { EntityManager em = getEntityManager(); em.getTransaction().begin(); Gateway gateway = new Gateway(); gateway.setGateway_name(gatewayResource.getGatewayName()); Users user = new Users(); user.setUser_name(userResource.getUserName()); Gateway_Worker gatewayWorker = new Gateway_Worker(); gatewayWorker.setGateway(gateway); gatewayWorker.setUser(user); em.persist(gatewayWorker); em.getTransaction().commit(); em.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } } /** * @param gatewayResource * @param userResource * @return */ public static boolean removeGatewayWorker(GatewayResource gatewayResource, UserResource userResource) { try { EntityManager em = getEntityManager(); em.getTransaction().begin(); QueryGenerator generator = new QueryGenerator(AbstractResource.GATEWAY_WORKER); generator.setParameter(AbstractResource.GatewayWorkerConstants.GATEWAY_NAME, gatewayResource.getGatewayName()); generator.setParameter(AbstractResource.UserConstants.USERNAME, userResource.getUserName()); Query q = generator.deleteQuery(em); q.executeUpdate(); em.getTransaction().commit(); em.close(); return true; } catch (Exception e) { logger.error(e.getMessage(), e); return false; } } /** * @param configKey * @return */ public static List<ConfigurationResource> getConfigurations(String configKey){ List<ConfigurationResource> list = new ArrayList<ConfigurationResource>(); EntityManager em = getEntityManager(); em.getTransaction().begin(); QueryGenerator generator = new QueryGenerator(AbstractResource.CONFIGURATION); generator.setParameter(AbstractResource.ConfigurationConstants.CONFIG_KEY, configKey); Query q = generator.selectQuery(em); List<?> resultList = q.getResultList(); if (resultList.size() != 0) { for (Object result : resultList) { ConfigurationResource configurationResource = createConfigurationResourceObject(result); list.add(configurationResource); } } em.getTransaction().commit(); em.close(); return list; } /** * @param configKey * @return */ public static ConfigurationResource getConfiguration(String configKey){ List<ConfigurationResource> configurations = getConfigurations(configKey); return (configurations != null && configurations.size() > 0) ? configurations.get(0) : null; } /** * @param configKey * @return */ public static boolean isConfigurationExist(String configKey){ List<ConfigurationResource> configurations = getConfigurations(configKey); return (configurations != null && configurations.size() > 0); } /** * @param configKey * @return */ public static ConfigurationResource createConfiguration(String configKey) { ConfigurationResource config = new ConfigurationResource(); config.setConfigKey(configKey); return config; } /** * @param result * @return */ private static ConfigurationResource createConfigurationResourceObject( Object result) { Configuration configuration = (Configuration) result; ConfigurationResource configurationResource = new ConfigurationResource(configuration.getConfig_key(), configuration.getConfig_val()); configurationResource.setExpireDate(configuration.getExpire_date()); return configurationResource; } /** * @param configkey * @param configValue */ public static void removeConfiguration(String configkey, String configValue){ QueryGenerator queryGenerator = new QueryGenerator(AbstractResource.CONFIGURATION); queryGenerator.setParameter(AbstractResource.ConfigurationConstants.CONFIG_KEY, configkey); queryGenerator.setParameter(AbstractResource.ConfigurationConstants.CONFIG_VAL, configValue); if(isConfigurationExists(configkey, configValue)){ EntityManager em = getEntityManager(); em.getTransaction().begin(); Query q = queryGenerator.deleteQuery(em); q.executeUpdate(); em.getTransaction().commit(); em.close(); } } /** * @param configkey */ public static void removeConfiguration(String configkey){ QueryGenerator queryGenerator = new QueryGenerator(AbstractResource.CONFIGURATION); queryGenerator.setParameter(AbstractResource.ConfigurationConstants.CONFIG_KEY, configkey); if(isConfigurationExist(configkey)){ EntityManager em = getEntityManager(); em.getTransaction().begin(); Query q = queryGenerator.deleteQuery(em); q.executeUpdate(); em.getTransaction().commit(); em.close(); } } public static boolean isConfigurationExists(String configKey, String configVal){ try{ //Currently categoryID is hardcoded value EntityManager em = ResourceUtils.getEntityManager(); Configuration existing = em.find(Configuration.class, new Configuration_PK(configKey, configVal, AbstractResource.ConfigurationConstants.CATEGORY_ID_DEFAULT_VALUE)); em.close(); return existing!= null; } catch (Exception e){ logger.error(e.getMessage(), e); throw new EntityNotFoundException(); } } public static Lock getLock() { return lock; } }
9,417
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/JPAConstants.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa; public class JPAConstants { public static final String KEY_JDBC_URL = "registry.jdbc.url"; public static final String KEY_JDBC_USER = "registry.jdbc.user"; public static final String KEY_JDBC_PASSWORD = "registry.jdbc.password"; public static final String KEY_JDBC_DRIVER = "registry.jdbc.driver"; public static final String KEY_DERBY_START_ENABLE = "start.derby.server.mode"; public static final String VALIDATION_QUERY = "validationQuery"; public static final String CONNECTION_JPA_PROPERTY = "jpa.connection.properties"; }
9,418
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/impl/AiravataJPARegistry.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.impl; import java.net.URI; import java.net.URISyntaxException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.apache.airavata.common.exception.AiravataConfigurationException; import org.apache.airavata.common.utils.AiravataJobState; import org.apache.airavata.common.utils.DBUtil; import org.apache.airavata.common.utils.Version; import org.apache.airavata.commons.gfac.type.ApplicationDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential; import org.apache.airavata.credential.store.credential.impl.ssh.SSHCredentialGenerator; import org.apache.airavata.credential.store.store.CredentialReader; import org.apache.airavata.credential.store.store.CredentialStoreException; import org.apache.airavata.credential.store.store.CredentialWriter; import org.apache.airavata.credential.store.store.impl.CredentialReaderImpl; import org.apache.airavata.credential.store.store.impl.SSHCredentialWriter; import org.apache.airavata.persistance.registry.jpa.JPAResourceAccessor; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.resources.ApplicationDescriptorResource; import org.apache.airavata.persistance.registry.jpa.resources.ConfigurationResource; import org.apache.airavata.persistance.registry.jpa.resources.ExecutionErrorResource; import org.apache.airavata.persistance.registry.jpa.resources.ExperimentDataResource; import org.apache.airavata.persistance.registry.jpa.resources.ExperimentDataRetriever; import org.apache.airavata.persistance.registry.jpa.resources.ExperimentMetadataResource; import org.apache.airavata.persistance.registry.jpa.resources.ExperimentResource; import org.apache.airavata.persistance.registry.jpa.resources.GFacJobDataResource; import org.apache.airavata.persistance.registry.jpa.resources.GFacJobStatusResource; import org.apache.airavata.persistance.registry.jpa.resources.GatewayResource; import org.apache.airavata.persistance.registry.jpa.resources.HostDescriptorResource; import org.apache.airavata.persistance.registry.jpa.resources.NodeDataResource; import org.apache.airavata.persistance.registry.jpa.resources.ProjectResource; import org.apache.airavata.persistance.registry.jpa.resources.PublishWorkflowResource; import org.apache.airavata.persistance.registry.jpa.resources.ServiceDescriptorResource; import org.apache.airavata.persistance.registry.jpa.resources.UserResource; import org.apache.airavata.persistance.registry.jpa.resources.UserWorkflowResource; import org.apache.airavata.persistance.registry.jpa.resources.WorkerResource; import org.apache.airavata.persistance.registry.jpa.resources.WorkflowDataResource; import org.apache.airavata.registry.api.AiravataExperiment; import org.apache.airavata.registry.api.AiravataRegistry2; import org.apache.airavata.registry.api.AiravataRegistryFactory; import org.apache.airavata.registry.api.AiravataSubRegistry; import org.apache.airavata.registry.api.AiravataUser; import org.apache.airavata.registry.api.ConfigurationRegistry; import org.apache.airavata.registry.api.DescriptorRegistry; import org.apache.airavata.registry.api.ExecutionErrors; import org.apache.airavata.registry.api.ExecutionErrors.Source; import org.apache.airavata.registry.api.Gateway; import org.apache.airavata.registry.api.PasswordCallback; import org.apache.airavata.registry.api.ProjectsRegistry; import org.apache.airavata.registry.api.ProvenanceRegistry; import org.apache.airavata.registry.api.PublishedWorkflowRegistry; import org.apache.airavata.registry.api.ResourceMetadata; import org.apache.airavata.registry.api.UserRegistry; import org.apache.airavata.registry.api.UserWorkflowRegistry; import org.apache.airavata.registry.api.WorkspaceProject; import org.apache.airavata.registry.api.exception.AiravataRegistryUninitializedException; import org.apache.airavata.registry.api.exception.GatewayNotRegisteredException; import org.apache.airavata.registry.api.exception.RegistryAPIVersionIncompatibleException; import org.apache.airavata.registry.api.exception.RegistryAccessorInstantiateException; import org.apache.airavata.registry.api.exception.RegistryAccessorNotFoundException; import org.apache.airavata.registry.api.exception.RegistryAccessorUndefinedException; import org.apache.airavata.registry.api.exception.RegistryException; import org.apache.airavata.registry.api.exception.RegistrySettingsException; import org.apache.airavata.registry.api.exception.UnimplementedRegistryOperationException; import org.apache.airavata.registry.api.exception.gateway.DescriptorAlreadyExistsException; import org.apache.airavata.registry.api.exception.gateway.DescriptorDoesNotExistsException; import org.apache.airavata.registry.api.exception.gateway.InsufficientDataException; import org.apache.airavata.registry.api.exception.gateway.MalformedDescriptorException; import org.apache.airavata.registry.api.exception.gateway.PublishedWorkflowAlreadyExistsException; import org.apache.airavata.registry.api.exception.gateway.PublishedWorkflowDoesNotExistsException; import org.apache.airavata.registry.api.exception.worker.ExperimentDoesNotExistsException; import org.apache.airavata.registry.api.exception.worker.ExperimentLazyLoadedException; import org.apache.airavata.registry.api.exception.worker.ApplicationJobAlreadyExistsException; import org.apache.airavata.registry.api.exception.worker.ApplicationJobDoesNotExistsException; import org.apache.airavata.registry.api.exception.worker.InvalidApplicationJobIDException; import org.apache.airavata.registry.api.exception.worker.UserWorkflowAlreadyExistsException; import org.apache.airavata.registry.api.exception.worker.UserWorkflowDoesNotExistsException; import org.apache.airavata.registry.api.exception.worker.WorkflowInstanceAlreadyExistsException; import org.apache.airavata.registry.api.exception.worker.WorkflowInstanceDoesNotExistsException; import org.apache.airavata.registry.api.exception.worker.WorkflowInstanceNodeAlreadyExistsException; import org.apache.airavata.registry.api.exception.worker.WorkflowInstanceNodeDoesNotExistsException; import org.apache.airavata.registry.api.exception.worker.WorkspaceProjectAlreadyExistsException; import org.apache.airavata.registry.api.exception.worker.WorkspaceProjectDoesNotExistsException; import org.apache.airavata.registry.api.impl.WorkflowExecutionDataImpl; import org.apache.airavata.registry.api.util.RegistryConstants; import org.apache.airavata.registry.api.util.RegistrySettings; import org.apache.airavata.registry.api.workflow.ApplicationJobStatusData; import org.apache.airavata.registry.api.workflow.ExecutionError; import org.apache.airavata.registry.api.workflow.ExperimentData; import org.apache.airavata.registry.api.workflow.ExperimentExecutionError; import org.apache.airavata.registry.api.workflow.ApplicationJob; import org.apache.airavata.registry.api.workflow.ApplicationJob.ApplicationJobStatus; import org.apache.airavata.registry.api.workflow.ApplicationJobExecutionError; import org.apache.airavata.registry.api.workflow.NodeExecutionData; import org.apache.airavata.registry.api.workflow.NodeExecutionError; import org.apache.airavata.registry.api.workflow.NodeExecutionStatus; import org.apache.airavata.registry.api.workflow.WorkflowExecution; import org.apache.airavata.registry.api.workflow.WorkflowExecutionData; import org.apache.airavata.registry.api.workflow.WorkflowExecutionError; import org.apache.airavata.registry.api.workflow.WorkflowExecutionStatus; import org.apache.airavata.registry.api.workflow.WorkflowExecutionStatus.State; import org.apache.airavata.registry.api.workflow.WorkflowIOData; import org.apache.airavata.registry.api.workflow.WorkflowInstanceNode; import org.apache.airavata.registry.api.workflow.WorkflowNodeGramData; import org.apache.airavata.registry.api.workflow.WorkflowNodeIOData; import org.apache.airavata.registry.api.workflow.WorkflowNodeType; import org.apache.xmlbeans.XmlException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class AiravataJPARegistry extends AiravataRegistry2{ private final static Logger logger = LoggerFactory.getLogger(AiravataJPARegistry.class); private static Map<String, String[]> compatibleVersionMap; private static int CONNECT_FAIL_WAIT_TIME=1000; private static int MAX_TRIES=15; private static final String DEFAULT_PROJECT_NAME = "default"; private static final Version API_VERSION=new Version("Airavata Registry API",0,11,null,null,null); private JPAResourceAccessor jpa; private boolean active=false; private URI registryConnectionURI; private ConfigurationRegistry configurationRegistry; private DescriptorRegistry descriptorRegistry; private ProjectsRegistry projectsRegistry; private ProvenanceRegistry provenanceRegistry; private UserWorkflowRegistry userWorkflowRegistry; private PublishedWorkflowRegistry publishedWorkflowRegistry; private UserRegistry userRegistry; private PasswordCallback callback; private CredentialReader credentialReader; private CredentialWriter credentialWriter; private SSHCredentialGenerator credentialGenerator; @Override protected void initialize() throws RegistryException { jpa = new JPAResourceAccessor(this); //TODO check if the db connections are proper & accessible & the relevant db/tables are //present active=true; initializeCustomRegistries(); String apiVersion = getVersion().toString(); String registryVersion; int tries=0; while(true){ try { tries++; registryVersion = getConfiguration("registry.version").toString(); if (System.getProperty("registry.initialize.state")==null){ //lets wait a few seconds for the initialization to complete Thread.sleep(CONNECT_FAIL_WAIT_TIME*5); } else { while(System.getProperty("registry.initialize.state").equals("0")){ Thread.sleep(CONNECT_FAIL_WAIT_TIME); } } break; } catch (Exception e) { ResourceUtils.reset(); if (tries<MAX_TRIES){ try { Thread.sleep(CONNECT_FAIL_WAIT_TIME); } catch (InterruptedException e1) { e1.printStackTrace(); } }else{ throw new AiravataRegistryUninitializedException("Airavata Registry has not yet initialized properly!!!", e); } } } String[] list = compatibleVersionMap.get(apiVersion); if (list == null || (!Arrays.asList(list).contains(registryVersion))){ throw new RegistryAPIVersionIncompatibleException("Incompatible registry versions. Please check whether you updated the API and Registry " + "versions."); } if (!ResourceUtils.isGatewayExist(getGateway().getGatewayName())){ throw new GatewayNotRegisteredException(getGateway().getGatewayName()); } } static { compatibleVersionMap = new HashMap<String, String[]>(); compatibleVersionMap.put("0.6", new String[]{"0.6"}); compatibleVersionMap.put("0.7", new String[]{"0.6", "0.7"}); compatibleVersionMap.put("0.8", new String[]{"0.8"}); compatibleVersionMap.put("0.9", new String[]{"0.9","0.8"}); compatibleVersionMap.put("0.10", new String[]{"0.10","0.9", "0.8"}); compatibleVersionMap.put("0.11", new String[]{"0.11","0.10","0.9", "0.8"}); } /** * Initialize the custom registries defined in the registry settings * @throws RegistryException */ private void initializeCustomRegistries() throws RegistryException { // retrieving user defined registry classes from registry settings try { configurationRegistry = (ConfigurationRegistry)getClassInstance(ConfigurationRegistry.class,RegistryConstants.CONFIGURATION_REGISTRY_ACCESSOR_CLASS); descriptorRegistry = (DescriptorRegistry)getClassInstance(ConfigurationRegistry.class,RegistryConstants.DESCRIPTOR_REGISTRY_ACCESSOR_CLASS); projectsRegistry = (ProjectsRegistry)getClassInstance(ConfigurationRegistry.class,RegistryConstants.PROJECT_REGISTRY_ACCESSOR_CLASS); provenanceRegistry = (ProvenanceRegistry)getClassInstance(ConfigurationRegistry.class,RegistryConstants.PROVENANCE_REGISTRY_ACCESSOR_CLASS); userWorkflowRegistry = (UserWorkflowRegistry)getClassInstance(ConfigurationRegistry.class,RegistryConstants.USER_WF_REGISTRY_ACCESSOR_CLASS); publishedWorkflowRegistry = (PublishedWorkflowRegistry)getClassInstance(ConfigurationRegistry.class,RegistryConstants.PUBLISHED_WF_REGISTRY_ACCESSOR_CLASS); userRegistry = (UserRegistry)getClassInstance(ConfigurationRegistry.class,RegistryConstants.USER_REGISTRY_ACCESSOR_CLASS); } catch (AiravataConfigurationException e) { throw new RegistryException("An error occured when attempting to determine any custom implementations of the registries!!!", e); } } private <T extends AiravataSubRegistry> Object getClassInstance(Class<T> c, String registryAccessorKey) throws AiravataConfigurationException{ try { T registryClass = c.cast(AiravataRegistryFactory.getRegistryClass(registryAccessorKey)); registryClass.setAiravataRegistry(this); return registryClass; } catch (ClassCastException e){ logger.error("The class defined for accessor type "+registryAccessorKey+" MUST be an extention of the interface "+c.getName(),e); } catch (RegistryAccessorNotFoundException e) { logger.error("Error in loading class for registry accessor "+registryAccessorKey,e); } catch (RegistryAccessorUndefinedException e) { // happens when user has not defined an accessor for the registry accessor key // thus ignore error } catch (RegistryAccessorInstantiateException e) { logger.error("Error in instantiating instance from class for registry accessor "+registryAccessorKey,e); } return null; } @Override public boolean isActive() { return active; } /**---------------------------------Configuration Registry----------------------------------**/ public Object getConfiguration(String key) throws RegistryException{ ConfigurationResource configuration = ResourceUtils.getConfiguration(key); return configuration==null? null: configuration.getConfigVal(); } // Not sure about this.. need some description public List<Object> getConfigurationList(String key) throws RegistryException{ if (configurationRegistry != null){ return configurationRegistry.getConfigurationList(key); } else { List<Object> values = new ArrayList<Object>(); List<ConfigurationResource> configurations = ResourceUtils.getConfigurations(key); for (ConfigurationResource configurationResource : configurations) { values.add(configurationResource.getConfigVal()); } return values; } } public void setConfiguration(String key, String value, Date expire) throws RegistryException{ if (configurationRegistry != null){ configurationRegistry.setConfiguration(key, value, expire); }else { ConfigurationResource config; if (ResourceUtils.isConfigurationExist(key)) { config = ResourceUtils.getConfiguration(key); }else{ config = ResourceUtils.createConfiguration(key); } config.setConfigVal(value); config.setExpireDate(new Timestamp(expire.getTime())); config.save(); } } public void addConfiguration(String key, String value, Date expire) throws RegistryException{ if (configurationRegistry != null){ configurationRegistry.addConfiguration(key, value, expire); } else { ConfigurationResource config = ResourceUtils.createConfiguration(key); config.setConfigVal(value); config.setExpireDate(new Timestamp(expire.getTime())); config.save(); } } public void removeAllConfiguration(String key) throws RegistryException{ if (configurationRegistry != null){ configurationRegistry.removeAllConfiguration(key); } else { ResourceUtils.removeConfiguration(key); } } public void removeConfiguration(String key, String value) throws RegistryException{ if (configurationRegistry != null){ configurationRegistry.removeConfiguration(key, value); } else { ResourceUtils.removeConfiguration(key, value); } } private static final String GFAC_URL="gfac.url"; private static final String INTERPRETER_URL="interpreter.url"; private static final String MESSAGE_BOX_URL="messagebox.url"; private static final String EVENTING_URL="eventing.url"; public List<URI> getGFacURIs() throws RegistryException{ if (configurationRegistry != null) { return configurationRegistry.getGFacURIs(); } else { return retrieveURIsFromConfiguration(GFAC_URL); } } private List<URI> retrieveURIsFromConfiguration(String urlType) throws RegistryException{ List<URI> urls=new ArrayList<URI>(); List<Object> configurationList = getConfigurationList(urlType); for (Object o : configurationList) { try { urls.add(new URI(o.toString())); } catch (URISyntaxException e) { e.printStackTrace(); } } return urls; } public List<URI> getWorkflowInterpreterURIs() throws RegistryException{ if (configurationRegistry != null) { return configurationRegistry.getWorkflowInterpreterURIs(); } else { return retrieveURIsFromConfiguration(INTERPRETER_URL); } } public URI getEventingServiceURI() throws RegistryException{ if (configurationRegistry != null) { return configurationRegistry.getEventingServiceURI(); }else { List<URI> eventingURLs = retrieveURIsFromConfiguration(EVENTING_URL); return eventingURLs.size()==0? null: eventingURLs.get(0); } } public URI getMessageBoxURI() throws RegistryException{ if (configurationRegistry != null) { return configurationRegistry.getMessageBoxURI(); } List<URI> messageboxURLs = retrieveURIsFromConfiguration(MESSAGE_BOX_URL); return messageboxURLs.size()==0? null: messageboxURLs.get(0); } public void addGFacURI(URI uri) throws RegistryException{ if (configurationRegistry != null) { addGFacURI(uri); } else { addConfigurationURL(GFAC_URL, uri); } } private void addConfigurationURL(String urlType,URI uri) throws RegistryException{ Calendar instance = Calendar.getInstance(); instance.add(Calendar.MINUTE, AiravataRegistry2.SERVICE_TTL); Date expire = instance.getTime(); addConfigurationURL(urlType, uri, expire); } private void addConfigurationURL(String urlType, URI uri, Date expire) throws RegistryException{ addConfiguration(urlType, uri.toString(), expire); } public void addWorkflowInterpreterURI(URI uri) throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.addWorkflowInterpreterURI(uri); }else { addConfigurationURL(INTERPRETER_URL,uri); } } public void setEventingURI(URI uri) throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.setEventingURI(uri); } else { addConfigurationURL(EVENTING_URL,uri); } } public void setMessageBoxURI(URI uri) throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.setMessageBoxURI(uri); } else { addConfigurationURL(MESSAGE_BOX_URL,uri); } } public void addGFacURI(URI uri, Date expire) throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.addGFacURI(uri, expire); } else { addConfigurationURL(GFAC_URL, uri, expire); } } public void addWorkflowInterpreterURI(URI uri, Date expire) throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.addWorkflowInterpreterURI(uri, expire); } else { addConfigurationURL(INTERPRETER_URL, uri, expire); } } public void setEventingURI(URI uri, Date expire) throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.setEventingURI(uri, expire); } else { addConfigurationURL(EVENTING_URL, uri, expire); } } public void setMessageBoxURI(URI uri, Date expire) throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.setMessageBoxURI(uri, expire); } else { addConfigurationURL(MESSAGE_BOX_URL, uri, expire); } } public void removeGFacURI(URI uri) throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.removeGFacURI(uri); } else { removeConfiguration(GFAC_URL, uri.toString()); } } public void removeWorkflowInterpreterURI(URI uri) throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.removeWorkflowInterpreterURI(uri); } else { removeConfiguration(INTERPRETER_URL, uri.toString()); } } public void removeAllGFacURI() throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.removeAllGFacURI(); } else { removeAllConfiguration(GFAC_URL); } } public void removeAllWorkflowInterpreterURI() throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.removeAllWorkflowInterpreterURI(); } else { removeAllConfiguration(INTERPRETER_URL); } } public void unsetEventingURI() throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.unsetEventingURI(); } else { removeAllConfiguration(EVENTING_URL); } } public void unsetMessageBoxURI() throws RegistryException{ if (configurationRegistry != null) { configurationRegistry.unsetMessageBoxURI(); } else { removeAllConfiguration(MESSAGE_BOX_URL); } } /**---------------------------------Descriptor Registry----------------------------------**/ public boolean isHostDescriptorExists(String descriptorName)throws RegistryException{ if (descriptorRegistry != null){ return descriptorRegistry.isHostDescriptorExists(descriptorName); } return jpa.getGateway().isHostDescriptorExists(descriptorName); } public void addHostDescriptor(HostDescription descriptor) throws RegistryException { if (descriptorRegistry != null){ descriptorRegistry.addHostDescriptor(descriptor); } else { GatewayResource gateway = jpa.getGateway(); WorkerResource workerResource = jpa.getWorker(); String hostName = descriptor.getType().getHostName(); if (isHostDescriptorExists(hostName)){ throw new DescriptorAlreadyExistsException(hostName); } HostDescriptorResource hostDescriptorResource = gateway.createHostDescriptorResource(hostName); hostDescriptorResource.setUserName(workerResource.getUser()); hostDescriptorResource.setContent(descriptor.toXML()); hostDescriptorResource.save(); } } public void updateHostDescriptor(HostDescription descriptor) throws RegistryException { if (descriptorRegistry != null){ descriptorRegistry.updateHostDescriptor(descriptor); } else { GatewayResource gateway = jpa.getGateway(); String hostName = descriptor.getType().getHostName(); if (!isHostDescriptorExists(hostName)){ throw new DescriptorDoesNotExistsException(hostName); } HostDescriptorResource hostDescriptorResource = gateway.getHostDescriptorResource(hostName); hostDescriptorResource.setContent(descriptor.toXML()); hostDescriptorResource.save(); } } public HostDescription getHostDescriptor(String hostName) throws RegistryException { if (descriptorRegistry != null){ return descriptorRegistry.getHostDescriptor(hostName); } else { GatewayResource gateway = jpa.getGateway(); if (!isHostDescriptorExists(hostName)){ return null; } HostDescriptorResource hostDescriptorResource = gateway.getHostDescriptorResource(hostName); return createHostDescriptor(hostDescriptorResource); } } private HostDescription createHostDescriptor( HostDescriptorResource hostDescriptorResource) throws MalformedDescriptorException { try { return HostDescription.fromXML(hostDescriptorResource.getContent()); } catch (XmlException e) { throw new MalformedDescriptorException(hostDescriptorResource.getHostDescName(),e); } } public void removeHostDescriptor(String hostName) throws RegistryException { if (descriptorRegistry != null){ descriptorRegistry.removeHostDescriptor(hostName); } else { GatewayResource gateway = jpa.getGateway(); if (!isHostDescriptorExists(hostName)){ throw new DescriptorDoesNotExistsException(hostName); } gateway.removeHostDescriptor(hostName); try { //we need to delete the application descriptors bound to this host Map<String, ApplicationDescription> applicationDescriptors = getApplicationDescriptorsFromHostName(hostName); for (String serviceName : applicationDescriptors.keySet()) { removeApplicationDescriptor(serviceName, hostName, applicationDescriptors.get(serviceName).getType().getApplicationName().getStringValue()); } } catch (Exception e) { logger.error("Error while removing application descriptors bound to host "+hostName, e); } } } @Override public List<HostDescription> getHostDescriptors() throws MalformedDescriptorException, RegistryException { if (descriptorRegistry != null){ return descriptorRegistry.getHostDescriptors(); } GatewayResource gateway = jpa.getGateway(); List<HostDescription> list=new ArrayList<HostDescription>(); List<HostDescriptorResource> hostDescriptorResources = gateway.getHostDescriptorResources(); for (HostDescriptorResource resource : hostDescriptorResources) { list.add(createHostDescriptor(resource)); } return list; } public ResourceMetadata getHostDescriptorMetadata(String hostName) throws RegistryException { if (descriptorRegistry != null) { return descriptorRegistry.getHostDescriptorMetadata(hostName); } //TODO throw new UnimplementedRegistryOperationException(); } public boolean isServiceDescriptorExists(String descriptorName)throws RegistryException{ if (descriptorRegistry != null) { return descriptorRegistry.isServiceDescriptorExists(descriptorName); } return jpa.getGateway().isServiceDescriptorExists(descriptorName); } public void addServiceDescriptor(ServiceDescription descriptor) throws RegistryException { if (descriptorRegistry != null) { descriptorRegistry.addServiceDescriptor(descriptor); }else { GatewayResource gateway = jpa.getGateway(); WorkerResource workerResource = jpa.getWorker(); String serviceName = descriptor.getType().getName(); if (isServiceDescriptorExists(serviceName)){ throw new DescriptorAlreadyExistsException(serviceName); } ServiceDescriptorResource serviceDescriptorResource = gateway.createServiceDescriptorResource(serviceName); serviceDescriptorResource.setUserName(workerResource.getUser()); serviceDescriptorResource.setContent(descriptor.toXML()); serviceDescriptorResource.save(); } } public void updateServiceDescriptor(ServiceDescription descriptor) throws RegistryException { if (descriptorRegistry != null) { descriptorRegistry.updateServiceDescriptor(descriptor); }else { GatewayResource gateway = jpa.getGateway(); String serviceName = descriptor.getType().getName(); if (!isServiceDescriptorExists(serviceName)){ throw new DescriptorDoesNotExistsException(serviceName); } ServiceDescriptorResource serviceDescriptorResource = gateway.getServiceDescriptorResource(serviceName); serviceDescriptorResource.setContent(descriptor.toXML()); serviceDescriptorResource.save(); } } public ServiceDescription getServiceDescriptor(String serviceName) throws RegistryException, MalformedDescriptorException { if (descriptorRegistry != null) { return descriptorRegistry.getServiceDescriptor(serviceName); }else { GatewayResource gateway = jpa.getGateway(); if (!gateway.isServiceDescriptorExists(serviceName)){ return null; } ServiceDescriptorResource serviceDescriptorResource = gateway.getServiceDescriptorResource(serviceName); return createServiceDescriptor(serviceDescriptorResource); } } private ServiceDescription createServiceDescriptor( ServiceDescriptorResource serviceDescriptorResource) throws MalformedDescriptorException { try { return ServiceDescription.fromXML(serviceDescriptorResource.getContent()); } catch (XmlException e) { throw new MalformedDescriptorException(serviceDescriptorResource.getServiceDescName(),e); } } public void removeServiceDescriptor(String serviceName) throws RegistryException { if (descriptorRegistry != null) { descriptorRegistry.removeServiceDescriptor(serviceName); }else { GatewayResource gateway = jpa.getGateway(); if (!isServiceDescriptorExists(serviceName)){ throw new DescriptorDoesNotExistsException(serviceName); } gateway.removeServiceDescriptor(serviceName); try { //we need to delete the application descriptors bound to this service Map<String, ApplicationDescription> applicationDescriptors = getApplicationDescriptors(serviceName); for (String hostName : applicationDescriptors.keySet()) { removeApplicationDescriptor(serviceName, hostName, applicationDescriptors.get(hostName).getType().getApplicationName().getStringValue()); } } catch (Exception e) { logger.error("Error while removing application descriptors bound to service "+serviceName, e); } } } @Override public List<ServiceDescription> getServiceDescriptors() throws MalformedDescriptorException, RegistryException { if (descriptorRegistry != null) { return descriptorRegistry.getServiceDescriptors(); }else { GatewayResource gateway = jpa.getGateway(); List<ServiceDescription> list=new ArrayList<ServiceDescription>(); List<ServiceDescriptorResource> serviceDescriptorResources = gateway.getServiceDescriptorResources(); for (ServiceDescriptorResource resource : serviceDescriptorResources) { list.add(createServiceDescriptor(resource)); } return list; } } public ResourceMetadata getServiceDescriptorMetadata(String serviceName) throws RegistryException { if (descriptorRegistry != null) { return descriptorRegistry.getServiceDescriptorMetadata(serviceName); }else { //TODO throw new UnimplementedRegistryOperationException(); } } private String createAppName(String serviceName, String hostName, String applicationName){ return serviceName+"/"+hostName+"/"+applicationName; } public boolean isApplicationDescriptorExists(String serviceName, String hostName, String descriptorName)throws RegistryException{ if (descriptorRegistry != null) { return descriptorRegistry.isApplicationDescriptorExists(serviceName, hostName, descriptorName); }else { return jpa.getGateway().isApplicationDescriptorExists(createAppName(serviceName, hostName, descriptorName)); } } public void addApplicationDescriptor(ServiceDescription serviceDescription, HostDescription hostDescriptor, ApplicationDescription descriptor) throws RegistryException { if (descriptorRegistry != null) { descriptorRegistry.addApplicationDescriptor(serviceDescription, hostDescriptor, descriptor); }else { addApplicationDescriptor(serviceDescription.getType().getName(), hostDescriptor.getType().getHostName(), descriptor); } } public void addApplicationDescriptor(String serviceName, String hostName, ApplicationDescription descriptor) throws RegistryException { if (descriptorRegistry != null){ descriptorRegistry.addApplicationDescriptor(serviceName, hostName, descriptor); } else { if (serviceName==null || hostName==null){ throw new InsufficientDataException("Service name or Host name cannot be null"); } GatewayResource gateway = jpa.getGateway(); WorkerResource workerResource = jpa.getWorker(); String applicationName = descriptor.getType().getApplicationName().getStringValue(); applicationName = createAppName(serviceName, hostName, applicationName); if (isApplicationDescriptorExists(serviceName,hostName,descriptor.getType().getApplicationName().getStringValue())){ throw new DescriptorAlreadyExistsException(applicationName); } ApplicationDescriptorResource applicationDescriptorResource = gateway.createApplicationDescriptorResource(applicationName); applicationDescriptorResource.setUpdatedUser(workerResource.getUser()); applicationDescriptorResource.setServiceDescName(serviceName); applicationDescriptorResource.setHostDescName(hostName); applicationDescriptorResource.setContent(descriptor.toXML()); applicationDescriptorResource.save(); } } public void udpateApplicationDescriptor(ServiceDescription serviceDescription, HostDescription hostDescriptor, ApplicationDescription descriptor) throws RegistryException { if (descriptorRegistry != null){ descriptorRegistry.udpateApplicationDescriptor(serviceDescription,hostDescriptor,descriptor); } else { updateApplicationDescriptor(serviceDescription.getType().getName(),hostDescriptor.getType().getHostName(),descriptor); } } public void updateApplicationDescriptor(String serviceName, String hostName, ApplicationDescription descriptor) throws RegistryException { if (descriptorRegistry != null){ descriptorRegistry.updateApplicationDescriptor(serviceName, hostName, descriptor); } else { if (serviceName==null || hostName==null){ throw new InsufficientDataException("Service name or Host name cannot be null"); } GatewayResource gateway = jpa.getGateway(); String applicationName = descriptor.getType().getApplicationName().getStringValue(); applicationName = createAppName(serviceName, hostName, applicationName); if (!isApplicationDescriptorExists(serviceName,hostName,descriptor.getType().getApplicationName().getStringValue())){ throw new DescriptorDoesNotExistsException(applicationName); } ApplicationDescriptorResource serviceDescriptorResource = gateway.getApplicationDescriptorResource(applicationName); serviceDescriptorResource.setContent(descriptor.toXML()); serviceDescriptorResource.save(); } } private ApplicationDescription createApplicationDescriptor( ApplicationDescriptorResource applicationDescriptorResource) throws MalformedDescriptorException { try { return ApplicationDescription.fromXML(applicationDescriptorResource.getContent()); } catch (XmlException e) { throw new MalformedDescriptorException(applicationDescriptorResource.getName(),e); } } public ApplicationDescription getApplicationDescriptor(String serviceName, String hostname, String applicationName)throws DescriptorDoesNotExistsException, MalformedDescriptorException, RegistryException{ if (descriptorRegistry != null){ return descriptorRegistry.getApplicationDescriptor(serviceName, hostname, applicationName); } if (serviceName==null || hostname==null){ throw new InsufficientDataException("Service name or Host name cannot be null"); } GatewayResource gateway = jpa.getGateway(); if (!isApplicationDescriptorExists(serviceName,hostname,applicationName)){ throw new DescriptorDoesNotExistsException(createAppName(serviceName, hostname, applicationName)); } return createApplicationDescriptor(gateway.getApplicationDescriptorResource(createAppName(serviceName, hostname, applicationName))); } public ApplicationDescription getApplicationDescriptors(String serviceName, String hostname) throws RegistryException { if (descriptorRegistry != null){ return descriptorRegistry.getApplicationDescriptors(serviceName, hostname); } GatewayResource gateway = jpa.getGateway(); List<ApplicationDescriptorResource> applicationDescriptorResources = gateway.getApplicationDescriptorResources(serviceName, hostname); if (applicationDescriptorResources.size()>0){ return createApplicationDescriptor(applicationDescriptorResources.get(0)); } return null; } public Map<String, ApplicationDescription> getApplicationDescriptors(String serviceName) throws RegistryException { if (descriptorRegistry != null){ return descriptorRegistry.getApplicationDescriptors(serviceName); } GatewayResource gateway = jpa.getGateway(); Map<String, ApplicationDescription> map=new HashMap<String,ApplicationDescription>(); List<ApplicationDescriptorResource> applicationDescriptorResources = gateway.getApplicationDescriptorResources(serviceName, null); for (ApplicationDescriptorResource resource : applicationDescriptorResources) { map.put(resource.getHostDescName(),createApplicationDescriptor(resource)); } return map; } private Map<String,ApplicationDescription> getApplicationDescriptorsFromHostName(String hostName)throws RegistryException { GatewayResource gateway = jpa.getGateway(); Map<String, ApplicationDescription> map=new HashMap<String,ApplicationDescription>(); List<ApplicationDescriptorResource> applicationDescriptorResources = gateway.getApplicationDescriptorResources(null, hostName); for (ApplicationDescriptorResource resource : applicationDescriptorResources) { map.put(resource.getServiceDescName(),createApplicationDescriptor(resource)); } return map; } public Map<String[],ApplicationDescription> getApplicationDescriptors()throws MalformedDescriptorException, RegistryException{ if (descriptorRegistry != null){ return descriptorRegistry.getApplicationDescriptors(); } GatewayResource gateway = jpa.getGateway(); Map<String[], ApplicationDescription> map=new HashMap<String[],ApplicationDescription>(); List<ApplicationDescriptorResource> applicationDescriptorResources = gateway.getApplicationDescriptorResources(); for (ApplicationDescriptorResource resource : applicationDescriptorResources) { map.put(new String[]{resource.getServiceDescName(),resource.getHostDescName()},createApplicationDescriptor(resource)); } return map; } public void removeApplicationDescriptor(String serviceName, String hostName, String applicationName) throws RegistryException { if (descriptorRegistry != null){ descriptorRegistry.removeApplicationDescriptor(serviceName, hostName, applicationName); } else { GatewayResource gateway = jpa.getGateway(); String appName = createAppName(serviceName, hostName, applicationName); if (!isApplicationDescriptorExists(serviceName,hostName,applicationName)){ throw new DescriptorDoesNotExistsException(appName); } gateway.removeApplicationDescriptor(appName); } } public ResourceMetadata getApplicationDescriptorMetadata(String serviceName, String hostName, String applicationName) throws RegistryException { if (descriptorRegistry != null) { return descriptorRegistry.getApplicationDescriptorMetadata(serviceName, hostName, applicationName); } //TODO throw new UnimplementedRegistryOperationException(); } /**---------------------------------Project Registry----------------------------------**/ private String createProjName(String projectName){ return createProjName(getGateway().getGatewayName(),getUser().getUserName(),projectName); } private String createProjName(String gatewayName, String userName, String projectName){ return gatewayName+"\n"+userName+"\n"+projectName; } private String getProjName(String projectLongName){ String[] s = projectLongName.split("\n"); return s[s.length-1]; } @Override public boolean isWorkspaceProjectExists(String projectName) throws RegistryException { if (projectsRegistry != null){ return projectsRegistry.isWorkspaceProjectExists(projectName); } return isWorkspaceProjectExists(projectName, false); } @Override public boolean isWorkspaceProjectExists(String projectName, boolean createIfNotExists) throws RegistryException { if (projectsRegistry != null){ return projectsRegistry.isWorkspaceProjectExists(projectName, createIfNotExists); } if (jpa.getWorker().isProjectExists(createProjName(projectName))){ return true; }else if (createIfNotExists){ addWorkspaceProject(new WorkspaceProject(projectName, this)); return isWorkspaceProjectExists(projectName); }else{ return false; } } public void addWorkspaceProject(WorkspaceProject project) throws RegistryException { if (projectsRegistry != null){ projectsRegistry.addWorkspaceProject(project); } else { WorkerResource worker = jpa.getWorker(); if (isWorkspaceProjectExists(project.getProjectName())){ throw new WorkspaceProjectAlreadyExistsException(createProjName(project.getProjectName())); } ProjectResource projectResource = worker.createProject(createProjName(project.getProjectName())); projectResource.save(); } } public void updateWorkspaceProject(WorkspaceProject project) throws RegistryException { if (projectsRegistry != null){ projectsRegistry.updateWorkspaceProject(project); }else { WorkerResource worker = jpa.getWorker(); if (!isWorkspaceProjectExists(project.getProjectName())){ throw new WorkspaceProjectDoesNotExistsException(createProjName(project.getProjectName())); } ProjectResource projectResource = worker.getProject(createProjName(project.getProjectName())); projectResource.save(); } } public void deleteWorkspaceProject(String projectName) throws RegistryException { if (projectsRegistry != null){ projectsRegistry.deleteWorkspaceProject(projectName); }else { WorkerResource worker = jpa.getWorker(); if (!isWorkspaceProjectExists(projectName)){ throw new WorkspaceProjectDoesNotExistsException(createProjName(projectName)); } worker.removeProject(createProjName(projectName)); } } public WorkspaceProject getWorkspaceProject(String projectName) throws RegistryException { if (projectsRegistry != null){ return projectsRegistry.getWorkspaceProject(projectName); } WorkerResource worker = jpa.getWorker(); if (!isWorkspaceProjectExists(projectName)){ throw new WorkspaceProjectDoesNotExistsException(createProjName(projectName)); } ProjectResource projectResource = worker.getProject(createProjName(projectName)); return new WorkspaceProject(getProjName(projectResource.getName()), this); } public List<WorkspaceProject> getWorkspaceProjects() throws RegistryException{ if (projectsRegistry != null){ return projectsRegistry.getWorkspaceProjects(); } WorkerResource worker = jpa.getWorker(); List<WorkspaceProject> projects=new ArrayList<WorkspaceProject>(); List<ProjectResource> projectResouces = worker.getProjects(); for (ProjectResource resource : projectResouces) { projects.add(new WorkspaceProject(getProjName(resource.getName()), this)); } return projects; } public void addExperiment(String projectName, AiravataExperiment experiment) throws RegistryException { if (projectsRegistry != null){ projectsRegistry.addExperiment(projectName, experiment); }else { WorkspaceProject workspaceProject = getWorkspaceProject(projectName); ProjectResource project = jpa.getWorker().getProject(createProjName(workspaceProject.getProjectName())); String experimentId = experiment.getExperimentId(); if (isExperimentExists(experimentId)){ throw new ExperimentDoesNotExistsException(experimentId); } ExperimentResource experimentResource = project.createExperiment(experimentId); if (experiment.getSubmittedDate()!=null) { experimentResource.setSubmittedDate(new Timestamp(experiment.getSubmittedDate().getTime())); } experimentResource.save(); } } public void removeExperiment(String experimentId) throws ExperimentDoesNotExistsException { if (projectsRegistry != null){ projectsRegistry.removeExperiment(experimentId); }else { WorkerResource worker = jpa.getWorker(); if (!worker.isExperimentExists(experimentId)){ throw new ExperimentDoesNotExistsException(experimentId); } worker.removeExperiment(experimentId); } } public List<AiravataExperiment> getExperiments() throws RegistryException{ if (projectsRegistry != null){ return projectsRegistry.getExperiments(); } WorkerResource worker = jpa.getWorker(); List<AiravataExperiment> result=new ArrayList<AiravataExperiment>(); List<ExperimentResource> experiments = worker.getExperiments(); for (ExperimentResource resource : experiments) { AiravataExperiment e = createAiravataExperimentObj(resource); result.add(e); } return result; } private AiravataExperiment createAiravataExperimentObj( ExperimentResource resource) { AiravataExperiment e = new AiravataExperiment(); e.setExperimentId(resource.getExpID()); e.setUser(new AiravataUser(resource.getWorker().getUser())); e.setSubmittedDate(new Date(resource.getSubmittedDate().getTime())); e.setGateway(new Gateway(resource.getGateway().getGatewayName())); e.setProject(new WorkspaceProject(getProjName(resource.getProject().getName()), this)); return e; } public List<AiravataExperiment> getExperiments(String projectName)throws RegistryException { if (projectsRegistry != null){ return projectsRegistry.getExperiments(projectName); } ProjectResource project = jpa.getWorker().getProject(createProjName(projectName)); List<ExperimentResource> experiments = project.getExperiments(); List<AiravataExperiment> result=new ArrayList<AiravataExperiment>(); for (ExperimentResource resource : experiments) { AiravataExperiment e = createAiravataExperimentObj(resource); result.add(e); } return result; } public List<AiravataExperiment> getExperiments(Date from, Date to)throws RegistryException { if (projectsRegistry != null){ return projectsRegistry.getExperiments(from, to); } List<AiravataExperiment> experiments = getExperiments(); List<AiravataExperiment> newExperiments = new ArrayList<AiravataExperiment>(); for(AiravataExperiment exp:experiments){ Date submittedDate = exp.getSubmittedDate(); if(submittedDate.after(from) && submittedDate.before(to)) { newExperiments.add(exp); } } return newExperiments; } public List<AiravataExperiment> getExperiments(String projectName, Date from, Date to)throws RegistryException { if (projectsRegistry != null){ return projectsRegistry.getExperiments(projectName, from, to); } List<AiravataExperiment> experiments = getExperiments(projectName); List<AiravataExperiment> newExperiments = new ArrayList<AiravataExperiment>(); for (AiravataExperiment exp : experiments) { Date submittedDate = exp.getSubmittedDate(); if (submittedDate.after(from) && submittedDate.before(to)) { newExperiments.add(exp); } } return newExperiments; } /**---------------------------------Published Workflow Registry----------------------------------**/ @Override public boolean isPublishedWorkflowExists(String workflowName) throws RegistryException { if (publishedWorkflowRegistry != null){ return publishedWorkflowRegistry.isPublishedWorkflowExists(workflowName); } return jpa.getGateway().isPublishedWorkflowExists(workflowName); } public void publishWorkflow(String workflowName, String publishWorkflowName) throws RegistryException { if (publishedWorkflowRegistry != null){ publishedWorkflowRegistry.publishWorkflow(workflowName, publishWorkflowName); } else { GatewayResource gateway = jpa.getGateway(); String workflowGraphXML = getWorkflowGraphXML(workflowName); if (gateway.isPublishedWorkflowExists(publishWorkflowName)){ throw new PublishedWorkflowAlreadyExistsException(publishWorkflowName); } PublishWorkflowResource publishedWorkflow = gateway.createPublishedWorkflow(publishWorkflowName); publishedWorkflow.setCreatedUser(getUser().getUserName()); publishedWorkflow.setContent(workflowGraphXML); publishedWorkflow.setPublishedDate(new Timestamp(Calendar.getInstance().getTime().getTime())); publishedWorkflow.save(); } } public void publishWorkflow(String workflowName) throws RegistryException { if (publishedWorkflowRegistry != null){ publishedWorkflowRegistry.publishWorkflow(workflowName); } else { publishWorkflow(workflowName, workflowName); } } public String getPublishedWorkflowGraphXML(String workflowName) throws RegistryException { if (publishedWorkflowRegistry != null){ return publishedWorkflowRegistry.getPublishedWorkflowGraphXML(workflowName); } GatewayResource gateway = jpa.getGateway(); if (!isPublishedWorkflowExists(workflowName)){ throw new PublishedWorkflowDoesNotExistsException(workflowName); } return gateway.getPublishedWorkflow(workflowName).getContent(); } public List<String> getPublishedWorkflowNames() throws RegistryException{ if (publishedWorkflowRegistry != null){ return publishedWorkflowRegistry.getPublishedWorkflowNames(); } GatewayResource gateway = jpa.getGateway(); List<String> result=new ArrayList<String>(); List<PublishWorkflowResource> publishedWorkflows = gateway.getPublishedWorkflows(); for (PublishWorkflowResource resource : publishedWorkflows) { result.add(resource.getName()); } return result; } public Map<String,String> getPublishedWorkflows() throws RegistryException{ if (publishedWorkflowRegistry != null){ return publishedWorkflowRegistry.getPublishedWorkflows(); } GatewayResource gateway = jpa.getGateway(); Map<String,String> result=new HashMap<String, String>(); List<PublishWorkflowResource> publishedWorkflows = gateway.getPublishedWorkflows(); for (PublishWorkflowResource resource : publishedWorkflows) { result.put(resource.getName(), resource.getContent()); } return result; } public void removePublishedWorkflow(String workflowName) throws RegistryException { if (publishedWorkflowRegistry != null){ publishedWorkflowRegistry.removePublishedWorkflow(workflowName); } else { GatewayResource gateway = jpa.getGateway(); if (!isPublishedWorkflowExists(workflowName)){ throw new PublishedWorkflowDoesNotExistsException(workflowName); } gateway.removePublishedWorkflow(workflowName); } } public ResourceMetadata getPublishedWorkflowMetadata(String workflowName) throws RegistryException { if (publishedWorkflowRegistry != null){ return publishedWorkflowRegistry.getPublishedWorkflowMetadata(workflowName); } //TODO throw new UnimplementedRegistryOperationException(); } /**---------------------------------User Workflow Registry----------------------------------**/ @Override public boolean isWorkflowExists(String workflowName) throws RegistryException { if (userWorkflowRegistry != null){ return userWorkflowRegistry.isWorkflowExists(workflowName); } return jpa.getWorker().isWorkflowTemplateExists(workflowName); } public void addWorkflow(String workflowName, String workflowGraphXml) throws RegistryException { if (userWorkflowRegistry != null){ userWorkflowRegistry.addWorkflow(workflowName, workflowGraphXml); }else { WorkerResource worker = jpa.getWorker(); if (isWorkflowExists(workflowName)){ throw new UserWorkflowAlreadyExistsException(workflowName); } UserWorkflowResource workflowResource = worker.createWorkflowTemplate(workflowName); workflowResource.setContent(workflowGraphXml); workflowResource.save(); } } public void updateWorkflow(String workflowName, String workflowGraphXml) throws RegistryException { if (userWorkflowRegistry != null){ userWorkflowRegistry.updateWorkflow(workflowName, workflowGraphXml); }else { WorkerResource worker = jpa.getWorker(); if (!isWorkflowExists(workflowName)){ throw new UserWorkflowDoesNotExistsException(workflowName); } UserWorkflowResource workflowResource = worker.getWorkflowTemplate(workflowName); workflowResource.setContent(workflowGraphXml); workflowResource.save(); } } public String getWorkflowGraphXML(String workflowName) throws RegistryException { if (userWorkflowRegistry != null){ return userWorkflowRegistry.getWorkflowGraphXML(workflowName); } WorkerResource worker = jpa.getWorker(); if (!isWorkflowExists(workflowName)){ throw new UserWorkflowDoesNotExistsException(workflowName); } return worker.getWorkflowTemplate(workflowName).getContent(); } @Override public Map<String, String> getWorkflows() throws RegistryException { if (userWorkflowRegistry != null){ return userWorkflowRegistry.getWorkflows(); } WorkerResource worker = jpa.getWorker(); Map<String, String> workflows=new HashMap<String, String>(); List<UserWorkflowResource> workflowTemplates = worker.getWorkflowTemplates(); for (UserWorkflowResource resource : workflowTemplates) { workflows.put(resource.getName(), resource.getContent()); } return workflows; } public void removeWorkflow(String workflowName) throws RegistryException { if (userWorkflowRegistry != null){ userWorkflowRegistry.removeWorkflow(workflowName); }else { WorkerResource worker = jpa.getWorker(); if (!isWorkflowExists(workflowName)){ throw new UserWorkflowDoesNotExistsException(workflowName); } worker.removeWorkflowTemplate(workflowName); } } public ResourceMetadata getWorkflowMetadata(String workflowName) throws RegistryException { if (userWorkflowRegistry != null){ return userWorkflowRegistry.getWorkflowMetadata(workflowName); } //TODO throw new UnimplementedRegistryOperationException(); } public void setAiravataRegistry(AiravataRegistry2 registry) { //redundant } public void setAiravataUser(AiravataUser user) { setUser(user); } @Override public AiravataUser getAiravataUser() { return getUser(); } /**---------------------------------Provenance Registry----------------------------------**/ @Override public boolean isExperimentExists(String experimentId, boolean createIfNotPresent)throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.isExperimentExists(experimentId, createIfNotPresent); } if (jpa.getWorker().isExperimentExists(experimentId)){ return true; }else if (createIfNotPresent){ if (!isWorkspaceProjectExists(DEFAULT_PROJECT_NAME, true)){ throw new WorkspaceProjectDoesNotExistsException(createProjName(DEFAULT_PROJECT_NAME)); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId(experimentId); experiment.setSubmittedDate(Calendar.getInstance().getTime()); experiment.setGateway(getGateway()); experiment.setUser(getUser()); addExperiment(DEFAULT_PROJECT_NAME, experiment); return jpa.getWorker().isExperimentExists(experimentId); }else{ return false; } } @Override public boolean isExperimentExists(String experimentId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.isExperimentExists(experimentId); } return isExperimentExists(experimentId, false); } @Override public void updateExperimentExecutionUser(String experimentId, String user) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.updateExperimentExecutionUser(experimentId, user); }else { if (!isExperimentExists(experimentId, true)){ throw new ExperimentDoesNotExistsException(experimentId); } ExperimentResource experiment = jpa.getWorker().getExperiment(experimentId); ExperimentDataResource data = experiment.getData(); data.setUserName(user); data.save(); } } @Override public String getExperimentExecutionUser(String experimentId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getExperimentExecutionUser(experimentId); } if (!isExperimentExists(experimentId)){ throw new ExperimentDoesNotExistsException(experimentId); } ExperimentResource experiment = jpa.getWorker().getExperiment(experimentId); return experiment.getData().getUserName(); } @Override public boolean isExperimentNameExist(String experimentName) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.isExperimentNameExist(experimentName); } return (new ExperimentDataRetriever()).isExperimentNameExist(experimentName); } @Override public String getExperimentName(String experimentId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getExperimentName(experimentId); } if (!isExperimentExists(experimentId)){ throw new ExperimentDoesNotExistsException(experimentId); } return (new ExperimentDataRetriever()).getExperimentName(experimentId); } @Override public void updateExperimentName(String experimentId, String experimentName) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.updateExperimentName(experimentId, experimentName); }else { if (!isExperimentExists(experimentId, true)){ throw new ExperimentDoesNotExistsException(experimentId); } ExperimentResource experiment = jpa.getWorker().getExperiment(experimentId); ExperimentDataResource data = experiment.getData(); data.setExpName(experimentName); data.save(); } } @Override public String getExperimentMetadata(String experimentId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getExperimentMetadata(experimentId); } if (!isExperimentExists(experimentId, true)){ throw new ExperimentDoesNotExistsException(experimentId); } ExperimentResource experiment = jpa.getWorker().getExperiment(experimentId); ExperimentDataResource data = experiment.getData(); if (data.isExperimentMetadataPresent()){ return data.getExperimentMetadata().getMetadata(); } return null; } @Override public void updateExperimentMetadata(String experimentId, String metadata) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.updateExperimentMetadata(experimentId, metadata); }else { if (!isExperimentExists(experimentId, true)){ throw new ExperimentDoesNotExistsException(experimentId); } ExperimentResource experiment = jpa.getWorker().getExperiment(experimentId); ExperimentDataResource data = experiment.getData(); ExperimentMetadataResource experimentMetadata; if (data.isExperimentMetadataPresent()){ experimentMetadata = data.getExperimentMetadata(); experimentMetadata.setMetadata(metadata); }else{ experimentMetadata = data.createExperimentMetadata(); experimentMetadata.setMetadata(metadata); } experimentMetadata.save(); } } @Override public String getWorkflowExecutionTemplateName(String workflowInstanceId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowExecutionTemplateName(workflowInstanceId); } if (!isWorkflowInstanceExists(workflowInstanceId, true)){ throw new WorkflowInstanceDoesNotExistsException(workflowInstanceId); } WorkflowDataResource wi = jpa.getWorker().getWorkflowInstance(workflowInstanceId); return wi.getTemplateName(); } @Override public void setWorkflowInstanceTemplateName(String workflowInstanceId, String templateName) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.setWorkflowInstanceTemplateName(workflowInstanceId, templateName); }else { if (!isWorkflowInstanceExists(workflowInstanceId, true)){ throw new WorkflowInstanceDoesNotExistsException(workflowInstanceId); } WorkflowDataResource wi = jpa.getWorker().getWorkflowInstance(workflowInstanceId); wi.setTemplateName(templateName); wi.save(); } } @Override public List<WorkflowExecution> getExperimentWorkflowInstances( String experimentId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getExperimentWorkflowInstances(experimentId); } if (!isExperimentExists(experimentId)){ throw new ExperimentDoesNotExistsException(experimentId); } ExperimentResource experiment = jpa.getWorker().getExperiment(experimentId); ExperimentDataResource data = experiment.getData(); List<WorkflowExecution> result=new ArrayList<WorkflowExecution>(); List<WorkflowDataResource> workflowInstances = data.getWorkflowInstances(); for (WorkflowDataResource resource : workflowInstances) { WorkflowExecution workflowInstance = new WorkflowExecution(resource.getExperimentID(), resource.getWorkflowInstanceID()); workflowInstance.setTemplateName(resource.getTemplateName()); result.add(workflowInstance); } return result; } @Override public boolean isWorkflowInstanceExists(String instanceId, boolean createIfNotPresent) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.isWorkflowInstanceExists(instanceId, createIfNotPresent); } if (jpa.getWorker().isWorkflowInstancePresent(instanceId)){ return true; }else if (createIfNotPresent){ //we are using the same id for the experiment id for backward compatibility //for up to airavata 0.5 if (!isExperimentExists(instanceId, true)){ throw new ExperimentDoesNotExistsException(instanceId); } addWorkflowInstance(instanceId, instanceId, null); return isWorkflowInstanceExists(instanceId); }else{ return false; } } @Override public boolean isWorkflowInstanceExists(String instanceId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.isWorkflowInstanceExists(instanceId); } return isWorkflowInstanceExists(instanceId, false); } @Override public void updateWorkflowInstanceStatus(String instanceId, State status) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.updateWorkflowInstanceStatus(instanceId, status); }else { if (!isWorkflowInstanceExists(instanceId, true)){ throw new WorkflowInstanceDoesNotExistsException(instanceId); } WorkflowDataResource wi = jpa.getWorker().getWorkflowInstance(instanceId); Timestamp currentTime = new Timestamp(Calendar.getInstance().getTime().getTime()); wi.setStatus(status.toString()); if (status==State.STARTED){ wi.setStartTime(currentTime); } wi.setLastUpdatedTime(currentTime); wi.save(); } } @Override public void updateWorkflowInstanceStatus(WorkflowExecutionStatus status) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.updateWorkflowInstanceStatus(status); }else { if (!isWorkflowInstanceExists(status.getWorkflowInstance().getWorkflowExecutionId(), true)){ throw new WorkflowInstanceDoesNotExistsException(status.getWorkflowInstance().getWorkflowExecutionId()); } WorkflowDataResource wi = jpa.getWorker().getWorkflowInstance(status.getWorkflowInstance().getWorkflowExecutionId()); Timestamp currentTime = new Timestamp(status.getStatusUpdateTime().getTime()); if(status.getExecutionStatus() != null){ wi.setStatus(status.getExecutionStatus().toString()); } if (status.getExecutionStatus()==State.STARTED){ wi.setStartTime(currentTime); } wi.setLastUpdatedTime(currentTime); wi.save(); } } @Override public WorkflowExecutionStatus getWorkflowInstanceStatus(String instanceId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowInstanceStatus(instanceId); } if (!isWorkflowInstanceExists(instanceId, true)){ throw new WorkflowInstanceDoesNotExistsException(instanceId); } WorkflowDataResource wi = jpa.getWorker().getWorkflowInstance(instanceId); return new WorkflowExecutionStatus(new WorkflowExecution(wi.getExperimentID(),wi.getWorkflowInstanceID()),wi.getStatus()==null?null:State.valueOf(wi.getStatus()),wi.getLastUpdatedTime()); } @Override public void updateWorkflowNodeInput(WorkflowInstanceNode node, String data) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.updateWorkflowNodeInput(node, data); }else { if (!isWorkflowInstanceNodePresent(node.getWorkflowInstance().getWorkflowExecutionId(),node.getNodeId(),true)){ throw new WorkflowInstanceNodeDoesNotExistsException(node.getWorkflowInstance().getWorkflowExecutionId(), node.getNodeId()); } WorkflowDataResource wi = jpa.getWorker().getWorkflowInstance(node.getWorkflowInstance().getWorkflowExecutionId()); NodeDataResource nodeData = wi.getNodeData(node.getNodeId()); nodeData.setInputs(data); nodeData.save(); } } @Override public void updateWorkflowNodeOutput(WorkflowInstanceNode node, String data) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.updateWorkflowNodeOutput(node, data); }else { try { if (!isWorkflowInstanceNodePresent(node.getWorkflowInstance().getWorkflowExecutionId(),node.getNodeId(),true)){ throw new WorkflowInstanceNodeDoesNotExistsException(node.getWorkflowInstance().getWorkflowExecutionId(), node.getNodeId()); } WorkflowDataResource wi = jpa.getWorker().getWorkflowInstance(node.getWorkflowInstance().getWorkflowExecutionId()); NodeDataResource nodeData = wi.getNodeData(node.getNodeId()); nodeData.setOutputs(data); nodeData.save(); } catch (RegistryException e) { e.printStackTrace(); throw e; } } } @Override public List<WorkflowNodeIOData> searchWorkflowInstanceNodeInput( String experimentIdRegEx, String workflowNameRegEx, String nodeNameRegEx) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.searchWorkflowInstanceNodeInput(experimentIdRegEx, workflowNameRegEx, nodeNameRegEx); } return null; } @Override public List<WorkflowNodeIOData> searchWorkflowInstanceNodeOutput( String experimentIdRegEx, String workflowNameRegEx, String nodeNameRegEx) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.searchWorkflowInstanceNodeOutput(experimentIdRegEx, workflowNameRegEx, nodeNameRegEx); } return null; } @Override public List<WorkflowNodeIOData> getWorkflowInstanceNodeInput( String workflowInstanceId, String nodeType) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowInstanceNodeInput(workflowInstanceId, nodeType); } return null; } @Override public List<WorkflowNodeIOData> getWorkflowInstanceNodeOutput( String workflowInstanceId, String nodeType) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowInstanceNodeOutput(workflowInstanceId, nodeType); } return null; } @Deprecated @Override public void saveWorkflowExecutionOutput(String experimentId, String outputNodeName, String output) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.saveWorkflowExecutionOutput(experimentId, outputNodeName, output); } } @Deprecated @Override public void saveWorkflowExecutionOutput(String experimentId, WorkflowIOData data) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.saveWorkflowExecutionOutput(experimentId, data); } } @Deprecated @Override public WorkflowIOData getWorkflowExecutionOutput(String experimentId, String outputNodeName) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowExecutionOutput(experimentId, outputNodeName); } // TODO Auto-generated method stub return null; } @Deprecated @Override public List<WorkflowIOData> getWorkflowExecutionOutput(String experimentId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowExecutionOutput(experimentId); } // TODO Auto-generated method stub return null; } @Deprecated @Override public String[] getWorkflowExecutionOutputNames(String exeperimentId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowExecutionOutputNames(exeperimentId); } // TODO Auto-generated method stub return null; } @Override public ExperimentData getExperiment(String experimentId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getExperiment(experimentId); } if (!isExperimentExists(experimentId)){ throw new ExperimentDoesNotExistsException(experimentId); } return (new ExperimentDataRetriever()).getExperiment(experimentId); } @Override public List<String> getExperimentIdByUser(String user) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getExperimentIdByUser(user); } if(user == null){ user = jpa.getWorker().getUser(); } return (new ExperimentDataRetriever()).getExperimentIdByUser(user); } @Override public List<ExperimentData> getExperimentByUser(String user) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getExperimentByUser(user); } if(user == null){ user = jpa.getWorker().getUser(); } return (new ExperimentDataRetriever()).getExperiments(user); } @Override public List<ExperimentData> getExperiments(HashMap<String,String> params) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getExperiments(params); } return (new ExperimentDataRetriever()).getExperiments(params); } @Override public List<ExperimentData> getExperimentByUser(String user, int pageSize, int pageNo) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getExperimentByUser(user, pageSize, pageNo); } // TODO Auto-generated method stub return null; } @Override public void updateWorkflowNodeStatus(NodeExecutionStatus workflowStatusNode) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.updateWorkflowNodeStatus(workflowStatusNode); }else { WorkflowExecution workflowInstance = workflowStatusNode.getWorkflowInstanceNode().getWorkflowInstance(); String nodeId = workflowStatusNode.getWorkflowInstanceNode().getNodeId(); if (!isWorkflowInstanceNodePresent(workflowInstance.getWorkflowExecutionId(), nodeId, true)){ throw new WorkflowInstanceNodeDoesNotExistsException(workflowInstance.getWorkflowExecutionId(), nodeId); } NodeDataResource nodeData = jpa.getWorker().getWorkflowInstance(workflowInstance.getWorkflowExecutionId()).getNodeData(nodeId); nodeData.setStatus(workflowStatusNode.getExecutionStatus().toString()); Timestamp t = new Timestamp(workflowStatusNode.getStatusUpdateTime().getTime()); if (workflowStatusNode.getExecutionStatus()==State.STARTED){ nodeData.setStartTime(t); } nodeData.setLastUpdateTime(t); nodeData.save(); //Each time node status is updated the the time of update for the workflow status is going to be the same WorkflowExecutionStatus currentWorkflowInstanceStatus = getWorkflowInstanceStatus(workflowInstance.getWorkflowExecutionId()); updateWorkflowInstanceStatus(new WorkflowExecutionStatus(workflowInstance, currentWorkflowInstanceStatus.getExecutionStatus(), t)); } } @Override public void updateWorkflowNodeStatus(String workflowInstanceId, String nodeId, State status) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.updateWorkflowNodeStatus(workflowInstanceId, nodeId, status); }else { updateWorkflowNodeStatus(new WorkflowInstanceNode(new WorkflowExecution(workflowInstanceId, workflowInstanceId), nodeId), status); } } @Override public void updateWorkflowNodeStatus(WorkflowInstanceNode workflowNode, State status) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.updateWorkflowNodeStatus(workflowNode, status); }else { updateWorkflowNodeStatus(new NodeExecutionStatus(workflowNode, status, Calendar.getInstance().getTime())); } } @Override public NodeExecutionStatus getWorkflowNodeStatus( WorkflowInstanceNode workflowNode) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowNodeStatus(workflowNode); } String id = workflowNode.getWorkflowInstance().getWorkflowExecutionId(); String nodeId = workflowNode.getNodeId(); if (!isWorkflowInstanceNodePresent(id, nodeId)){ throw new WorkflowInstanceNodeDoesNotExistsException(id, nodeId); } WorkflowDataResource workflowInstance = jpa.getWorker().getWorkflowInstance(id); NodeDataResource nodeData = workflowInstance.getNodeData(nodeId); return new NodeExecutionStatus(new WorkflowInstanceNode(new WorkflowExecution(workflowInstance.getExperimentID(), workflowInstance.getWorkflowInstanceID()), nodeData.getNodeID()), nodeData.getStatus()==null?null:State.valueOf(nodeData.getStatus()),nodeData.getLastUpdateTime()); } @Override public Date getWorkflowNodeStartTime(WorkflowInstanceNode workflowNode) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowNodeStartTime(workflowNode); } String id = workflowNode.getWorkflowInstance().getWorkflowExecutionId(); String nodeId = workflowNode.getNodeId(); if (!isWorkflowInstanceNodePresent(id, nodeId)){ throw new WorkflowInstanceNodeDoesNotExistsException(id, nodeId); } WorkflowDataResource workflowInstance = jpa.getWorker().getWorkflowInstance(id); NodeDataResource nodeData = workflowInstance.getNodeData(nodeId); return nodeData.getStartTime(); } @Override public Date getWorkflowStartTime(WorkflowExecution workflowInstance) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowStartTime(workflowInstance); } if (!isWorkflowInstanceExists(workflowInstance.getWorkflowExecutionId(),true)){ throw new WorkflowInstanceDoesNotExistsException(workflowInstance.getWorkflowExecutionId()); } WorkflowDataResource wi = jpa.getWorker().getWorkflowInstance(workflowInstance.getWorkflowExecutionId()); return wi.getStartTime(); } @Override public void updateWorkflowNodeGramData( WorkflowNodeGramData workflowNodeGramData) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.updateWorkflowNodeGramData(workflowNodeGramData); }else { ApplicationJob job = new ApplicationJob(); job.setJobId(workflowNodeGramData.getGramJobID()); job.setHostDescriptionId(workflowNodeGramData.getInvokedHost()); job.setExperimentId(workflowNodeGramData.getWorkflowInstanceId()); job.setWorkflowExecutionId(workflowNodeGramData.getWorkflowInstanceId()); job.setNodeId(workflowNodeGramData.getNodeID()); job.setJobData(workflowNodeGramData.getRsl()); if (isApplicationJobExists(job.getJobId())){ updateApplicationJob(job); }else{ addApplicationJob(job); } } } @Override public WorkflowExecutionData getWorkflowInstanceData( String workflowInstanceId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowInstanceData(workflowInstanceId); } if (!isWorkflowInstanceExists(workflowInstanceId,true)){ throw new WorkflowInstanceDoesNotExistsException(workflowInstanceId); } try{ WorkflowDataResource resource = jpa.getWorker().getWorkflowInstance(workflowInstanceId); WorkflowExecution workflowInstance = new WorkflowExecution(resource.getExperimentID(), resource.getWorkflowInstanceID()); workflowInstance.setTemplateName(resource.getTemplateName()); WorkflowExecutionData workflowInstanceData = new WorkflowExecutionDataImpl(null, workflowInstance, new WorkflowExecutionStatus(workflowInstance, resource.getStatus()==null? null:State.valueOf(resource.getStatus()),resource.getLastUpdatedTime()), null); List<NodeDataResource> nodeData = resource.getNodeData(); for (NodeDataResource nodeDataResource : nodeData) { workflowInstanceData.getNodeDataList().add(getWorkflowInstanceNodeData(workflowInstanceId, nodeDataResource.getNodeID())); } return workflowInstanceData; } catch (ExperimentLazyLoadedException e) { throw new RegistryException(e); } } @Override public NodeExecutionData getWorkflowInstanceNodeData( String workflowInstanceId, String nodeId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowInstanceNodeData(workflowInstanceId, nodeId); } if (!isWorkflowInstanceNodePresent(workflowInstanceId, nodeId)){ throw new WorkflowInstanceNodeDoesNotExistsException(workflowInstanceId,nodeId); } NodeDataResource nodeData = jpa.getWorker().getWorkflowInstance(workflowInstanceId).getNodeData(nodeId); NodeExecutionData data = new NodeExecutionData(new WorkflowInstanceNode(new WorkflowExecution(nodeData.getWorkflowDataResource().getExperimentID(),nodeData.getWorkflowDataResource().getWorkflowInstanceID()),nodeData.getNodeID())); data.setInput(nodeData.getInputs()); data.setOutput(nodeData.getOutputs()); data.setType(WorkflowNodeType.getType(nodeData.getNodeType()).getNodeType()); //TODO setup status return data; } @Override public boolean isWorkflowInstanceNodePresent(String workflowInstanceId, String nodeId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.isWorkflowInstanceNodePresent(workflowInstanceId, nodeId); } return isWorkflowInstanceNodePresent(workflowInstanceId, nodeId, false); } @Override public boolean isWorkflowInstanceNodePresent(String workflowInstanceId, String nodeId, boolean createIfNotPresent) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.isWorkflowInstanceNodePresent(workflowInstanceId, nodeId, createIfNotPresent); } if (!isWorkflowInstanceExists(workflowInstanceId, true)){ throw new WorkflowInstanceDoesNotExistsException(workflowInstanceId); } if (jpa.getWorker().getWorkflowInstance(workflowInstanceId).isNodeExists(nodeId)){ return true; }else if (createIfNotPresent){ addWorkflowInstanceNode(workflowInstanceId, nodeId); return isWorkflowInstanceNodePresent(workflowInstanceId, nodeId); }else{ return false; } } @Override public void addWorkflowInstance(String experimentId, String workflowInstanceId, String templateName) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.addWorkflowInstance(experimentId,workflowInstanceId, templateName); }else { if (!isExperimentExists(experimentId, true)){ throw new ExperimentDoesNotExistsException(experimentId); } if (isWorkflowInstanceExists(workflowInstanceId)){ throw new WorkflowInstanceAlreadyExistsException(workflowInstanceId); } ExperimentResource experiment = jpa.getWorker().getExperiment(experimentId); ExperimentDataResource data = experiment.getData(); WorkflowDataResource workflowInstanceResource = data.createWorkflowInstanceResource(workflowInstanceId); workflowInstanceResource.setTemplateName(templateName); workflowInstanceResource.save(); } } @Override public void updateWorkflowNodeType(WorkflowInstanceNode node, WorkflowNodeType type) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.updateWorkflowNodeType(node, type); }else { try { if (!isWorkflowInstanceNodePresent(node.getWorkflowInstance().getWorkflowExecutionId(),node.getNodeId(), true)){ throw new WorkflowInstanceNodeDoesNotExistsException(node.getWorkflowInstance().getWorkflowExecutionId(),node.getNodeId()); } NodeDataResource nodeData = jpa.getWorker().getWorkflowInstance(node.getWorkflowInstance().getWorkflowExecutionId()).getNodeData(node.getNodeId()); nodeData.setNodeType(type.getNodeType().toString()); nodeData.save(); } catch (RegistryException e) { e.printStackTrace(); throw e; } } } @Override public void addWorkflowInstanceNode(String workflowInstanceId, String nodeId) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.addWorkflowInstanceNode(workflowInstanceId, nodeId); }else { if (isWorkflowInstanceNodePresent(workflowInstanceId, nodeId)){ throw new WorkflowInstanceNodeAlreadyExistsException(workflowInstanceId, nodeId); } NodeDataResource nodeData = jpa.getWorker().getWorkflowInstance(workflowInstanceId).createNodeData(nodeId); nodeData.save(); } } @Override public ExperimentData getExperimentMetaInformation(String experimentId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getExperimentMetaInformation(experimentId); } if (!isExperimentExists(experimentId)){ throw new ExperimentDoesNotExistsException(experimentId); } ExperimentDataRetriever experimentDataRetriever = new ExperimentDataRetriever(); return experimentDataRetriever.getExperimentMetaInformation(experimentId); } @Override public List<ExperimentData> getAllExperimentMetaInformation(String user) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getAllExperimentMetaInformation(user); } ExperimentDataRetriever experimentDataRetriever = new ExperimentDataRetriever(); return experimentDataRetriever.getAllExperimentMetaInformation(user); } @Override public List<ExperimentData> searchExperiments(String user, String experimentNameRegex) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.searchExperiments(user, experimentNameRegex); } Pattern pattern = Pattern.compile(experimentNameRegex); List<ExperimentData> filteredExperiments=new ArrayList<ExperimentData>(); List<ExperimentData> allExperimentMetaInformation = getAllExperimentMetaInformation(user); for (ExperimentData experimentData : allExperimentMetaInformation) { if (experimentData.getExperimentName()!=null && pattern.matcher(experimentData.getExperimentName()).find()){ filteredExperiments.add(experimentData); } } return filteredExperiments; } @Override public Version getVersion() { return API_VERSION; } @Override public void setConnectionURI(URI connectionURI) { registryConnectionURI=connectionURI; } @Override public URI getConnectionURI() { return registryConnectionURI; } @Override public void setCallback(PasswordCallback callback) { this.callback=callback; } @Override public PasswordCallback getCallback() { return callback; } @Override public List<ExperimentExecutionError> getExperimentExecutionErrors( String experimentId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getExperimentExecutionErrors(experimentId); } List<ExperimentExecutionError> result=new ArrayList<ExperimentExecutionError>(); List<ExecutionErrorResource> executionErrors = jpa.getWorker().getExperiment(experimentId).getData().getExecutionErrors(Source.EXPERIMENT.toString(), experimentId, null, null, null); for (ExecutionErrorResource errorResource : executionErrors) { ExperimentExecutionError error = new ExperimentExecutionError(); setupValues(errorResource, error); error.setExperimentId(errorResource.getExperimentDataResource().getExperimentID()); result.add(error); } return result; } @Override public List<WorkflowExecutionError> getWorkflowExecutionErrors( String experimentId, String workflowInstanceId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getWorkflowExecutionErrors(experimentId, workflowInstanceId); } List<WorkflowExecutionError> result=new ArrayList<WorkflowExecutionError>(); List<ExecutionErrorResource> executionErrors = jpa.getWorker().getExperiment(experimentId).getData().getExecutionErrors(Source.WORKFLOW.toString(), experimentId, workflowInstanceId, null, null); for (ExecutionErrorResource errorResource : executionErrors) { WorkflowExecutionError error = new WorkflowExecutionError(); setupValues(errorResource, error); error.setExperimentId(errorResource.getExperimentDataResource().getExperimentID()); error.setWorkflowInstanceId(errorResource.getWorkflowDataResource().getWorkflowInstanceID()); result.add(error); } return result; } @Override public List<NodeExecutionError> getNodeExecutionErrors(String experimentId, String workflowInstanceId, String nodeId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getNodeExecutionErrors(experimentId, workflowInstanceId, nodeId); } List<NodeExecutionError> result=new ArrayList<NodeExecutionError>(); List<ExecutionErrorResource> executionErrors = jpa.getWorker().getExperiment(experimentId).getData().getExecutionErrors(Source.NODE.toString(), experimentId, workflowInstanceId, nodeId, null); for (ExecutionErrorResource errorResource : executionErrors) { NodeExecutionError error = new NodeExecutionError(); setupValues(errorResource, error); error.setExperimentId(errorResource.getExperimentDataResource().getExperimentID()); error.setNodeId(errorResource.getNodeID()); error.setWorkflowInstanceId(errorResource.getWorkflowDataResource().getWorkflowInstanceID()); result.add(error); } return result; } @Override public List<ApplicationJobExecutionError> getApplicationJobErrors(String experimentId, String workflowInstanceId, String nodeId, String gfacJobId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getApplicationJobErrors(experimentId, workflowInstanceId, nodeId, gfacJobId); } List<ApplicationJobExecutionError> result=new ArrayList<ApplicationJobExecutionError>(); List<ExecutionErrorResource> executionErrors = jpa.getWorker().getExperiment(experimentId).getData().getExecutionErrors(Source.APPLICATION.toString(), experimentId, workflowInstanceId, nodeId, gfacJobId); for (ExecutionErrorResource errorResource : executionErrors) { ApplicationJobExecutionError error = new ApplicationJobExecutionError(); setupValues(errorResource, error); error.setExperimentId(errorResource.getExperimentDataResource().getExperimentID()); error.setJobId(errorResource.getGfacJobID()); error.setNodeId(errorResource.getNodeID()); error.setWorkflowInstanceId(errorResource.getWorkflowDataResource().getWorkflowInstanceID()); result.add(error); } return result; } private void setupValues(ExecutionErrorResource source, ExecutionError destination) { destination.setActionTaken(source.getActionTaken()); destination.setErrorCode(source.getErrorCode()); destination.setErrorDescription(source.getErrorDes()); destination.setErrorLocation(source.getErrorLocation()); destination.setErrorMessage(source.getErrorMsg()); destination.setErrorReported(source.getErrorReporter()); destination.setErrorTime(source.getErrorTime()); destination.setSource(Source.valueOf(source.getSourceType())); destination.setErrorReference(source.getErrorReference()); } @Override public List<ApplicationJobExecutionError> getApplicationJobErrors(String gfacJobId) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getApplicationJobErrors(gfacJobId); } return getApplicationJobErrors(null, null, null, gfacJobId); } @Override public List<ExecutionError> getExecutionErrors(String experimentId, String workflowInstanceId, String nodeId, String gfacJobId, Source... filterBy) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.getExecutionErrors(experimentId, workflowInstanceId, nodeId, gfacJobId, filterBy); } List<ExecutionError> errors = new ArrayList<ExecutionError>(); for (Source sourceType : filterBy) { if (sourceType==Source.ALL){ errors.addAll(getExperimentExecutionErrors(experimentId)); errors.addAll(getWorkflowExecutionErrors(experimentId, workflowInstanceId)); errors.addAll(getNodeExecutionErrors(experimentId, workflowInstanceId, nodeId)); errors.addAll(getApplicationJobErrors(experimentId, workflowInstanceId, nodeId, gfacJobId)); break; } else if (sourceType==Source.EXPERIMENT){ errors.addAll(getExperimentExecutionErrors(experimentId)); } else if (sourceType==Source.WORKFLOW){ errors.addAll(getWorkflowExecutionErrors(experimentId, workflowInstanceId)); } else if (sourceType==Source.NODE){ errors.addAll(getNodeExecutionErrors(experimentId, workflowInstanceId, nodeId)); } else if (sourceType==Source.APPLICATION){ errors.addAll(getApplicationJobErrors(experimentId, workflowInstanceId, nodeId, gfacJobId)); } } return errors; } // @Override // public List<ExecutionError> getAllExperimentErrors(String experimentId, // Source... filterBy) throws RegistryException { // return getExecutionErrors(experimentId, null, null, null, filterBy); // } // @Override // public List<ExecutionError> getAllWorkflowErrors(String experimentId, // String workflowInstanceId, Source... filterBy) // throws RegistryException { // return getExecutionErrors(experimentId, workflowInstanceId, null, null, filterBy); // } // @Override // public List<ExecutionError> getAllNodeErrors(String experimentId, // String workflowInstanceId, String nodeId, Source... filterBy) // throws RegistryException { // return getExecutionErrors(experimentId, workflowInstanceId, nodeId, null, filterBy); // } @Override public int addExperimentError(ExperimentExecutionError error) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.addExperimentError(error); } ExecutionErrorResource executionError = createNewExecutionErrorResource(error.getExperimentId(),error,ExecutionErrors.Source.EXPERIMENT); executionError.save(); return executionError.getErrorID(); } private ExecutionErrorResource createNewExecutionErrorResource( String experimentId, ExecutionError errorSource, ExecutionErrors.Source type) throws RegistryException { if (!isExperimentExists(experimentId)){ throw new ExperimentDoesNotExistsException(experimentId); } ExecutionErrorResource executionError = jpa.getWorker().getExperiment(experimentId).getData().createExecutionError(); setupValues(errorSource, executionError); executionError.setSourceType(type.toString()); return executionError; } private void setupValues(ExecutionError source, ExecutionErrorResource destination) { destination.setErrorCode(source.getErrorCode()); destination.setErrorDes(source.getErrorDescription()); destination.setErrorLocation(source.getErrorLocation()); destination.setErrorMsg(source.getErrorMessage()); destination.setErrorReference(source.getErrorReference()); destination.setErrorReporter(source.getErrorReported()); destination.setErrorTime(new Timestamp(source.getErrorTime().getTime())); destination.setActionTaken(source.getActionTaken()); } @Override public int addWorkflowExecutionError(WorkflowExecutionError error) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.addWorkflowExecutionError(error); } ExecutionErrorResource executionError = createNewExecutionErrorResource(error.getExperimentId(),error,ExecutionErrors.Source.WORKFLOW); executionError.setWorkflowDataResource(jpa.getWorker().getExperiment(error.getExperimentId()).getData().getWorkflowInstance(error.getWorkflowInstanceId())); executionError.save(); return executionError.getErrorID(); } @Override public int addNodeExecutionError(NodeExecutionError error) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.addNodeExecutionError(error); } ExecutionErrorResource executionError = createNewExecutionErrorResource(error.getExperimentId(),error, Source.NODE); executionError.setWorkflowDataResource(jpa.getWorker().getExperiment(error.getExperimentId()).getData().getWorkflowInstance(error.getWorkflowInstanceId())); executionError.setNodeID(error.getNodeId()); executionError.save(); return executionError.getErrorID(); } @Override public int addApplicationJobExecutionError(ApplicationJobExecutionError error) throws RegistryException { if (provenanceRegistry != null){ return provenanceRegistry.addApplicationJobExecutionError(error); } ExecutionErrorResource executionError = createNewExecutionErrorResource(error.getExperimentId(),error, Source.APPLICATION); executionError.setWorkflowDataResource(jpa.getWorker().getExperiment(error.getExperimentId()).getData().getWorkflowInstance(error.getWorkflowInstanceId())); executionError.setNodeID(error.getNodeId()); executionError.setGfacJobID(error.getJobId()); executionError.save(); return executionError.getErrorID(); } @Override public void addApplicationJob(ApplicationJob job) throws RegistryException { if (provenanceRegistry != null){ provenanceRegistry.addApplicationJob(job); } if (job.getJobId()==null || job.getJobId().equals("")){ throw new InvalidApplicationJobIDException(); } if (isApplicationJobExists(job.getJobId())){ throw new ApplicationJobAlreadyExistsException(job.getJobId()); } // if (!isWorkflowInstanceNodePresent(job.getWorkflowExecutionId(), job.getNodeId())){ // throw new WorkflowInstanceNodeDoesNotExistsException(job.getWorkflowExecutionId(), job.getNodeId()); // } ExperimentDataResource expData = jpa.getWorker().getExperiment(job.getExperimentId()).getData(); GFacJobDataResource gfacJob = expData.createGFacJob(job.getJobId()); gfacJob.setExperimentDataResource(expData); gfacJob.setWorkflowDataResource(expData.getWorkflowInstance(job.getWorkflowExecutionId())); gfacJob.setNodeID(job.getNodeId()); setupValues(job, gfacJob); gfacJob.save(); addApplicationJobStatusData(job.getJobId(), job.getStatus(), job.getStatusUpdateTime(),gfacJob); } private void setupValues(ApplicationJob job, GFacJobDataResource gfacJob) { gfacJob.setApplicationDescID(job.getApplicationDescriptionId()); gfacJob.setStatusUpdateTime(new Timestamp(job.getStatusUpdateTime().getTime())); gfacJob.setHostDescID(job.getHostDescriptionId()); gfacJob.setJobData(job.getJobData()); gfacJob.setMetadata(job.getMetadata()); gfacJob.setServiceDescID(job.getServiceDescriptionId()); gfacJob.setStatus(job.getStatus().toString()); gfacJob.setSubmittedTime(new Timestamp(job.getSubmittedTime().getTime())); } @Override public void updateApplicationJob(ApplicationJob job) throws RegistryException { GFacJobDataResource gFacJob = validateAndGetGFacJob(job.getJobId()); setupValues(job, gFacJob); gFacJob.save(); } private GFacJobDataResource validateAndGetGFacJob(String jobId) throws InvalidApplicationJobIDException, RegistryException, ApplicationJobDoesNotExistsException { if (jobId==null || jobId.equals("")){ throw new InvalidApplicationJobIDException(); } if (!isApplicationJobExists(jobId)){ throw new ApplicationJobDoesNotExistsException(jobId); } GFacJobDataResource gFacJob = jpa.getWorker().getGFacJob(jobId); return gFacJob; } @Override public void updateApplicationJobStatus(String gfacJobId, ApplicationJobStatus status, Date statusUpdateTime) throws RegistryException { GFacJobDataResource gFacJob = validateAndGetGFacJob(gfacJobId); gFacJob.setStatus(status.toString()); gFacJob.setStatusUpdateTime(new Timestamp(statusUpdateTime.getTime())); gFacJob.save(); addApplicationJobStatusData(gfacJobId, status, statusUpdateTime, null); } @Override public void updateApplicationJobData(String gfacJobId, String jobdata) throws RegistryException { GFacJobDataResource gFacJob = validateAndGetGFacJob(gfacJobId); gFacJob.setJobData(jobdata); gFacJob.save(); } @Override public void updateApplicationJobSubmittedTime(String gfacJobId, Date submitted) throws RegistryException { GFacJobDataResource gFacJob = validateAndGetGFacJob(gfacJobId); gFacJob.setSubmittedTime(new Timestamp(submitted.getTime())); gFacJob.save(); } @Override public void updateApplicationJobStatusUpdateTime(String gfacJobId, Date completed) throws RegistryException { GFacJobDataResource gFacJob = validateAndGetGFacJob(gfacJobId); gFacJob.setStatusUpdateTime(new Timestamp(completed.getTime())); gFacJob.save(); } @Override public void updateApplicationJobMetadata(String gfacJobId, String metadata) throws RegistryException { GFacJobDataResource gFacJob = validateAndGetGFacJob(gfacJobId); gFacJob.setMetadata(metadata); gFacJob.save(); } @Override public ApplicationJob getApplicationJob(String gfacJobId) throws RegistryException { GFacJobDataResource gfacJob = validateAndGetGFacJob(gfacJobId); ApplicationJob job = new ApplicationJob(); setupValues(gfacJob, job); return job; } private void setupValues(GFacJobDataResource gfacJob, ApplicationJob job) { job.setApplicationDescriptionId(gfacJob.getApplicationDescID()); job.setStatusUpdateTime(gfacJob.getStatusUpdateTime()); job.setExperimentId(gfacJob.getExperimentDataResource().getExperimentID()); job.setHostDescriptionId(gfacJob.getHostDescID()); job.setJobData(gfacJob.getJobData()); job.setJobId(gfacJob.getLocalJobID()); job.setStatus(ApplicationJobStatus.valueOf(gfacJob.getStatus())); job.setMetadata(gfacJob.getMetadata()); job.setNodeId(gfacJob.getNodeID()); job.setServiceDescriptionId(gfacJob.getServiceDescID()); job.setSubmittedTime(gfacJob.getSubmittedTime()); job.setWorkflowExecutionId(gfacJob.getWorkflowDataResource().getWorkflowInstanceID()); } @Override public List<ApplicationJob> getApplicationJobsForDescriptors(String serviceDescriptionId, String hostDescriptionId, String applicationDescriptionId) throws RegistryException { List<ApplicationJob> jobs=new ArrayList<ApplicationJob>(); List<GFacJobDataResource> gFacJobs = jpa.getWorker().getGFacJobs(serviceDescriptionId,hostDescriptionId,applicationDescriptionId); for (GFacJobDataResource resource : gFacJobs) { ApplicationJob job = new ApplicationJob(); setupValues(resource, job); jobs.add(job); } return jobs; } @Override public List<ApplicationJob> getApplicationJobs(String experimentId, String workflowExecutionId, String nodeId) throws RegistryException { List<ApplicationJob> jobs=new ArrayList<ApplicationJob>(); List<Resource> gFacJobs; if (workflowExecutionId==null){ if (!isExperimentExists(experimentId)){ throw new ExperimentDoesNotExistsException(experimentId); } gFacJobs = jpa.getWorker().getExperiment(experimentId).getData().getGFacJobs(); }else if (nodeId==null){ if (!isWorkflowInstanceExists(workflowExecutionId)){ throw new WorkflowInstanceDoesNotExistsException(workflowExecutionId); } gFacJobs = jpa.getWorker().getExperiment(experimentId).getData().getWorkflowInstance(workflowExecutionId).getGFacJobs(); }else{ if (!isWorkflowInstanceNodePresent(workflowExecutionId, nodeId)){ throw new WorkflowInstanceNodeDoesNotExistsException(workflowExecutionId, nodeId); } gFacJobs = jpa.getWorker().getExperiment(experimentId).getData().getWorkflowInstance(workflowExecutionId).getNodeData(nodeId).getGFacJobs(); } for (Resource resource : gFacJobs) { ApplicationJob job = new ApplicationJob(); setupValues((GFacJobDataResource)resource, job); jobs.add(job); } return jobs; } @Override public boolean isApplicationJobExists(String gfacJobId) throws RegistryException { return jpa.getWorker().isGFacJobExists(gfacJobId); } @Override public List<ApplicationJobStatusData> getApplicationJobStatusHistory( String jobId) throws RegistryException { List<ApplicationJobStatusData> statusData=new ArrayList<ApplicationJobStatusData>(); List<GFacJobStatusResource> statuses = jpa.getWorker().getGFacJobStatuses(jobId); for (GFacJobStatusResource resource : statuses) { statusData.add(new ApplicationJobStatusData(resource.getLocalJobID(),ApplicationJobStatus.valueOf(resource.getStatus()),resource.getStatusUpdateTime())); } return statusData; } @Override public List<AiravataUser> getUsers() throws RegistryException { if (userRegistry != null){ return userRegistry.getUsers(); } List<AiravataUser> result=new ArrayList<AiravataUser>(); List<Resource> users = jpa.getGateway().get(ResourceType.USER); for (Resource resource : users) { UserResource userRes = (UserResource) resource; AiravataUser user = new AiravataUser(userRes.getUserName()); result.add(user); } return result; } private void addApplicationJobStatusData(String jobId, ApplicationJobStatus status, Date updatedTime, GFacJobDataResource dataResource) throws RegistryException { if (RegistrySettings.isApplicationJobStatusHistoryEnabled()){ if (dataResource==null){ dataResource = jpa.getWorker().getGFacJob(jobId); } GFacJobStatusResource s = (GFacJobStatusResource)dataResource.create(ResourceType.GFAC_JOB_STATUS); s.setStatus(status.toString()); s.setStatusUpdateTime(new Timestamp(updatedTime.getTime())); s.save(); } } @Override public boolean isCredentialExist(String gatewayId, String tokenId) throws RegistryException { credentialReader = new CredentialReaderImpl(getDBConnector()); try { SSHCredential credential = (SSHCredential) credentialReader.getCredential(gatewayId, tokenId); if (credential!=null) { return true; } } catch(CredentialStoreException e) { return false; } return false; } @Override public String getCredentialPublicKey(String gatewayId, String tokenId) throws RegistryException { credentialReader = new CredentialReaderImpl(getDBConnector()); try { SSHCredential credential = (SSHCredential) credentialReader.getCredential(gatewayId, tokenId); if (credential!=null) { return new String(credential.getPublicKey()); } } catch(CredentialStoreException e) { return null; } return null; } @Override public String createCredential(String gatewayId, String tokenId) throws RegistryException { return createCredential(gatewayId, tokenId, null); } @Override public String createCredential(String gatewayId, String tokenId, String username) throws RegistryException { credentialWriter = new SSHCredentialWriter(getDBConnector()); credentialGenerator = new SSHCredentialGenerator(); try { SSHCredential credential = credentialGenerator.generateCredential(tokenId); if (credential!=null) { credential.setGateway(gatewayId); credential.setToken(tokenId); credential.setPortalUserName(username); credentialWriter.writeCredentials(credential); return new String(credential.getPublicKey()); } } catch (CredentialStoreException e) { return null; } return null; } private static DBUtil getDBConnector() throws RegistryException{ try { String url = RegistrySettings.getSetting("registry.jdbc.url"); String driver = RegistrySettings.getSetting("registry.jdbc.driver"); String username = RegistrySettings.getSetting("registry.jdbc.user"); String password = RegistrySettings.getSetting("registry.jdbc.password"); DBUtil dbConnector = new DBUtil(url,username,password,driver); return dbConnector; } catch (InstantiationException e) { logger.error("Error while accesing registrty settings ", e); throw new RegistryException("Error while accesing registrty settings ", e); } catch (IllegalAccessException e) { logger.error("Error while reading registrty settings ", e); throw new RegistryException("Error while accesing registrty settings ", e); } catch (ClassNotFoundException e) { logger.error("Error while reading registrty settings ", e); throw new RegistryException("Error while accesing registrty settings ", e); } catch (RegistrySettingsException e) { logger.error("Error while reading registrty settings ", e); throw new RegistryException("Error while accesing registrty settings ", e); } } public Map<String, Integer> getGFACNodeList() throws RegistryException { return null; //To change body of implemented methods use File | Settings | File Templates. } /** *These are the methods inherited from Orchestrator Registry */ public List<URI> getLiveGFacURIs() throws RegistryException { return null; //To change body of implemented methods use File | Settings | File Templates. } public boolean storeExperiment(String userName, String experimentID) throws RegistryException { return false; //To change body of implemented methods use File | Settings | File Templates. } public boolean changeStatus(String userName, String experimentID, AiravataJobState.State state) throws RegistryException { return false; //To change body of implemented methods use File | Settings | File Templates. } public AiravataJobState getState(String experimentID) throws RegistryException { return null; //To change body of implemented methods use File | Settings | File Templates. } public List<String> getAllJobsWithState(AiravataJobState state) throws RuntimeException { return null; //To change body of implemented methods use File | Settings | File Templates. } public List<String> getAllAcceptedJobs() throws RegistryException { return null; //To change body of implemented methods use File | Settings | File Templates. } public String fetchAJob() throws RegistryException { return null; //To change body of implemented methods use File | Settings | File Templates. } public List<String> getAllHangedJobs() throws RegistryException { return null; //To change body of implemented methods use File | Settings | File Templates. } public int getHangedJobCount() throws RegistryException { return 0; //To change body of implemented methods use File | Settings | File Templates. } public boolean resetHangedJob(String experimentID) throws RegistryException { return false; //To change body of implemented methods use File | Settings | File Templates. } }
9,419
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/HostDescriptorResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.*; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.sql.rowset.serial.SerialBlob; import java.sql.Blob; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class HostDescriptorResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(HostDescriptorResource.class); private String hostDescName; private String gatewayName; private String userName; private String content; /** * */ public HostDescriptorResource() { } /** * * @return user name */ public String getUserName() { return userName; } /** * * @param userName user name */ public void setUserName(String userName) { this.userName = userName; } /** * * @return host descriptor name */ public String getHostDescName() { return hostDescName; } /** * * @return gateway name */ public String getGatewayName() { return gatewayName; } /** * * @return content of the host descriptor */ public String getContent() { return content; } /** * * @param gatewayName gateway name */ public void setGatewayName(String gatewayName) { this.gatewayName = gatewayName; } /** * * @param content content of the host descriptor */ public void setContent(String content) { this.content = content; } /** * Host descriptor can create an application descriptor * @param type child resource type * @return child resource */ public Resource create(ResourceType type) { if (type == ResourceType.APPLICATION_DESCRIPTOR) { ApplicationDescriptorResource applicationDescriptorResource = new ApplicationDescriptorResource(); applicationDescriptorResource.setGatewayName(gatewayName); applicationDescriptorResource.setHostDescName(getHostDescName()); return applicationDescriptorResource; }else{ logger.error("Unsupported resource type for host descriptor resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for host descriptor resource."); } } /** * Host descriptor by alone cannot remove any other resource types * @param type child resource type * @param name child resource name */ public void remove(ResourceType type, Object name) { logger.error("Unsupported resource type for host descriptor resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * Host descriptor by alone cannot get any other resource types * @param type child resource type * @param name child resource name * @return UnsupportedOperationException */ public Resource get(ResourceType type, Object name) { logger.error("Unsupported resource type for host descriptor resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * key should be host_descriptor_name * @param keys host descriptor names * @return list of host descriptors */ public List<Resource> populate(Object[] keys) { List<Resource> list = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator = new QueryGenerator(HOST_DESCRIPTOR); generator.setParameter(HostDescriptorConstants.GATEWAY_NAME, keys [0]); generator.setParameter(HostDescriptorConstants.HOST_DESC_ID, keys[1]); Query q = generator.selectQuery(em); Host_Descriptor hostDescriptor = (Host_Descriptor)q.getSingleResult(); HostDescriptorResource hostDescriptorResource = (HostDescriptorResource)Utils.getResource(ResourceType.HOST_DESCRIPTOR, hostDescriptor); em.getTransaction().commit(); em.close(); list.add(hostDescriptorResource); return list; } /** * Host descriptors can get a list of application descriptors * @param type child resource type * @return list of child resources */ public List<Resource> get(ResourceType type) { List<Resource> resourceList = new ArrayList<Resource>(); if (type == ResourceType.APPLICATION_DESCRIPTOR) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator = new QueryGenerator(APPLICATION_DESCRIPTOR); generator.setParameter(ApplicationDescriptorConstants.GATEWAY_NAME, gatewayName); generator.setParameter(ApplicationDescriptorConstants.HOST_DESC_ID, getHostDescName()); Query q = generator.selectQuery(em); List results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Application_Descriptor applicationDescriptor = (Application_Descriptor) result; ApplicationDescriptorResource applicationDescriptorResource = (ApplicationDescriptorResource)Utils.getResource( ResourceType.APPLICATION_DESCRIPTOR, applicationDescriptor); resourceList.add(applicationDescriptorResource); } } em.getTransaction().commit(); em.close(); } return resourceList; } /** * save host descriptor to the database */ public void save() { try { EntityManager em = ResourceUtils.getEntityManager(); Host_Descriptor existingHost_desc = em.find(Host_Descriptor.class, new Host_Descriptor_PK(gatewayName, hostDescName)); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Host_Descriptor hostDescriptor = new Host_Descriptor(); Gateway existingGateway = em.find(Gateway.class, gatewayName); Users existingUser = em.find(Users.class, userName); // Gateway gateway = new Gateway(); // gateway.setGateway_name(gatewayName); // Users user = new Users(); // user.setUser_name(userName); hostDescriptor.setHost_descriptor_ID(getHostDescName()); hostDescriptor.setGateway(existingGateway); byte[] contentBytes = content.getBytes(); hostDescriptor.setHost_descriptor_xml(contentBytes); hostDescriptor.setUser(existingUser); if (existingHost_desc != null) { existingHost_desc.setUser(existingUser); existingHost_desc.setHost_descriptor_xml(contentBytes); hostDescriptor = em.merge(existingHost_desc); } else { em.merge(hostDescriptor); } em.getTransaction().commit(); em.close(); } catch (Exception e) { e.printStackTrace(); } } /** * * @param type child resource type * @param name child resource name * @return boolean whether the child resource already exists */ public boolean isExists(ResourceType type, Object name) { logger.error("Unsupported resource type for host descriptor resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * * @param hostDescName host descriptor name */ public void setHostDescName(String hostDescName) { this.hostDescName = hostDescName; } }
9,420
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/AbstractResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import java.util.ArrayList; import java.util.List; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; public abstract class AbstractResource implements Resource { //table names public static final String GATEWAY = "Gateway"; public static final String CONFIGURATION = "Configuration"; public static final String USERS = "Users"; public static final String GATEWAY_WORKER = "Gateway_Worker"; public static final String PROJECT = "Project"; public static final String PUBLISHED_WORKFLOW = "Published_Workflow"; public static final String USER_WORKFLOW = "User_Workflow"; public static final String HOST_DESCRIPTOR = "Host_Descriptor"; public static final String SERVICE_DESCRIPTOR = "Service_Descriptor"; public static final String APPLICATION_DESCRIPTOR = "Application_Descriptor"; public static final String EXPERIMENT = "Experiment"; public static final String EXPERIMENT_DATA = "Experiment_Data"; public static final String WORKFLOW_DATA = "Workflow_Data"; public static final String EXPERIMENT_METADATA = "Experiment_Metadata"; public static final String EXECUTION_ERROR = "Execution_Error"; public static final String GFAC_JOB_DATA = "GFac_Job_Data"; public static final String GFAC_JOB_STATUS = "GFac_Job_Status"; //Gateway Table public final class GatewayConstants { public static final String GATEWAY_NAME = "gateway_name"; public static final String GATEWAY_OWNER = "owner"; } //Configuration Table public final class ConfigurationConstants { // public static final String CONFIG_ID = "config_ID"; public static final String CONFIG_KEY = "config_key"; public static final String CONFIG_VAL = "config_val"; public static final String EXPIRE_DATE = "expire_date"; public static final String CATEGORY_ID = "category_id"; public static final String CATEGORY_ID_DEFAULT_VALUE = "SYSTEM"; } //Users table public final class UserConstants { public static final String USERNAME = "user_name"; public static final String PASSWORD = "password"; } //Gateway_Worker table public final class GatewayWorkerConstants { public static final String USERNAME = "user_name"; public static final String GATEWAY_NAME = "gateway_name"; } //Project table public final class ProjectConstants { public static final String GATEWAY_NAME = "gateway_name"; public static final String USERNAME = "user_name"; public static final String PROJECT_NAME = "project_name"; } //Published_Workflow table public final class PublishedWorkflowConstants { public static final String GATEWAY_NAME = "gateway_name"; public static final String CREATED_USER = "created_user"; public static final String PUBLISH_WORKFLOW_NAME = "publish_workflow_name"; public static final String VERSION = "version"; public static final String PUBLISHED_DATE = "published_date"; public static final String PATH = "path"; public static final String WORKFLOW_CONTENT = "workflow_content"; } //User_Workflow table public final class UserWorkflowConstants { public static final String GATEWAY_NAME = "gateway_name"; public static final String OWNER = "owner"; public static final String TEMPLATE_NAME = "template_name"; public static final String LAST_UPDATED_DATE = "last_updated_date"; public static final String PATH = "path"; public static final String WORKFLOW_GRAPH = "workflow_graph"; } //Host_Descriptor table public final class HostDescriptorConstants { public static final String GATEWAY_NAME = "gateway_name"; public static final String UPDATED_USER = "updated_user"; public static final String HOST_DESC_ID = "host_descriptor_ID"; public static final String HOST_DESC_XML = "host_descriptor_xml"; } //Service_Descriptor table public final class ServiceDescriptorConstants { public static final String GATEWAY_NAME = "gateway_name"; public static final String UPDATED_USER = "updated_user"; public static final String SERVICE_DESC_ID = "service_descriptor_ID"; public static final String SERVICE_DESC_XML = "service_descriptor_xml"; } //Application_Descriptor table public final class ApplicationDescriptorConstants { public static final String GATEWAY_NAME = "gateway_name"; public static final String UPDATED_USER = "updated_user"; public static final String APPLICATION_DESC_ID = "application_descriptor_ID"; public static final String HOST_DESC_ID = "host_descriptor_ID"; public static final String SERVICE_DESC_ID = "service_descriptor_ID"; public static final String APPLICATION_DESC_XML = "application_descriptor_xml"; } //Experiment table public final class ExperimentConstants { public static final String PROJECT_NAME = "project_name"; public static final String USERNAME = "user_name"; public static final String GATEWAY_NAME = "gateway_name"; public static final String EXPERIMENT_ID = "experiment_ID"; public static final String SUBMITTED_DATE = "submitted_date"; } //Experiment_Data table public final class ExperimentDataConstants{ public static final String EXPERIMENT_ID="experiment_ID"; public static final String NAME = "name"; public static final String USERNAME = "username"; public static final String METADATA = "metadata"; } //Workflow_Data table public final class WorkflowDataConstants{ public static final String EXPERIMENT_ID="experiment_ID"; public static final String WORKFLOW_INSTANCE_ID = "workflow_instanceID"; public static final String TEMPLATE_NAME = "template_name"; public static final String STATUS = "status"; public static final String START_TIME = "start_time"; public static final String LAST_UPDATE_TIME = "last_update_time"; } //Node_Data table public final class NodeDataConstants{ public static final String WORKFLOW_INSTANCE_ID = "workflow_instanceID"; public static final String NODE_ID = "node_id"; public static final String NODE_TYPE = "node_type"; public static final String INPUTS = "inputs"; public static final String OUTPUTS = "outputs"; public static final String STATUS = "status"; public static final String START_TIME = "start_time"; public static final String LAST_UPDATE_TIME = "last_update_time"; } //Gram_Data table public final class GramDataConstants{ public static final String WORKFLOW_INSTANCE_ID = "workflow_instanceID"; public static final String NODE_ID = "node_id"; public static final String RSL = "rsl"; public static final String INVOKED_HOST = "invoked_host"; public static final String LOCAL_JOB_ID = "local_Job_ID"; } public final class ExecutionErrorConstants { public static final String ERROR_ID = "error_id"; public static final String EXPERIMENT_ID = "experiment_ID"; public static final String WORKFLOW_ID = "workflow_instanceID"; public static final String NODE_ID = "node_id"; public static final String GFAC_JOB_ID = "gfacJobID"; public static final String SOURCE_TYPE = "source_type"; public static final String ERROR_DATE = "error_date"; public static final String ERROR_MSG = "error_msg"; public static final String ERROR_DES = "error_des"; public static final String ERROR_CODE = "error_code"; } public final class GFacJobDataConstants { public static final String EXPERIMENT_ID = "experiment_ID"; public static final String WORKFLOW_INSTANCE_ID = "workflow_instanceID"; public static final String NODE_ID = "node_id"; public static final String APP_DESC_ID = "application_descriptor_ID"; public static final String HOST_DESC_ID = "host_descriptor_ID"; public static final String SERVICE_DESC_ID = "service_descriptor_ID"; public static final String JOB_DATA = "job_data"; public static final String LOCAL_JOB_ID = "local_Job_ID"; public static final String SUBMITTED_TIME = "submitted_time"; public static final String STATUS_UPDATE_TIME = "status_update_time"; public static final String STATUS = "status"; public static final String METADATA = "metadata"; } public final class GFacJobStatusConstants { public static final String LOCAL_JOB_ID = "local_Job_ID"; public static final String STATUS = "status"; public static final String STATUS_UPDATE_TIME = "status_update_time"; } protected AbstractResource() { } public boolean isExists(ResourceType type, Object name) { try { return get(type, name) != null; } catch (Exception e) { return false; } } @SuppressWarnings("unchecked") public static <T> List<T> getResourceList(List<Resource> resources, Class<?> T){ List<T> list=new ArrayList<T>(); for (Resource o : resources) { list.add((T) o); } return list; } }
9,421
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/GFacJobDataResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.Experiment_Data; import org.apache.airavata.persistance.registry.jpa.model.GFac_Job_Data; import org.apache.airavata.persistance.registry.jpa.model.GFac_Job_Status; import org.apache.airavata.persistance.registry.jpa.model.Workflow_Data; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.Query; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; public class GFacJobDataResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(GFacJobDataResource.class); private ExperimentDataResource experimentDataResource; private WorkflowDataResource workflowDataResource; private String nodeID; private String applicationDescID; private String hostDescID; private String serviceDescID; private String jobData; private String localJobID; private Timestamp submittedTime; private Timestamp statusUpdateTime; private String status; private String metadata; public ExperimentDataResource getExperimentDataResource() { return experimentDataResource; } public WorkflowDataResource getWorkflowDataResource() { return workflowDataResource; } public String getNodeID() { return nodeID; } public String getApplicationDescID() { return applicationDescID; } public String getHostDescID() { return hostDescID; } public String getServiceDescID() { return serviceDescID; } public String getJobData() { return jobData; } public String getLocalJobID() { return localJobID; } public Timestamp getSubmittedTime() { return submittedTime; } public Timestamp getStatusUpdateTime() { return statusUpdateTime; } public String getStatus() { return status; } public String getMetadata() { return metadata; } public void setExperimentDataResource(ExperimentDataResource experimentDataResource) { this.experimentDataResource = experimentDataResource; } public void setWorkflowDataResource(WorkflowDataResource workflowDataResource) { this.workflowDataResource = workflowDataResource; } public void setNodeID(String nodeID) { this.nodeID = nodeID; } public void setApplicationDescID(String applicationDescID) { this.applicationDescID = applicationDescID; } public void setHostDescID(String hostDescID) { this.hostDescID = hostDescID; } public void setServiceDescID(String serviceDescID) { this.serviceDescID = serviceDescID; } public void setJobData(String jobData) { this.jobData = jobData; } public void setLocalJobID(String localJobID) { this.localJobID = localJobID; } public void setSubmittedTime(Timestamp submittedTime) { this.submittedTime = submittedTime; } public void setStatusUpdateTime(Timestamp statusUpdateTime) { this.statusUpdateTime = statusUpdateTime; } public void setStatus(String status) { this.status = status; } public void setMetadata(String metadata) { this.metadata = metadata; } @Override public Resource create(ResourceType type) { switch (type){ case GFAC_JOB_STATUS: GFacJobStatusResource gFacJobStatusResource = new GFacJobStatusResource(); gFacJobStatusResource.setLocalJobID(localJobID); gFacJobStatusResource.setgFacJobDataResource(this); return gFacJobStatusResource; default: logger.error("Unsupported resource type for GFac Job status resource" ,new UnsupportedOperationException() ); throw new UnsupportedOperationException(); } } @Override public void remove(ResourceType type, Object name) { logger.error("Unsupported resource type for GFac Job data resource" ,new UnsupportedOperationException() ); throw new UnsupportedOperationException(); } @Override public Resource get(ResourceType type, Object name) { logger.error("Unsupported resource type for GFac Job data resource" ,new UnsupportedOperationException() ); throw new UnsupportedOperationException(); } @Override public List<Resource> get(ResourceType type) { List<Resource> resourceList = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Query q; QueryGenerator generator; List results; switch (type){ case GFAC_JOB_STATUS: generator = new QueryGenerator(GFAC_JOB_STATUS); generator.setParameter(GFacJobStatusConstants.LOCAL_JOB_ID, localJobID); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { GFac_Job_Status gFacJobStatus = (GFac_Job_Status) result; GFacJobStatusResource gFacJobStatusResource = (GFacJobStatusResource)Utils.getResource(ResourceType.GFAC_JOB_STATUS, gFacJobStatus); resourceList.add(gFacJobStatusResource); } } break; default: em.getTransaction().commit(); em.close(); logger.error("Unsupported resource type for gfac job data resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for gfac job data resource."); } em.getTransaction().commit(); em.close(); return resourceList; } @Override public void save() { EntityManager em = ResourceUtils.getEntityManager(); GFac_Job_Data existingGfacJobData = em.find(GFac_Job_Data.class, localJobID); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); GFac_Job_Data gFacJobData = new GFac_Job_Data(); Experiment_Data experiment_data = em.find(Experiment_Data.class, experimentDataResource.getExperimentID()); gFacJobData.setExperiment_data(experiment_data); gFacJobData.setExperiment_ID(experimentDataResource.getExperimentID()); Workflow_Data workflow_data = em.find(Workflow_Data.class, workflowDataResource.getWorkflowInstanceID()); gFacJobData.setWorkflow_Data(workflow_data); gFacJobData.setWorkflow_instanceID(workflowDataResource.getWorkflowInstanceID()); gFacJobData.setNode_id(nodeID); gFacJobData.setApplication_descriptor_ID(applicationDescID); gFacJobData.setLocal_Job_ID(localJobID); gFacJobData.setService_descriptor_ID(serviceDescID); gFacJobData.setHost_descriptor_ID(hostDescID); gFacJobData.setJob_data(jobData); gFacJobData.setSubmitted_time(submittedTime); gFacJobData.setStatus_update_time(statusUpdateTime); gFacJobData.setStatus(status); gFacJobData.setMetadata(metadata); if(existingGfacJobData != null){ Experiment_Data experiment_data1 = em.find(Experiment_Data.class, experimentDataResource.getExperimentID()); existingGfacJobData.setExperiment_data(experiment_data1); existingGfacJobData.setExperiment_ID(experimentDataResource.getExperimentID()); Workflow_Data workflow_data1 = em.find(Workflow_Data.class, workflowDataResource.getWorkflowInstanceID()); existingGfacJobData.setWorkflow_Data(workflow_data1); existingGfacJobData.setWorkflow_instanceID(workflowDataResource.getWorkflowInstanceID()); existingGfacJobData.setNode_id(nodeID); existingGfacJobData.setApplication_descriptor_ID(applicationDescID); existingGfacJobData.setLocal_Job_ID(localJobID); existingGfacJobData.setService_descriptor_ID(serviceDescID); existingGfacJobData.setHost_descriptor_ID(hostDescID); existingGfacJobData.setJob_data(jobData); existingGfacJobData.setSubmitted_time(submittedTime); existingGfacJobData.setStatus_update_time(statusUpdateTime); existingGfacJobData.setStatus(status); existingGfacJobData.setMetadata(metadata); gFacJobData = em.merge(existingGfacJobData); } else { em.persist(gFacJobData); } em.getTransaction().commit(); em.close(); } }
9,422
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/PublishWorkflowResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.Gateway; import org.apache.airavata.persistance.registry.jpa.model.Published_Workflow; import org.apache.airavata.persistance.registry.jpa.model.Published_Workflow_PK; import org.apache.airavata.persistance.registry.jpa.model.Users; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.Query; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; public class PublishWorkflowResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(PublishWorkflowResource.class); private String name; private String version; private Timestamp publishedDate; private String content; private GatewayResource gateway; private String createdUser; private String path; /** * */ public PublishWorkflowResource() { } /** * * @param gateway gateway resource */ public PublishWorkflowResource(GatewayResource gateway) { this.gateway = gateway; } /** * * @return created user */ public String getCreatedUser() { return createdUser; } /** * * @return path of the workflow */ public String getPath() { return path; } /** * * @param createdUser created user */ public void setCreatedUser(String createdUser) { this.createdUser = createdUser; } /** * * @param path path of the workflow */ public void setPath(String path) { this.path = path; } /** * * @return name of the publish workflow */ public String getName() { return name; } /** * * @return version */ public String getVersion() { return version; } /** * * @return published date */ public Timestamp getPublishedDate() { return publishedDate; } /** * * @return content of the workflow */ public String getContent() { return content; } /** * * @param version version of the workflow */ public void setVersion(String version) { this.version = version; } /** * * @param publishedDate published date of the workflow */ public void setPublishedDate(Timestamp publishedDate) { this.publishedDate = publishedDate; } /** * * @param content content of the workflow */ public void setContent(String content) { this.content = content; } /** * Since published workflows are at the leaf level of the * data structure, this method is not valid * @param type type of the child resource * @return UnsupportedOperationException */ public Resource create(ResourceType type) { logger.error("Unsupported resource type for published workflow resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * Since published workflows are at the leaf level of the * data structure, this method is not valid * @param type type of the child resource * @param name name of the child resource */ public void remove(ResourceType type, Object name) { logger.error("Unsupported resource type for published workflow resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * Since published workflows are at the leaf level of the * data structure, this method is not valid * @param type type of the child resource * @param name name of the child resource * @return UnsupportedOperationException */ public Resource get(ResourceType type, Object name) { logger.error("Unsupported resource type for published workflow resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * * @param keys object list including gateway name and published workflow name * @return published workflow resource */ public List<Resource> populate(Object[] keys) { List<Resource> list = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator = new QueryGenerator(PUBLISHED_WORKFLOW); generator.setParameter(PublishedWorkflowConstants.GATEWAY_NAME, keys[0]); generator.setParameter(PublishedWorkflowConstants.PUBLISH_WORKFLOW_NAME, keys[1]); Query q = generator.selectQuery(em); Published_Workflow publishedWorkflow = (Published_Workflow)q.getSingleResult(); PublishWorkflowResource publishWorkflowResource = (PublishWorkflowResource) Utils.getResource(ResourceType.PUBLISHED_WORKFLOW, publishedWorkflow); em.getTransaction().commit(); em.close(); list.add(publishWorkflowResource); return list; } /** * since published workflows are at the leaf level of the * data structure, this method is not valid * @param type type of the child resource * @return UnsupportedOperationException */ public List<Resource> get(ResourceType type) { logger.error("Unsupported resource type for published workflow resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * save published workflow to the database */ public void save() { EntityManager em = ResourceUtils.getEntityManager(); Published_Workflow existingWF = em.find(Published_Workflow.class, new Published_Workflow_PK(gateway.getGatewayName(), name)); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Published_Workflow publishedWorkflow = new Published_Workflow(); publishedWorkflow.setPublish_workflow_name(getName()); publishedWorkflow.setPublished_date(publishedDate); publishedWorkflow.setVersion(version); byte[] bytes = content.getBytes(); publishedWorkflow.setWorkflow_content(bytes); Gateway gateway = new Gateway(); gateway.setGateway_name(this.gateway.getGatewayName()); publishedWorkflow.setGateway(gateway); Users user = new Users(); user.setUser_name(createdUser); publishedWorkflow.setUser(user); if(existingWF != null){ existingWF.setUser(user); existingWF.setPublished_date(publishedDate); existingWF.setWorkflow_content(bytes); existingWF.setVersion(version); existingWF.setPath(path); publishedWorkflow = em.merge(existingWF); }else { em.merge(publishedWorkflow); } em.getTransaction().commit(); em.close(); } /** * Since published workflows are at the leaf level of the * data structure, this method is not valid * @param type type of the child resource * @param name name of the child resource * @return UnsupportedOperationException */ public boolean isExists(ResourceType type, Object name) { logger.error("Unsupported resource type for published workflow resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * * @return gateway resource */ public GatewayResource getGateway() { return gateway; } /** * * @param gateway gateway resource */ public void setGateway(GatewayResource gateway) { this.gateway = gateway; } /** * * @param name published workflow name */ public void setName(String name) { this.name = name; } }
9,423
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/ExperimentDataResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.*; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.Query; import java.util.ArrayList; import java.util.List; public class ExperimentDataResource extends AbstractResource{ private final static Logger logger = LoggerFactory.getLogger(ExperimentDataResource.class); private String experimentID; private String expName; private String userName; public String getExperimentID() { return experimentID; } public String getExpName() { return expName; } public String getUserName() { return userName; } public void setExperimentID(String experimentID) { this.experimentID = experimentID; } public void setExpName(String expName) { this.expName = expName; } public void setUserName(String userName) { this.userName = userName; } public Resource create(ResourceType type) { switch (type){ case WORKFLOW_DATA: WorkflowDataResource workflowDataResource = new WorkflowDataResource(); workflowDataResource.setExperimentID(experimentID); return workflowDataResource; case EXECUTION_ERROR: ExecutionErrorResource executionErrorResource = new ExecutionErrorResource(); executionErrorResource.setExperimentDataResource(this); return executionErrorResource; case EXPERIMENT_METADATA: ExperimentMetadataResource experimentMetadataResource = new ExperimentMetadataResource(); experimentMetadataResource.setExpID(experimentID); return experimentMetadataResource; case GFAC_JOB_DATA: GFacJobDataResource gFacJobDataResource = new GFacJobDataResource(); gFacJobDataResource.setExperimentDataResource(this); return gFacJobDataResource; default: logger.error("Unsupported resource type for experiment data resource... ", new UnsupportedOperationException()); throw new IllegalArgumentException("Unsupported resource type for experiment data resource."); } } public void remove(ResourceType type, Object name) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Query q; QueryGenerator generator; switch (type){ case WORKFLOW_DATA: generator = new QueryGenerator(WORKFLOW_DATA); // generator.setParameter(WorkflowDataConstants.EXPERIMENT_ID, experimentID); generator.setParameter(WorkflowDataConstants.WORKFLOW_INSTANCE_ID, name); q = generator.deleteQuery(em); q.executeUpdate(); break; case EXPERIMENT_METADATA: generator = new QueryGenerator(EXPERIMENT_METADATA); generator.setParameter(ExperimentDataConstants.EXPERIMENT_ID, name); q = generator.deleteQuery(em); q.executeUpdate(); break; case GFAC_JOB_DATA: generator = new QueryGenerator(GFAC_JOB_DATA); generator.setParameter(GFacJobDataConstants.LOCAL_JOB_ID, name); q = generator.deleteQuery(em); q.executeUpdate(); break; default: break; } em.getTransaction().commit(); em.close(); } public Resource get(ResourceType type, Object name) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator; Query q; switch (type) { case WORKFLOW_DATA: generator = new QueryGenerator(WORKFLOW_DATA); // generator.setParameter(WorkflowDataConstants.EXPERIMENT_ID, experimentID); generator.setParameter(WorkflowDataConstants.WORKFLOW_INSTANCE_ID, name); q = generator.selectQuery(em); Workflow_Data eworkflowData = (Workflow_Data)q.getSingleResult(); WorkflowDataResource workflowDataResource = (WorkflowDataResource)Utils.getResource(ResourceType.WORKFLOW_DATA, eworkflowData); em.getTransaction().commit(); em.close(); return workflowDataResource; case EXPERIMENT_METADATA: generator = new QueryGenerator(EXPERIMENT_METADATA); generator.setParameter(ExperimentDataConstants.EXPERIMENT_ID, name); q = generator.selectQuery(em); Experiment_Metadata expMetadata = (Experiment_Metadata)q.getSingleResult(); ExperimentMetadataResource experimentMetadataResource = (ExperimentMetadataResource)Utils.getResource(ResourceType.EXPERIMENT_METADATA, expMetadata); em.getTransaction().commit(); em.close(); return experimentMetadataResource; case GFAC_JOB_DATA: generator = new QueryGenerator(GFAC_JOB_DATA); generator.setParameter(GFacJobDataConstants.LOCAL_JOB_ID, name); q = generator.selectQuery(em); GFac_Job_Data gFacJobData = (GFac_Job_Data)q.getSingleResult(); GFacJobDataResource gFacJobDataResource = (GFacJobDataResource)Utils.getResource(ResourceType.GFAC_JOB_DATA, gFacJobData); em.getTransaction().commit(); em.close(); return gFacJobDataResource; default: em.getTransaction().commit(); em.close(); logger.error("Unsupported resource type for experiment data resource... ", new UnsupportedOperationException()); throw new IllegalArgumentException("Unsupported resource type for experiment data resource."); } } public List<Resource> get(ResourceType type) { List<Resource> resourceList = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Query q; QueryGenerator generator; List<?> results; switch (type){ case WORKFLOW_DATA: generator = new QueryGenerator(WORKFLOW_DATA); // generator.setParameter(WorkflowDataConstants.EXPERIMENT_ID, experimentID); Experiment_Data experiment_data = em.find(Experiment_Data.class, experimentID); generator.setParameter("experiment_data", experiment_data); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Workflow_Data workflowData = (Workflow_Data) result; WorkflowDataResource workflowDataResource = (WorkflowDataResource)Utils.getResource(ResourceType.WORKFLOW_DATA, workflowData); resourceList.add(workflowDataResource); } } break; case EXPERIMENT_METADATA: generator = new QueryGenerator(EXPERIMENT_METADATA); generator.setParameter(ExperimentDataConstants.EXPERIMENT_ID, experimentID); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Experiment_Metadata expMetadata = (Experiment_Metadata) result; ExperimentMetadataResource experimentMetadataResource = (ExperimentMetadataResource)Utils.getResource(ResourceType.EXPERIMENT_METADATA, expMetadata); resourceList.add(experimentMetadataResource); } } break; case EXECUTION_ERROR: generator = new QueryGenerator(EXECUTION_ERROR); generator.setParameter(ExecutionErrorConstants.EXPERIMENT_ID, experimentID); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Execution_Error executionError = (Execution_Error)result; ExecutionErrorResource executionErrorResource = (ExecutionErrorResource)Utils.getResource(ResourceType.EXECUTION_ERROR, executionError); resourceList.add(executionErrorResource); } } break; case GFAC_JOB_DATA: generator = new QueryGenerator(GFAC_JOB_DATA); generator.setParameter(GFacJobDataConstants.EXPERIMENT_ID, experimentID); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { GFac_Job_Data gFacJobData = (GFac_Job_Data)result; GFacJobDataResource gFacJobDataResource = (GFacJobDataResource)Utils.getResource(ResourceType.GFAC_JOB_DATA, gFacJobData); resourceList.add(gFacJobDataResource); } } break; default: em.getTransaction().commit(); em.close(); logger.error("Unsupported resource type for experiment data resource... ", new UnsupportedOperationException()); throw new IllegalArgumentException("Unsupported resource type for experiment data resource."); } em.getTransaction().commit(); em.close(); return resourceList; } public void save() { EntityManager em = ResourceUtils.getEntityManager(); Experiment_Data existingExpData = em.find(Experiment_Data.class, experimentID); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Experiment_Data experimentData = new Experiment_Data(); experimentData.setExperiment_ID(experimentID); experimentData.setName(expName); experimentData.setUsername(userName); if(existingExpData != null){ existingExpData.setName(expName); existingExpData.setUsername(userName); experimentData = em.merge(existingExpData); } else{ em.persist(experimentData); } em.getTransaction().commit(); em.close(); } public boolean isWorkflowInstancePresent(String workflowInstanceId){ return isExists(ResourceType.WORKFLOW_DATA, workflowInstanceId); } public boolean isGFacJobPresent(String jobId){ return isExists(ResourceType.GFAC_JOB_DATA, jobId); } public boolean isExperimentMetadataPresent(){ return isExists(ResourceType.EXPERIMENT_METADATA, getExperimentID()); } public WorkflowDataResource getWorkflowInstance(String workflowInstanceId){ return (WorkflowDataResource)get(ResourceType.WORKFLOW_DATA, workflowInstanceId); } public List<Resource> getGFacJobs(){ return get(ResourceType.GFAC_JOB_DATA); } public ExperimentMetadataResource getExperimentMetadata(){ return (ExperimentMetadataResource)get(ResourceType.EXPERIMENT_METADATA,getExperimentID()); } public List<WorkflowDataResource> getWorkflowInstances(){ return getResourceList(get(ResourceType.WORKFLOW_DATA),WorkflowDataResource.class); } public WorkflowDataResource createWorkflowInstanceResource(String workflowInstanceID){ WorkflowDataResource r=(WorkflowDataResource)create(ResourceType.WORKFLOW_DATA); r.setWorkflowInstanceID(workflowInstanceID); return r; } public GFacJobDataResource createGFacJob(String jobID){ GFacJobDataResource r=(GFacJobDataResource)create(ResourceType.GFAC_JOB_DATA); r.setLocalJobID(jobID); return r; } public ExperimentMetadataResource createExperimentMetadata(){ return (ExperimentMetadataResource)create(ResourceType.EXPERIMENT_METADATA); } public ExecutionErrorResource createExecutionError(){ return (ExecutionErrorResource) create(ResourceType.EXECUTION_ERROR); } public void removeWorkflowInstance(String workflowInstanceId){ remove(ResourceType.WORKFLOW_DATA, workflowInstanceId); } public void removeExperimentMetadata(){ remove(ResourceType.EXPERIMENT_METADATA,getExperimentID()); } public List<ExecutionErrorResource> getExecutionErrors(String type, String experimentId, String workflowInstanceId, String nodeId, String gfacJobId){ List<ExecutionErrorResource> resourceList = new ArrayList<ExecutionErrorResource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Query q; QueryGenerator generator; List<?> results; generator = new QueryGenerator(EXECUTION_ERROR); if (experimentId!=null){ generator.setParameter(ExecutionErrorConstants.EXPERIMENT_ID, experimentId); } if (type!=null){ generator.setParameter(ExecutionErrorConstants.SOURCE_TYPE, type); } if (workflowInstanceId!=null){ generator.setParameter(ExecutionErrorConstants.WORKFLOW_ID, workflowInstanceId); } if (nodeId!=null){ generator.setParameter(ExecutionErrorConstants.NODE_ID, nodeId); } if (gfacJobId!=null){ generator.setParameter(ExecutionErrorConstants.GFAC_JOB_ID, gfacJobId); } q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Execution_Error executionError = (Execution_Error)result; ExecutionErrorResource executionErrorResource = (ExecutionErrorResource)Utils.getResource(ResourceType.EXECUTION_ERROR, executionError); resourceList.add(executionErrorResource); } } em.getTransaction().commit(); em.close(); return resourceList; } }
9,424
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/WorkerResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.*; import org.apache.airavata.persistance.registry.jpa.resources.AbstractResource.GFacJobStatusConstants; import org.apache.airavata.persistance.registry.jpa.resources.AbstractResource.WorkflowDataConstants; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class WorkerResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(WorkerResource.class); private String user; private GatewayResource gateway; /** * */ public WorkerResource() { } /** * * @param user username * @param gateway gatewayResource */ public WorkerResource(String user, GatewayResource gateway) { this.setUser(user); this.gateway=gateway; } /** * Gateway worker can create child data structures such as projects and user workflows * @param type child resource type * @return child resource */ public Resource create(ResourceType type) { Resource result = null; switch (type) { case PROJECT: ProjectResource projectResource = new ProjectResource(); projectResource.setWorker(this); projectResource.setGateway(gateway); result=projectResource; break; case USER_WORKFLOW: UserWorkflowResource userWorkflowResource = new UserWorkflowResource(); userWorkflowResource.setWorker(this); userWorkflowResource.setGateway(gateway); result=userWorkflowResource; break; case EXPERIMENT: ExperimentResource experimentResource = new ExperimentResource(); experimentResource.setWorker(this); experimentResource.setGateway(gateway); result=experimentResource; break; default: logger.error("Unsupported resource type for worker resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for worker resource."); } return result; } /** * * @param type child resource type * @param name child resource name */ public void remove(ResourceType type, Object name) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Query q; QueryGenerator generator; switch (type) { case PROJECT: generator = new QueryGenerator(PROJECT); generator.setParameter(ProjectConstants.PROJECT_NAME, name); q = generator.deleteQuery(em); q.executeUpdate(); break; case USER_WORKFLOW: generator = new QueryGenerator(USER_WORKFLOW); generator.setParameter(UserWorkflowConstants.OWNER, getUser()); generator.setParameter(UserWorkflowConstants.TEMPLATE_NAME, name); generator.setParameter(UserWorkflowConstants.GATEWAY_NAME, gateway.getGatewayName()); q = generator.deleteQuery(em); q.executeUpdate(); break; case EXPERIMENT: generator = new QueryGenerator(EXPERIMENT); generator.setParameter(ExperimentConstants.USERNAME, getUser()); generator.setParameter(ExperimentConstants.EXPERIMENT_ID, name); q = generator.deleteQuery(em); q.executeUpdate(); break; case WORKFLOW_DATA: generator = new QueryGenerator(WORKFLOW_DATA); generator.setParameter(WorkflowDataConstants.WORKFLOW_INSTANCE_ID, name); q = generator.deleteQuery(em); q.executeUpdate(); break; default: logger.error("Unsupported resource type for worker resource.", new IllegalArgumentException()); break; } em.getTransaction().commit(); em.close(); } /** * * @param type child resource type * @param name child resource name * @return child resource */ public Resource get(ResourceType type, Object name) { Resource result = null; EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator; Query q; switch (type) { case PROJECT: generator = new QueryGenerator(PROJECT); generator.setParameter(ProjectConstants.PROJECT_NAME, name); q = generator.selectQuery(em); Project project = (Project) q.getSingleResult(); result= Utils.getResource(ResourceType.PROJECT, project); break; case USER_WORKFLOW: generator = new QueryGenerator(USER_WORKFLOW); generator.setParameter(UserWorkflowConstants.OWNER, getUser()); generator.setParameter(UserWorkflowConstants.TEMPLATE_NAME, name); generator.setParameter(UserWorkflowConstants.GATEWAY_NAME, gateway.getGatewayName()); q = generator.selectQuery(em); User_Workflow userWorkflow = (User_Workflow) q.getSingleResult(); result= Utils.getResource(ResourceType.USER_WORKFLOW, userWorkflow); break; case EXPERIMENT: generator = new QueryGenerator(EXPERIMENT); generator.setParameter(ExperimentConstants.USERNAME, getUser()); generator.setParameter(ExperimentConstants.EXPERIMENT_ID, name); q = generator.selectQuery(em); Experiment experiment = (Experiment) q.getSingleResult(); result= Utils.getResource(ResourceType.EXPERIMENT, experiment); break; case WORKFLOW_DATA: generator = new QueryGenerator(WORKFLOW_DATA); generator.setParameter(WorkflowDataConstants.WORKFLOW_INSTANCE_ID, name); q = generator.selectQuery(em); Workflow_Data eworkflowData = (Workflow_Data)q.getSingleResult(); WorkflowDataResource workflowDataResource = (WorkflowDataResource)Utils.getResource(ResourceType.WORKFLOW_DATA, eworkflowData); result= workflowDataResource; break; case GFAC_JOB_DATA: generator = new QueryGenerator(GFAC_JOB_DATA); generator.setParameter(GFacJobDataConstants.LOCAL_JOB_ID, name); q = generator.selectQuery(em); GFac_Job_Data gFacJobData = (GFac_Job_Data)q.getSingleResult(); GFacJobDataResource gFacJobDataResource = (GFacJobDataResource)Utils.getResource(ResourceType.GFAC_JOB_DATA, gFacJobData); result= gFacJobDataResource; break; default: logger.error("Unsupported resource type for worker resource.", new IllegalArgumentException()); break; } em.getTransaction().commit(); em.close(); return result; } public List<GFacJobDataResource> getGFacJobs(String serviceDescriptionId, String hostDescriptionId, String applicationDescriptionId){ List<GFacJobDataResource> result = new ArrayList<GFacJobDataResource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator; Query q; generator = new QueryGenerator(GFAC_JOB_DATA); generator.setParameter(GFacJobDataConstants.SERVICE_DESC_ID, serviceDescriptionId); generator.setParameter(GFacJobDataConstants.HOST_DESC_ID, hostDescriptionId); generator.setParameter(GFacJobDataConstants.APP_DESC_ID, applicationDescriptionId); q = generator.selectQuery(em); for (Object o : q.getResultList()) { GFac_Job_Data gFacJobData = (GFac_Job_Data)o; result.add((GFacJobDataResource)Utils.getResource(ResourceType.GFAC_JOB_DATA, gFacJobData)); } em.getTransaction().commit(); em.close(); return result; } public List<GFacJobStatusResource> getGFacJobStatuses(String jobId){ List<GFacJobStatusResource> resourceList = new ArrayList<GFacJobStatusResource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator; Query q; generator = new QueryGenerator(GFAC_JOB_STATUS); generator.setParameter(GFacJobStatusConstants.LOCAL_JOB_ID, jobId); q = generator.selectQuery(em); for (Object result : q.getResultList()) { GFac_Job_Status gFacJobStatus = (GFac_Job_Status) result; GFacJobStatusResource gFacJobStatusResource = (GFacJobStatusResource)Utils.getResource(ResourceType.GFAC_JOB_STATUS, gFacJobStatus); resourceList.add(gFacJobStatusResource); } return resourceList; } /** * * @param type child resource type * @return list of child resources */ public List<Resource> get(ResourceType type) { List<Resource> result = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator; Query q; switch (type) { case PROJECT: generator = new QueryGenerator(PROJECT); Users users = em.find(Users.class, getUser()); Gateway gatewayModel = em.find(Gateway.class, gateway.getGatewayName()); generator.setParameter("users", users); generator.setParameter("gateway", gatewayModel); // generator.setParameter(ProjectConstants.USERNAME, getUser()); // generator.setParameter(ProjectConstants.GATEWAY_NAME, gateway.getGatewayName()); q = generator.selectQuery(em); for (Object o : q.getResultList()) { Project project = (Project) o; ProjectResource projectResource = (ProjectResource)Utils.getResource(ResourceType.PROJECT, project); result.add(projectResource); } break; case USER_WORKFLOW: generator = new QueryGenerator(USER_WORKFLOW); generator.setParameter(UserWorkflowConstants.OWNER, getUser()); q = generator.selectQuery(em); // q.setParameter("usr_name", getUser()); for (Object o : q.getResultList()) { User_Workflow userWorkflow = (User_Workflow) o; UserWorkflowResource userWorkflowResource = (UserWorkflowResource)Utils.getResource(ResourceType.USER_WORKFLOW, userWorkflow); result.add(userWorkflowResource); } break; case EXPERIMENT: generator = new QueryGenerator(EXPERIMENT); generator.setParameter(ExperimentConstants.USERNAME, getUser()); generator.setParameter(ExperimentConstants.GATEWAY_NAME, gateway.getGatewayName()); q = generator.selectQuery(em); for (Object o : q.getResultList()) { Experiment experiment = (Experiment) o; ExperimentResource experimentResource = (ExperimentResource)Utils.getResource(ResourceType.EXPERIMENT, experiment); result.add(experimentResource); } break; default: logger.error("Unsupported resource type for worker resource.", new IllegalArgumentException()); break; } em.getTransaction().commit(); em.close(); return result; } /** * save gateway worker to database */ public void save() { EntityManager em = ResourceUtils.getEntityManager(); Gateway_Worker existingWorker = em.find(Gateway_Worker.class, new Gateway_Worker_PK(gateway.getGatewayName(), user)); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Gateway_Worker gatewayWorker = new Gateway_Worker(); Users users = new Users(); users.setUser_name(user); gatewayWorker.setUser(users); Gateway gatewaymodel = new Gateway(); gatewaymodel.setGateway_name(gateway.getGatewayName()); gatewaymodel.setOwner(gateway.getOwner()); gatewayWorker.setGateway(gatewaymodel); if(existingWorker != null){ gatewayWorker = em.merge(existingWorker); }else { em.merge(gatewayWorker); } em.getTransaction().commit(); em.close(); } /** * * @return user name */ public String getUser() { return user; } /** * * @param user user name */ public void setUser(String user) { this.user = user; } /** * * @return gateway resource */ public GatewayResource getGateway() { return gateway; } /** * * @param gateway gateway resource */ public void setGateway(GatewayResource gateway) { this.gateway = gateway; } /** * * @param name project name * @return whether the project is available under the user */ public boolean isProjectExists(String name){ return isExists(ResourceType.PROJECT, name); } /** * * @param name project name * @return project resource for the user */ public ProjectResource createProject(String name){ ProjectResource project=(ProjectResource)create(ResourceType.PROJECT); project.setName(name); return project; } /** * * @param name project name * @return project resource */ public ProjectResource getProject(String name){ return (ProjectResource)get(ResourceType.PROJECT, name); } /** * * @param name project name */ public void removeProject(String name){ remove(ResourceType.PROJECT, name); } /** * * @return list of projects for the user */ public List<ProjectResource> getProjects(){ List<ProjectResource> result=new ArrayList<ProjectResource>(); List<Resource> list = get(ResourceType.PROJECT); for (Resource resource : list) { result.add((ProjectResource) resource); } return result; } /** * * @param templateName user workflow template * @return whether the workflow is already exists under the given user */ public boolean isWorkflowTemplateExists(String templateName){ return isExists(ResourceType.USER_WORKFLOW, templateName); } /** * * @param templateName user workflow template * @return user workflow resource */ public UserWorkflowResource createWorkflowTemplate(String templateName){ UserWorkflowResource workflow=(UserWorkflowResource)create(ResourceType.USER_WORKFLOW); workflow.setName(templateName); return workflow; } /** * * @param templateName user workflow template * @return user workflow resource */ public UserWorkflowResource getWorkflowTemplate(String templateName){ return (UserWorkflowResource)get(ResourceType.USER_WORKFLOW, templateName); } /** * * @param templateName user workflow template */ public void removeWorkflowTemplate(String templateName){ remove(ResourceType.USER_WORKFLOW, templateName); } /** * * @return list of user workflows for the given user */ public List<UserWorkflowResource> getWorkflowTemplates(){ List<UserWorkflowResource> result=new ArrayList<UserWorkflowResource>(); List<Resource> list = get(ResourceType.USER_WORKFLOW); for (Resource resource : list) { result.add((UserWorkflowResource) resource); } return result; } /** * * @param name experiment name * @return whether experiment is already exist for the given user */ public boolean isExperimentExists(String name){ return isExists(ResourceType.EXPERIMENT, name); } /** * Returns of the gfac job record is present for the job id * @param jobId * @return */ public boolean isGFacJobExists(String jobId){ return isExists(ResourceType.GFAC_JOB_DATA, jobId); } /** * * @param name experiment name * @return experiment resource */ public ExperimentResource getExperiment(String name){ return (ExperimentResource)get(ResourceType.EXPERIMENT, name); } public GFacJobDataResource getGFacJob(String jobId){ return (GFacJobDataResource)get(ResourceType.GFAC_JOB_DATA,jobId); } /** * * @return list of experiments for the user */ public List<ExperimentResource> getExperiments(){ List<ExperimentResource> result=new ArrayList<ExperimentResource>(); List<Resource> list = get(ResourceType.EXPERIMENT); for (Resource resource : list) { result.add((ExperimentResource) resource); } return result; } /** * * @param experimentId experiment name */ public void removeExperiment(String experimentId){ remove(ResourceType.EXPERIMENT, experimentId); } public boolean isWorkflowInstancePresent(String workflowInstanceId){ return isExists(ResourceType.WORKFLOW_DATA, workflowInstanceId); } public WorkflowDataResource getWorkflowInstance(String workflowInstanceId){ return (WorkflowDataResource)get(ResourceType.WORKFLOW_DATA, workflowInstanceId); } public void removeWorkflowInstance(String workflowInstanceId){ remove(ResourceType.WORKFLOW_DATA, workflowInstanceId); } }
9,425
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/ProjectResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.Experiment; import org.apache.airavata.persistance.registry.jpa.model.Gateway; import org.apache.airavata.persistance.registry.jpa.model.Project; import org.apache.airavata.persistance.registry.jpa.model.Users; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ProjectResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(ProjectResource.class); private String name; private GatewayResource gateway; private WorkerResource worker; /** * */ public ProjectResource() { } /** * * @param worker gateway worker * @param gateway gateway * @param projectName project name */ public ProjectResource(WorkerResource worker, GatewayResource gateway, String projectName) { this.setWorker(worker); this.setGateway(gateway); this.name = projectName; } /** * * @param type child resource type * @return child resource */ public Resource create(ResourceType type) { if (type == ResourceType.EXPERIMENT) { ExperimentResource experimentResource = new ExperimentResource(); experimentResource.setGateway(getGateway()); experimentResource.setProject(this); experimentResource.setWorker(getWorker()); return experimentResource; } else { logger.error("Unsupported resource type for project resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for project resource."); } } /** * * @param type child resource type * @param name child resource name */ public void remove(ResourceType type, Object name) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); if (type == ResourceType.EXPERIMENT) { QueryGenerator generator = new QueryGenerator(EXPERIMENT); generator.setParameter(ExperimentConstants.EXPERIMENT_ID, name); Query q = generator.deleteQuery(em); q.executeUpdate(); }else { logger.error("Unsupported resource type for project resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for project resource."); } em.getTransaction().commit(); em.close(); } /** * * @param type child resource type * @param name child resource name * @return child resource */ public Resource get(ResourceType type, Object name) { if (type == ResourceType.EXPERIMENT) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator = new QueryGenerator(EXPERIMENT); generator.setParameter(ExperimentConstants.EXPERIMENT_ID, name); Query q = generator.selectQuery(em); Experiment experiment = (Experiment) q.getSingleResult(); ExperimentResource experimentResource = (ExperimentResource) Utils.getResource(ResourceType.EXPERIMENT, experiment); em.getTransaction().commit(); em.close(); return experimentResource; }else{ logger.error("Unsupported resource type for project resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for project resource."); } } /** * * @param keys project name * @return project resource */ public List<Resource> populate(Object[] keys) { List<Resource> list = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator queryGenerator = new QueryGenerator(PROJECT); queryGenerator.setParameter(ProjectConstants.PROJECT_NAME, keys[0]); Query q = queryGenerator.selectQuery(em); List<?> resultList = q.getResultList(); if (resultList.size() != 0) { for (Object result : resultList) { Project project = (Project) result; ProjectResource projectResource = (ProjectResource) Utils.getResource(ResourceType.PROJECT, project); list.add(projectResource); } } em.getTransaction().commit(); em.close(); return list; } /** * * @param type child resource type * @return list of child resources */ public List<Resource> get(ResourceType type) { List<Resource> resourceList = new ArrayList<Resource>(); if (type == ResourceType.EXPERIMENT) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator = new QueryGenerator(EXPERIMENT); generator.setParameter(ExperimentConstants.PROJECT_NAME, name); Query q = generator.selectQuery(em); List<?> results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Experiment experiment = (Experiment) result; ExperimentResource experimentResource = (ExperimentResource) Utils.getResource(ResourceType.EXPERIMENT, experiment); resourceList.add(experimentResource); } } em.getTransaction().commit(); em.close(); } else { logger.error("Unsupported resource type for project resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for project resource."); } return resourceList; } /** * save project to the database */ public void save() { EntityManager em = ResourceUtils.getEntityManager(); Project existingprojectResource = em.find(Project.class, name); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Project project = new Project(); project.setProject_name(name); Gateway modelGateway = em.find(Gateway.class, gateway.getGatewayName()); project.setGateway(modelGateway); Users user = em.find(Users.class, worker.getUser()); project.setUsers(user); if(existingprojectResource != null){ existingprojectResource.setGateway(modelGateway); existingprojectResource.setUsers(user); project = em.merge(existingprojectResource); }else { em.persist(project); } em.getTransaction().commit(); em.close(); } /** * * @return project name */ public String getName() { return name; } /** * * @param name project name */ public void setName(String name) { this.name = name; } /** * * @return gateway worker */ public WorkerResource getWorker() { return worker; } /** * * @param worker gateway worker */ public void setWorker(WorkerResource worker) { this.worker = worker; } /** * * @return gateway resource */ public GatewayResource getGateway() { return gateway; } /** * * @param gateway gateway resource */ public void setGateway(GatewayResource gateway) { this.gateway = gateway; } /** * * @param experimentId experiment ID * @return whether the experiment exist */ public boolean isExperimentExists(String experimentId){ return isExists(ResourceType.EXPERIMENT, experimentId); } /** * * @param experimentId experiment ID * @return experiment resource */ public ExperimentResource createExperiment(String experimentId){ ExperimentResource experimentResource = (ExperimentResource)create(ResourceType.EXPERIMENT); experimentResource.setExpID(experimentId); return experimentResource; } /** * * @param experimentId experiment ID * @return experiment resource */ public ExperimentResource getExperiment(String experimentId){ return (ExperimentResource)get(ResourceType.EXPERIMENT,experimentId); } /** * * @return list of experiments */ public List<ExperimentResource> getExperiments(){ List<Resource> list = get(ResourceType.EXPERIMENT); List<ExperimentResource> result=new ArrayList<ExperimentResource>(); for (Resource resource : list) { result.add((ExperimentResource) resource); } return result; } /** * * @param experimentId experiment ID */ public void removeExperiment(String experimentId){ remove(ResourceType.EXPERIMENT, experimentId); } }
9,426
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/ExperimentMetadataResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.Experiment_Metadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import java.util.List; public class ExperimentMetadataResource extends AbstractResource { private static final Logger logger = LoggerFactory.getLogger(ExperimentMetadataResource.class); private String expID; private String metadata; public String getExpID() { return expID; } public String getMetadata() { return metadata; } public void setExpID(String expID) { this.expID = expID; } public void setMetadata(String metadata) { this.metadata = metadata; } public Resource create(ResourceType type) { logger.error("Unsupported operation for experiment metadata resource " + "since there are no child resources generated by experiment metadata resource.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } public void remove(ResourceType type, Object name) { logger.error("Unsupported operation for experiment metadata resource " + "since there are no child resources generated by experiment metadata resource.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } public Resource get(ResourceType type, Object name) { logger.error("Unsupported operation for experiment metadata resource " + "since there are no child resources generated by experiment metadata resource.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } public List<Resource> get(ResourceType type) { logger.error("Unsupported operation for experiment metadata resource " + "since there are no child resources generated by experiment metadata resource.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } public void save() { EntityManager em = ResourceUtils.getEntityManager(); Experiment_Metadata existingExpMetaData = em.find(Experiment_Metadata.class, expID); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Experiment_Metadata experimentMetadata = new Experiment_Metadata(); experimentMetadata.setExperiment_ID(expID); byte[] contentBytes = metadata.getBytes(); experimentMetadata.setMetadata(contentBytes); if (existingExpMetaData != null) { existingExpMetaData.setMetadata(contentBytes); existingExpMetaData.setExperiment_ID(expID); experimentMetadata = em.merge(existingExpMetaData); } else { em.persist(experimentMetadata); } em.getTransaction().commit(); em.close(); } }
9,427
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/UserResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import java.security.NoSuchAlgorithmException; import java.util.List; import org.apache.airavata.common.utils.SecurityUtil; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.Users; import org.apache.airavata.registry.api.exception.RegistrySettingsException; import org.apache.airavata.registry.api.util.RegistrySettings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; public class UserResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(UserResource.class); private String userName; private String password; private String gatewayName; private ProjectResource projectResource; /** * */ public UserResource() { } /** * * @param userName user name */ public void setUserName(String userName) { this.userName = userName; } /** * * @return user name */ public String getUserName() { return userName; } /** * * @return gateway name */ public String getGatewayName() { return gatewayName; } /** * * @param gatewayName gateway name */ public void setGatewayName(String gatewayName) { this.gatewayName = gatewayName; } /** * User is a hypothical data structure. * @param type child resource type * @return child resource */ public Resource create(ResourceType type) { logger.error("Unsupported resource type for user resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * * @param type child resource type * @param name child resource name */ public void remove(ResourceType type, Object name) { logger.error("Unsupported resource type for user resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * * @param type child resource type * @param name child resource name * @return UnsupportedOperationException */ public Resource get(ResourceType type, Object name) { logger.error("Unsupported resource type for user resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * * @param type child resource type * @return UnsupportedOperationException */ public List<Resource> get(ResourceType type) { logger.error("Unsupported resource type for user resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * save user to the database */ public void save() { EntityManager em = ResourceUtils.getEntityManager(); Users existingUser = em.find(Users.class, userName); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Users user = new Users(); user.setUser_name(userName); try { user.setPassword(SecurityUtil.digestString(password, RegistrySettings.getSetting("default.registry.password.hash.method"))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error hashing default admin password. Invalid hash algorithm.", e); } catch (RegistrySettingsException e) { throw new RuntimeException("Error reading hash algorithm from configurations", e); } if(existingUser != null){ try { existingUser.setPassword(SecurityUtil.digestString(password, RegistrySettings.getSetting("default.registry.password.hash.method"))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error hashing default admin password. Invalid hash algorithm.", e); } catch (RegistrySettingsException e) { throw new RuntimeException("Error reading hash algorithm from configurations", e); } user = em.merge(existingUser); }else { em.persist(user); } em.getTransaction().commit(); em.close(); } /** * * @param type child resource type * @param name child resource name * @return UnsupportedOperationException */ public boolean isExists(ResourceType type, Object name) { logger.error("Unsupported resource type for user resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * * @return project resource */ public ProjectResource getProjectResource() { return projectResource; } /** * * @param projectResource project resource */ public void setProjectResource(ProjectResource projectResource) { this.projectResource = projectResource; } /** * * @return password */ public String getPassword() { return password; } /** * * @param password password */ public void setPassword(String password) { this.password = password; } }
9,428
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/Utils.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import java.net.URI; import org.apache.airavata.persistance.registry.jpa.JPAConstants; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.model.*; import org.apache.airavata.registry.api.AiravataRegistryConnectionDataProvider; import org.apache.airavata.registry.api.AiravataRegistryFactory; import org.apache.airavata.registry.api.exception.RegistrySettingsException; import org.apache.airavata.registry.api.util.RegistrySettings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Utils { private final static Logger logger = LoggerFactory.getLogger(Utils.class); public static String getJDBCFullURL(){ String jdbcUrl = getJDBCURL(); String jdbcUser = getJDBCUser(); String jdbcPassword = getJDBCPassword(); jdbcUrl = jdbcUrl + "?" + "user=" + jdbcUser + "&" + "password=" + jdbcPassword; return jdbcUrl; } public static String getJDBCURL(){ try { return getProvider().getValue(JPAConstants.KEY_JDBC_URL).toString(); } catch (RegistrySettingsException e) { logger.error(e.getMessage(), e); return null; } } public static String getHost(){ try{ String jdbcURL = getJDBCURL(); String cleanURI = jdbcURL.substring(5); URI uri = URI.create(cleanURI); return uri.getHost(); } catch (Exception e) { logger.error(e.getMessage(), e); return null; } } public static int getPort(){ try{ String jdbcURL = getJDBCURL(); String cleanURI = jdbcURL.substring(5); URI uri = URI.create(cleanURI); return uri.getPort(); } catch (Exception e) { logger.error(e.getMessage(), e); return -1; } } public static String getDBType(){ try{ String jdbcURL = getJDBCURL(); String cleanURI = jdbcURL.substring(5); URI uri = URI.create(cleanURI); return uri.getScheme(); } catch (Exception e) { logger.error(e.getMessage(), e); return null; } } public static boolean isDerbyStartEnabled(){ try { String s = getProvider().getValue(JPAConstants.KEY_DERBY_START_ENABLE).toString(); if("true".equals(s)){ return true; } } catch (RegistrySettingsException e) { logger.error(e.getMessage(), e); return false; } return false; } private static AiravataRegistryConnectionDataProvider getProvider() { return AiravataRegistryFactory.getRegistryConnectionDataProvider(); } static { if(AiravataRegistryFactory.getRegistryConnectionDataProvider() == null){ AiravataRegistryFactory.registerRegistryConnectionDataProvider(new AiravataRegistryConnectionDataProviderImpl()); } } public static String getJDBCUser(){ try { if (getProvider()!=null){ return getProvider().getValue(JPAConstants.KEY_JDBC_USER).toString(); } else { return RegistrySettings.getSetting(JPAConstants.KEY_JDBC_USER); } } catch (RegistrySettingsException e) { logger.error(e.getMessage(), e); return null; } } public static String getValidationQuery(){ try { if (getProvider()!=null){ if(getProvider().getValue(JPAConstants.VALIDATION_QUERY) != null){ return getProvider().getValue(JPAConstants.VALIDATION_QUERY).toString(); } } else { if(getProvider().getValue(JPAConstants.VALIDATION_QUERY) != null){ return RegistrySettings.getSetting(JPAConstants.VALIDATION_QUERY); } } return ""; } catch (RegistrySettingsException e) { logger.error(e.getMessage(), e); return null; } } public static String getJPAConnectionProperties(){ try { if (getProvider()!=null){ if(getProvider().getValue(JPAConstants.CONNECTION_JPA_PROPERTY) != null){ return getProvider().getValue(JPAConstants.CONNECTION_JPA_PROPERTY).toString(); } } else { if(getProvider().getValue(JPAConstants.CONNECTION_JPA_PROPERTY) != null){ return RegistrySettings.getSetting(JPAConstants.CONNECTION_JPA_PROPERTY); } } return ""; } catch (RegistrySettingsException e) { logger.error(e.getMessage(), e); return null; } } public static String getJDBCPassword(){ try { if (getProvider()!=null){ return getProvider().getValue(JPAConstants.KEY_JDBC_PASSWORD).toString(); }else { return RegistrySettings.getSetting(JPAConstants.KEY_JDBC_PASSWORD); } } catch (RegistrySettingsException e) { logger.error(e.getMessage(), e); return null; } } public static String getJDBCDriver(){ try { if (getProvider()!=null){ return getProvider().getValue(JPAConstants.KEY_JDBC_DRIVER).toString(); } else { return RegistrySettings.getSetting(JPAConstants.KEY_JDBC_DRIVER); } } catch (RegistrySettingsException e) { logger.error(e.getMessage(), e); return null; } } /** * * @param type model type * @param o model type instance * @return corresponding resource object */ public static Resource getResource(ResourceType type, Object o) { switch (type){ case GATEWAY: if (o instanceof Gateway) { return createGateway((Gateway) o); } else { logger.error("Object should be a Gateway.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Gateway."); } case PROJECT: if (o instanceof Project){ return createProject((Project) o); } else { logger.error("Object should be a Project.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Project."); } case CONFIGURATION: if(o instanceof Configuration){ return createConfiguration((Configuration) o); }else { logger.error("Object should be a Configuration.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Configuration."); } case APPLICATION_DESCRIPTOR: if (o instanceof Application_Descriptor){ return createApplicationDescriptor((Application_Descriptor) o); } else { logger.error("Object should be a Application Descriptor.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Application Descriptor."); } case EXPERIMENT: if (o instanceof Experiment){ return createExperiment((Experiment) o); } else { logger.error("Object should be a Experiment.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Experiment."); } case USER: if(o instanceof Users) { return createUser((Users) o); }else { logger.error("Object should be a User.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a User."); } case HOST_DESCRIPTOR: if (o instanceof Host_Descriptor){ return createHostDescriptor((Host_Descriptor) o); }else { logger.error("Object should be a Host Descriptor.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Host Descriptor."); } case SERVICE_DESCRIPTOR: if (o instanceof Service_Descriptor){ return createServiceDescriptor((Service_Descriptor) o); }else { logger.error("Object should be a Service Descriptor.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Service Descriptor."); } case PUBLISHED_WORKFLOW: if (o instanceof Published_Workflow){ return createPublishWorkflow((Published_Workflow) o); }else { logger.error("Object should be a Publish Workflow.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Publish Workflow."); } case USER_WORKFLOW: if (o instanceof User_Workflow){ return createUserWorkflow((User_Workflow) o); }else { logger.error("Object should be a User Workflow.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a User Workflow."); } case GATEWAY_WORKER: if (o instanceof Gateway_Worker){ return createGatewayWorker((Gateway_Worker)o); } else { logger.error("Object should be a Gateway Worker.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Gateway Worker."); } case EXPERIMENT_DATA: if (o instanceof Experiment_Data){ return createExperimentData((Experiment_Data)o); }else { logger.error("Object should be a Experiment Data.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Experiment Data."); } case EXPERIMENT_METADATA: if (o instanceof Experiment_Metadata){ return createExperimentMetadata((Experiment_Metadata)o); }else { logger.error("Object should be a Experiment Metadata.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Experiment Metadata."); } case WORKFLOW_DATA: if (o instanceof Workflow_Data){ return createWorkflowData((Workflow_Data) o); }else { logger.error("Object should be a Workflow Data.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Workflow Data."); } case NODE_DATA: if (o instanceof Node_Data){ return createNodeData((Node_Data) o); }else { logger.error("Object should be a Node Data.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Node Data."); } case GRAM_DATA: if (o instanceof Gram_Data){ return createGramData((Gram_Data) o); }else { logger.error("Object should be a Gram Data.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Gram Data."); } case EXECUTION_ERROR: if (o instanceof Execution_Error){ return createExecutionError((Execution_Error) o); }else { logger.error("Object should be a Node Error type.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a Node Error."); } case GFAC_JOB_DATA: if (o instanceof GFac_Job_Data){ return createGfacJobData((GFac_Job_Data) o); }else { logger.error("Object should be a GFac Job Data type.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a GFac Job Data."); } case GFAC_JOB_STATUS: if (o instanceof GFac_Job_Status){ return createGfacJobStatus((GFac_Job_Status) o); }else { logger.error("Object should be a GFac Job Status type.", new IllegalArgumentException()); throw new IllegalArgumentException("Object should be a GFac Job Status."); } default: } return null; } /** * * @param o Gateway model object * @return GatewayResource object */ private static Resource createGateway(Gateway o) { GatewayResource gatewayResource = new GatewayResource(); gatewayResource.setGatewayName(o.getGateway_name()); return gatewayResource; } /** * * @param o Project model object * @return ProjectResource object */ private static Resource createProject(Project o) { ProjectResource projectResource = new ProjectResource(); projectResource.setName(o.getProject_name()); GatewayResource gatewayResource = (GatewayResource)createGateway(o.getGateway()); projectResource.setGateway(gatewayResource); Gateway_Worker gateway_worker = new Gateway_Worker(); gateway_worker.setGateway(o.getGateway()); gateway_worker.setUser(o.getUsers()); WorkerResource workerResource = (WorkerResource) createGatewayWorker(gateway_worker); projectResource.setWorker(workerResource); return projectResource; } /** * * @param o configuration model object * @return configuration resource object */ private static Resource createConfiguration (Configuration o){ ConfigurationResource configurationResource = new ConfigurationResource(); configurationResource.setConfigKey(o.getConfig_key()); configurationResource.setConfigVal(o.getConfig_val()); configurationResource.setExpireDate(o.getExpire_date()); configurationResource.setCategoryID(o.getCategory_id()); return configurationResource; } /** * * @param o application descriptor model object * @return application descriptor resource object */ private static Resource createApplicationDescriptor(Application_Descriptor o) { ApplicationDescriptorResource applicationDescriptorResource = new ApplicationDescriptorResource(); applicationDescriptorResource.setName(o.getApplication_descriptor_ID()); applicationDescriptorResource.setHostDescName(o.getHost_descriptor_ID()); applicationDescriptorResource.setServiceDescName(o.getService_descriptor_ID()); applicationDescriptorResource.setContent(new String(o.getApplication_descriptor_xml())); applicationDescriptorResource.setUpdatedUser(o.getUser().getUser_name()); applicationDescriptorResource.setGatewayName(o.getGateway().getGateway_name()); return applicationDescriptorResource; } /** * * @param o Experiment model object * @return Experiment resource object */ private static Resource createExperiment(Experiment o) { ExperimentResource experimentResource = new ExperimentResource(); GatewayResource gatewayResource = (GatewayResource)createGateway(o.getGateway()); experimentResource.setGateway(gatewayResource); Gateway_Worker gateway_worker = new Gateway_Worker(); gateway_worker.setGateway(o.getGateway()); gateway_worker.setUser(o.getUser()); WorkerResource workerResource = (WorkerResource) createGatewayWorker(gateway_worker); experimentResource.setWorker(workerResource); ProjectResource projectResource = (ProjectResource)createProject(o.getProject()); experimentResource.setProject(projectResource); experimentResource.setExpID(o.getExperiment_ID()); experimentResource.setSubmittedDate(o.getSubmitted_date()); return experimentResource; } /** * * @param o Gateway_Worker model object * @return Gateway_Worker resource object */ private static Resource createGatewayWorker(Gateway_Worker o) { GatewayResource gatewayResource = new GatewayResource(o.getGateway().getGateway_name()); gatewayResource.setOwner(o.getGateway().getOwner()); WorkerResource workerResource = new WorkerResource(o.getUser().getUser_name(), gatewayResource); return workerResource; } /** * * @param o Host_Descriptor model object * @return HostDescriptor resource object */ private static Resource createHostDescriptor(Host_Descriptor o) { try { HostDescriptorResource hostDescriptorResource = new HostDescriptorResource(); hostDescriptorResource.setGatewayName(o.getGateway().getGateway_name()); hostDescriptorResource.setUserName(o.getUser().getUser_name()); hostDescriptorResource.setHostDescName(o.getHost_descriptor_ID()); byte[] bytes = o.getHost_descriptor_xml(); hostDescriptorResource.setContent(new String(bytes)); return hostDescriptorResource; } catch (Exception e) { e.printStackTrace(); return null; } } /** * * @param o Published_Workflow model object * @return Published Workflow resource object */ private static Resource createPublishWorkflow(Published_Workflow o) { PublishWorkflowResource publishWorkflowResource = new PublishWorkflowResource(); GatewayResource gatewayResource = (GatewayResource)createGateway(o.getGateway()); publishWorkflowResource.setGateway(gatewayResource); publishWorkflowResource.setCreatedUser(o.getUser().getUser_name()); publishWorkflowResource.setName(o.getPublish_workflow_name()); publishWorkflowResource.setContent(new String(o.getWorkflow_content())); publishWorkflowResource.setPublishedDate(o.getPublished_date()); publishWorkflowResource.setVersion(o.getVersion()); publishWorkflowResource.setPath(o.getPath()); return publishWorkflowResource; } /** * * @param o Service_Descriptor model object * @return ServiceDescriptor resource object */ private static Resource createServiceDescriptor(Service_Descriptor o) { ServiceDescriptorResource serviceDescriptorResource = new ServiceDescriptorResource(); serviceDescriptorResource.setGatewayName(o.getGateway().getGateway_name()); serviceDescriptorResource.setUserName(o.getUser().getUser_name()); serviceDescriptorResource.setServiceDescName(o.getService_descriptor_ID()); serviceDescriptorResource.setContent(new String(o.getService_descriptor_xml())); return serviceDescriptorResource; } /** * * @param o User_Workflow model object * @return User_Workflow resource object */ private static Resource createUserWorkflow(User_Workflow o) { UserWorkflowResource userWorkflowResource = new UserWorkflowResource(); userWorkflowResource.setName(o.getTemplate_name()); GatewayResource gatewayResource = (GatewayResource)createGateway(o.getGateway()); userWorkflowResource.setGateway(gatewayResource); Gateway_Worker gateway_worker = new Gateway_Worker(); gateway_worker.setGateway(o.getGateway()); gateway_worker.setUser(o.getUser()); WorkerResource workerResource = (WorkerResource) createGatewayWorker(gateway_worker); userWorkflowResource.setWorker(workerResource); userWorkflowResource.setLastUpdateDate(o.getLast_updated_date()); userWorkflowResource.setContent(new String(o.getWorkflow_graph())); userWorkflowResource.setPath(o.getPath()); return userWorkflowResource; } /** * * @param o Users model object * @return UserResource object */ private static Resource createUser(Users o) { UserResource userResource = new UserResource(); userResource.setUserName(o.getUser_name()); userResource.setPassword(o.getPassword()); return userResource; } /** * * @param o Experiment Data model object * @return Experiment Data resource object */ private static Resource createExperimentData(Experiment_Data o){ ExperimentDataResource experimentDataResource = new ExperimentDataResource(); experimentDataResource.setExperimentID(o.getExperiment_ID()); experimentDataResource.setExpName(o.getName()); experimentDataResource.setUserName(o.getUsername()); return experimentDataResource; } /** * * @param o Experiment MetaData model object * @return Experiment MetaData resource object */ private static Resource createExperimentMetadata(Experiment_Metadata o) { ExperimentMetadataResource experimentMetadataResource = new ExperimentMetadataResource(); experimentMetadataResource.setExpID(o.getExperiment_ID()); experimentMetadataResource.setMetadata(new String(o.getMetadata())); return experimentMetadataResource; } /** * * @param o Workflow_Data model object * @return WorkflowDataResource object */ private static Resource createWorkflowData(Workflow_Data o){ WorkflowDataResource workflowDataResource = new WorkflowDataResource(); workflowDataResource.setExperimentID(o.getExperiment_data().getExperiment_ID()); workflowDataResource.setWorkflowInstanceID(o.getWorkflow_instanceID()); workflowDataResource.setTemplateName(o.getTemplate_name()); workflowDataResource.setStatus(o.getStatus()); workflowDataResource.setStartTime(o.getStart_time()); workflowDataResource.setLastUpdatedTime(o.getLast_update_time()); return workflowDataResource; } /** * * @param o Node_Data model object * @return Node Data resource */ private static Resource createNodeData (Node_Data o){ NodeDataResource nodeDataResource = new NodeDataResource(); WorkflowDataResource workflowDataResource = (WorkflowDataResource)createWorkflowData(o.getWorkflow_Data()); nodeDataResource.setWorkflowDataResource(workflowDataResource); nodeDataResource.setNodeID(o.getNode_id()); nodeDataResource.setNodeType(o.getNode_type()); if (o.getInputs()!=null) { nodeDataResource.setInputs(new String(o.getInputs())); } if (o.getOutputs()!=null) { nodeDataResource.setOutputs(new String(o.getOutputs())); } nodeDataResource.setStatus(o.getStatus()); nodeDataResource.setStartTime(o.getStart_time()); nodeDataResource.setLastUpdateTime(o.getLast_update_time()); nodeDataResource.setExecutionIndex(o.getExecution_index()); return nodeDataResource; } /** * * @param o GramData model object * @return GramData Resource object */ private static Resource createGramData (Gram_Data o){ GramDataResource gramDataResource = new GramDataResource(); WorkflowDataResource workflowDataResource = (WorkflowDataResource)createWorkflowData(o.getWorkflow_Data()); gramDataResource.setWorkflowDataResource(workflowDataResource); gramDataResource.setNodeID(o.getNode_id()); gramDataResource.setRsl(new String(o.getRsl())); gramDataResource.setInvokedHost(o.getInvoked_host()); gramDataResource.setLocalJobID(o.getLocal_Job_ID()); return gramDataResource; } private static Resource createExecutionError(Execution_Error o){ ExecutionErrorResource executionErrorResource = new ExecutionErrorResource(); ExperimentDataResource experimentDataResource = (ExperimentDataResource)createExperimentData(o.getExperiment_Data()); executionErrorResource.setExperimentDataResource(experimentDataResource); WorkflowDataResource workflowDataResource = (WorkflowDataResource)createWorkflowData(o.getWorkflow_Data()); executionErrorResource.setWorkflowDataResource(workflowDataResource); executionErrorResource.setNodeID(o.getNode_id()); executionErrorResource.setErrorID(o.getError_id()); executionErrorResource.setGfacJobID(o.getGfacJobID()); executionErrorResource.setSourceType(o.getSource_type()); executionErrorResource.setErrorTime(o.getError_date()); executionErrorResource.setErrorMsg(o.getError_msg()); executionErrorResource.setErrorDes(o.getError_des()); executionErrorResource.setErrorCode(o.getError_code()); executionErrorResource.setErrorReporter(o.getError_reporter()); executionErrorResource.setErrorLocation(o.getError_location()); executionErrorResource.setActionTaken(o.getAction_taken()); executionErrorResource.setErrorReference(o.getError_reference()); return executionErrorResource; } private static Resource createGfacJobData (GFac_Job_Data o){ GFacJobDataResource gFacJobDataResource = new GFacJobDataResource(); ExperimentDataResource experimentDataResource = (ExperimentDataResource)createExperimentData(o.getExperiment_data()); WorkflowDataResource workflowDataResource = (WorkflowDataResource)createWorkflowData(o.getWorkflow_Data()); gFacJobDataResource.setExperimentDataResource(experimentDataResource); gFacJobDataResource.setWorkflowDataResource(workflowDataResource); gFacJobDataResource.setNodeID(o.getNode_id()); gFacJobDataResource.setApplicationDescID(o.getApplication_descriptor_ID()); gFacJobDataResource.setServiceDescID(o.getService_descriptor_ID()); gFacJobDataResource.setHostDescID(o.getHost_descriptor_ID()); gFacJobDataResource.setJobData(o.getJob_data()); gFacJobDataResource.setLocalJobID(o.getLocal_Job_ID()); gFacJobDataResource.setSubmittedTime(o.getSubmitted_time()); gFacJobDataResource.setStatusUpdateTime(o.getStatus_update_time()); gFacJobDataResource.setStatus(o.getStatus()); gFacJobDataResource.setMetadata(o.getMetadata()); return gFacJobDataResource; } private static Resource createGfacJobStatus(GFac_Job_Status o) { GFacJobStatusResource gFacJobStatusResource = new GFacJobStatusResource(); gFacJobStatusResource.setLocalJobID(o.getLocal_Job_ID()); gFacJobStatusResource.setStatus(o.getStatus()); gFacJobStatusResource.setStatusUpdateTime(o.getStatus_update_time()); GFacJobDataResource gFacJobDataResource = (GFacJobDataResource)createGfacJobData(o.getgFac_job_data()); gFacJobStatusResource.setgFacJobDataResource(gFacJobDataResource); return gFacJobStatusResource; } // public static byte[] getByteArray(String content){ // byte[] contentBytes = content.getBytes(); // return contentBytes; // } }
9,429
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/ServiceDescriptorResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.*; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.Query; import java.util.ArrayList; import java.util.List; public class ServiceDescriptorResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(ServiceDescriptorResource.class); private String serviceDescName; private String gatewayName; private String userName; private String content; public ServiceDescriptorResource() { } public String getGatewayName() { return gatewayName; } public String getUserName() { return userName; } public void setGatewayName(String gatewayName) { this.gatewayName = gatewayName; } public void setUserName(String userName) { this.userName = userName; } public String getServiceDescName() { return serviceDescName; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Resource create(ResourceType type) { if (type == ResourceType.APPLICATION_DESCRIPTOR) { ApplicationDescriptorResource applicationDescriptorResource = new ApplicationDescriptorResource(); applicationDescriptorResource.setGatewayName(gatewayName); applicationDescriptorResource.setHostDescName(getServiceDescName()); return applicationDescriptorResource; } logger.error("Unsupported resource type for service descriptor resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for service descriptor resource."); } public void remove(ResourceType type, Object name) { logger.error("Unsupported resource type for service descriptor resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } public Resource get(ResourceType type, Object name) { logger.error("Unsupported resource type for service descriptor resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } public List<Resource> populate(Object[] keys) { List<Resource> list = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator = new QueryGenerator(SERVICE_DESCRIPTOR); generator.setParameter(ServiceDescriptorConstants.GATEWAY_NAME, keys[0]); generator.setParameter(ServiceDescriptorConstants.SERVICE_DESC_ID, keys[1]); Query q = generator.selectQuery(em); Service_Descriptor serviceDescriptor = (Service_Descriptor)q.getSingleResult(); ServiceDescriptorResource serviceDescriptorResource = (ServiceDescriptorResource)Utils.getResource(ResourceType.SERVICE_DESCRIPTOR, serviceDescriptor); em.getTransaction().commit(); em.close(); list.add(serviceDescriptorResource); return list; } public List<Resource> get(ResourceType type) { List<Resource> resourceList = new ArrayList<Resource>(); if (type == ResourceType.APPLICATION_DESCRIPTOR) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator queryGenerator = new QueryGenerator(APPLICATION_DESCRIPTOR); queryGenerator.setParameter(ApplicationDescriptorConstants.GATEWAY_NAME, gatewayName); queryGenerator.setParameter(ApplicationDescriptorConstants.SERVICE_DESC_ID, serviceDescName); Query q = queryGenerator.selectQuery(em); List results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Application_Descriptor applicationDescriptor = (Application_Descriptor) result; ApplicationDescriptorResource applicationDescriptorResource = (ApplicationDescriptorResource)Utils.getResource(ResourceType.APPLICATION_DESCRIPTOR, applicationDescriptor); resourceList.add(applicationDescriptorResource); } } em.getTransaction().commit(); em.close(); } return resourceList; } public void save() { EntityManager em = ResourceUtils.getEntityManager(); Service_Descriptor existingServiceDesc = em.find(Service_Descriptor.class, new Service_Descriptor_PK(gatewayName, serviceDescName)); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Service_Descriptor serviceDescriptor = new Service_Descriptor(); serviceDescriptor.setService_descriptor_ID(getServiceDescName()); Gateway gateway = em.find(Gateway.class, gatewayName); serviceDescriptor.setGateway(gateway); byte[] bytes = content.getBytes(); serviceDescriptor.setService_descriptor_xml(bytes); Users user = em.find(Users.class, userName); serviceDescriptor.setUser(user); if(existingServiceDesc != null) { existingServiceDesc.setUser(user); existingServiceDesc.setService_descriptor_xml(bytes); serviceDescriptor = em.merge(existingServiceDesc); }else { em.merge(serviceDescriptor); } em.getTransaction().commit(); em.close(); } public boolean isExists(ResourceType type, Object name) { logger.error("Unsupported resource type for service descriptor resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } public void setServiceDescName(String serviceDescName) { this.serviceDescName = serviceDescName; } }
9,430
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/ApplicationDescriptorResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.*; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.Query; import java.util.ArrayList; import java.util.List; public class ApplicationDescriptorResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(ApplicationDescriptorResource.class); private String name; private String gatewayName; private String updatedUser; private String content; private String hostDescName; private String serviceDescName; /** * * @param name application descriptor name * @param gatewayName gateway name * returns ApplicationDescriptorResource */ public ApplicationDescriptorResource(String name, String gatewayName) { this.setName(name); this.gatewayName = gatewayName; } /** * */ public ApplicationDescriptorResource() { } /** * * @return gateway name */ public String getGatewayName() { return gatewayName; } /** * * @param gatewayName gateway name */ public void setGatewayName(String gatewayName) { this.gatewayName = gatewayName; } /** * * @param updatedUser updated user */ public void setUpdatedUser(String updatedUser) { this.updatedUser = updatedUser; } /** * * @return name of the application descriptor */ public String getName() { return name; } /** * * @return content */ public String getContent() { return content; } /** * * @return host descriptor name */ public String getHostDescName() { return hostDescName; } /** * * @return service descriptor name */ public String getServiceDescName() { return serviceDescName; } /** * * @param content content of the application descriptor */ public void setContent(String content) { this.content = content; } /** * * @param hostDescName host descriptor name */ public void setHostDescName(String hostDescName) { this.hostDescName = hostDescName; } /** * * @param serviceDescName service descriptor name */ public void setServiceDescName(String serviceDescName) { this.serviceDescName = serviceDescName; } /** * Since application descriptors are at the leaf level, this method is not * valid for application descriptors * @param type child resource types * @return UnsupportedOperationException */ public Resource create(ResourceType type) { logger.error("Unsupported operation for application descriptor resource " + "since application descriptors could not create child resources.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * Since application descriptors are at the leaf level, this method is not * valid for application descriptors * @param type child resource types * @param name name of the resource */ public void remove(ResourceType type, Object name) { logger.error("Unsupported operation for application descriptor resource " + "since application descriptors could not remove child resources.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * key should be gateway_name, application_descriptor_ID, host_descriptor_ID, service_descriptor_ID * * @param keys primary keys of the Application_descriptor table */ // public void removeMe(Object[] keys) { // EntityManager em = ResourceUtils.getEntityManager(); // em.getTransaction().begin(); // QueryGenerator queryGenerator = new QueryGenerator(APPLICATION_DESCRIPTOR); // queryGenerator.setParameter(ApplicationDescriptorConstants.GATEWAY_NAME, keys[0]); // queryGenerator.setParameter(ApplicationDescriptorConstants.APPLICATION_DESC_ID, keys[1]); // queryGenerator.setParameter(ApplicationDescriptorConstants.HOST_DESC_ID, keys[2]); // queryGenerator.setParameter(ApplicationDescriptorConstants.SERVICE_DESC_ID, keys[3]); // Query q = queryGenerator.deleteQuery(em); // q.executeUpdate(); // em.getTransaction().commit(); // em.close(); // } /** * * Since application descriptors are at the leaf level, this method is not * valid for application descriptors * @param type child resource types * @param name name of the resource * @return UnsupportedOperationException */ public Resource get(ResourceType type, Object name) { logger.error("Unsupported operation for application descriptor resource " + "since there are no child resources generated by application descriptors.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * keys should contain gateway_name, application_descriptor_ID, host_descriptor_ID, service_descriptor_ID * * @param keys names * @return list of ApplicationDescriptorResources */ public List<Resource> populate(Object[] keys) { List<Resource> list = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator queryGenerator = new QueryGenerator(APPLICATION_DESCRIPTOR); queryGenerator.setParameter(ApplicationDescriptorConstants.GATEWAY_NAME, keys[0]); queryGenerator.setParameter(ApplicationDescriptorConstants.APPLICATION_DESC_ID, keys[1]); queryGenerator.setParameter(ApplicationDescriptorConstants.HOST_DESC_ID, keys[2]); queryGenerator.setParameter(ApplicationDescriptorConstants.SERVICE_DESC_ID, keys[3]); Query q = queryGenerator.selectQuery(em); Application_Descriptor applicationDescriptor = (Application_Descriptor) q.getSingleResult(); ApplicationDescriptorResource applicationDescriptorResource = (ApplicationDescriptorResource) Utils.getResource( ResourceType.APPLICATION_DESCRIPTOR, applicationDescriptor); em.getTransaction().commit(); em.close(); list.add(applicationDescriptorResource); return list; } /** * Since application descriptors are at the leaf level, this method is not * valid for application descriptors * @param type child resource types * @return UnsupportedOperationException */ public List<Resource> get(ResourceType type) { logger.error("Unsupported operation for application descriptor resource " + "since there are no child resources generated by application descriptors.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * save application descriptor to database */ public void save() { try{ EntityManager em = ResourceUtils.getEntityManager(); Application_Descriptor existingAppDesc = em.find(Application_Descriptor.class, new Application_Descriptor_PK(gatewayName, name)); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Application_Descriptor applicationDescriptor = new Application_Descriptor(); applicationDescriptor.setApplication_descriptor_ID(getName()); Gateway gateway = em.find(Gateway.class, gatewayName); Users user = em.find(Users.class, updatedUser); applicationDescriptor.setGateway(gateway); applicationDescriptor.setUser(user); byte[] contentBytes = content.getBytes(); applicationDescriptor.setApplication_descriptor_xml(contentBytes); applicationDescriptor.setService_descriptor_ID(serviceDescName); applicationDescriptor.setHost_descriptor_ID(hostDescName); if (existingAppDesc != null) { existingAppDesc.setUser(user); existingAppDesc.setApplication_descriptor_xml(contentBytes); existingAppDesc.setHost_descriptor_ID(hostDescName); existingAppDesc.setService_descriptor_ID(serviceDescName); applicationDescriptor = em.merge(existingAppDesc); } else { em.persist(applicationDescriptor); } em.getTransaction().commit(); em.close(); } catch (Exception e){ e.printStackTrace(); } } /** * Since application descriptors are at the leaf level, this method is not * valid for application descriptors * @param type child resource types * @param name name of the resource * @return UnsupportedOperationException */ public boolean isExists(ResourceType type, Object name) { logger.error("Unsupported operation for application descriptor resource " + "since there are no child resources generated by application descriptors.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * * @param name application descriptor name */ public void setName(String name) { this.name = name; } }
9,431
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/UserWorkflowResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.Gateway; import org.apache.airavata.persistance.registry.jpa.model.User_Workflow; import org.apache.airavata.persistance.registry.jpa.model.User_Workflow_PK; import org.apache.airavata.persistance.registry.jpa.model.Users; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.Query; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; public class UserWorkflowResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(UserWorkflowResource.class); private GatewayResource gateway; private WorkerResource worker; private String name; private Timestamp lastUpdateDate; private String content; private String path; public UserWorkflowResource() { } public UserWorkflowResource(GatewayResource gateway, WorkerResource worker, String name) { this.setGateway(gateway); this.setWorker(worker); this.name = name; } public String getName() { return name; } public void setLastUpdateDate(Timestamp lastUpdateDate) { this.lastUpdateDate = lastUpdateDate; } public void setContent(String content) { this.content = content; } public Timestamp getLastUpdateDate() { return lastUpdateDate; } public String getContent() { return content; } public void setName(String name) { this.name = name; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Resource create(ResourceType type) { logger.error("Unsupported resource type for user workflow resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } public void remove(ResourceType type, Object name) { logger.error("Unsupported resource type for user workflow resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } public Resource get(ResourceType type, Object name) { logger.error("Unsupported resource type for user workflow resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * * @param keys should be in the order of gateway_name,user_name and user_workflow_name * @return resource list */ public List<Resource> populate(Object[] keys) { List<Resource> list = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator queryGenerator = new QueryGenerator(USER_WORKFLOW); queryGenerator.setParameter(UserWorkflowConstants.GATEWAY_NAME, keys[0]); queryGenerator.setParameter(UserWorkflowConstants.OWNER, keys[1]); queryGenerator.setParameter(UserWorkflowConstants.TEMPLATE_NAME, keys[2]); Query q = queryGenerator.selectQuery(em); User_Workflow userWorkflow = (User_Workflow)q.getSingleResult(); UserWorkflowResource userWorkflowResource = (UserWorkflowResource)Utils.getResource( ResourceType.USER_WORKFLOW, userWorkflow); em.getTransaction().commit(); em.close(); list.add(userWorkflowResource); return list; } public List<Resource> get(ResourceType type) { logger.error("Unsupported resource type for user workflow resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } public void save() { EntityManager em = ResourceUtils.getEntityManager(); User_Workflow existingWF = em.find(User_Workflow.class, new User_Workflow_PK(name, worker.getUser(), gateway.getGatewayName())); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); User_Workflow userWorkflow = new User_Workflow(); userWorkflow.setTemplate_name(name); if(lastUpdateDate == null){ java.util.Date date= new java.util.Date(); lastUpdateDate = new Timestamp(date.getTime()); } userWorkflow.setLast_updated_date(lastUpdateDate); byte[] bytes = content.getBytes(); userWorkflow.setWorkflow_graph(bytes); userWorkflow.setGateway_name(this.gateway.getGatewayName()); userWorkflow.setOwner(this.getWorker().getUser()); userWorkflow.setPath(path); if(existingWF != null){ existingWF.setGateway_name(this.gateway.getGatewayName()); existingWF.setOwner(this.getWorker().getUser()); existingWF.setTemplate_name(name); existingWF.setLast_updated_date(lastUpdateDate); existingWF.setPath(path); existingWF.setWorkflow_graph(bytes); userWorkflow = em.merge(existingWF); } else { em.persist(userWorkflow); } em.getTransaction().commit(); em.close(); } public boolean isExists(ResourceType type, Object name) { logger.error("Unsupported resource type for user workflow resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } public GatewayResource getGateway() { return gateway; } public void setGateway(GatewayResource gateway) { this.gateway = gateway; } public WorkerResource getWorker() { return worker; } public void setWorker(WorkerResource worker) { this.worker = worker; } }
9,432
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/AiravataRegistryConnectionDataProviderImpl.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.registry.api.AiravataRegistryConnectionDataProvider; import org.apache.airavata.registry.api.AiravataUser; import org.apache.airavata.registry.api.Gateway; import org.apache.airavata.registry.api.exception.RegistrySettingsException; import org.apache.airavata.registry.api.exception.UnknownRegistryConnectionDataException; import org.apache.airavata.registry.api.util.RegistrySettings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URL; import java.util.Properties; public class AiravataRegistryConnectionDataProviderImpl implements AiravataRegistryConnectionDataProvider { private final static Logger logger = LoggerFactory.getLogger(AiravataRegistryConnectionDataProviderImpl.class); public void setIdentity(Gateway gateway, AiravataUser use) { } public Object getValue(String key) throws RegistrySettingsException { return RegistrySettings.getSetting(key); } }
9,433
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/WorkflowDataResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.*; import org.apache.airavata.persistance.registry.jpa.resources.AbstractResource.GFacJobDataConstants; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.Query; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; public class WorkflowDataResource extends AbstractResource{ private final static Logger logger = LoggerFactory.getLogger(WorkflowDataResource.class); public static final String NODE_DATA = "Node_Data"; public static final String GRAM_DATA = "Gram_Data"; public static final String EXECUTION_ERROR = "Execution_Error"; private String experimentID; private String workflowInstanceID; private String templateName; private String status; private Timestamp startTime; private Timestamp lastUpdatedTime; public String getExperimentID() { return experimentID; } public String getWorkflowInstanceID() { return workflowInstanceID; } public String getTemplateName() { return templateName; } public String getStatus() { return status; } public void setExperimentID(String experimentID) { this.experimentID = experimentID; } public void setWorkflowInstanceID(String workflowInstanceID) { this.workflowInstanceID = workflowInstanceID; } public void setTemplateName(String templateName) { this.templateName = templateName; } public void setStatus(String status) { this.status = status; } public Timestamp getStartTime() { return startTime; } public Timestamp getLastUpdatedTime() { return lastUpdatedTime; } public void setStartTime(Timestamp startTime) { this.startTime = startTime; } public void setLastUpdatedTime(Timestamp lastUpdatedTime) { this.lastUpdatedTime = lastUpdatedTime; } public Resource create(ResourceType type) { switch (type){ case NODE_DATA: NodeDataResource nodeDataResource = new NodeDataResource(); nodeDataResource.setWorkflowDataResource(this); return nodeDataResource; case GRAM_DATA: GramDataResource gramDataResource = new GramDataResource(); gramDataResource.setWorkflowDataResource(this); return gramDataResource; case EXECUTION_ERROR: ExecutionErrorResource executionErrorResource = new ExecutionErrorResource(); executionErrorResource.setWorkflowDataResource(this); return executionErrorResource; case GFAC_JOB_DATA: GFacJobDataResource gFacJobDataResource = new GFacJobDataResource(); gFacJobDataResource.setWorkflowDataResource(this); return gFacJobDataResource; default: logger.error("Unsupported resource type for workflow data resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for workflow data resource."); } } public void remove(ResourceType type, Object name) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Query q; QueryGenerator generator; switch (type){ case NODE_DATA: generator = new QueryGenerator(NODE_DATA); generator.setParameter(NodeDataConstants.WORKFLOW_INSTANCE_ID, workflowInstanceID); generator.setParameter(NodeDataConstants.NODE_ID, name); q = generator.deleteQuery(em); q.executeUpdate(); break; case GRAM_DATA: generator = new QueryGenerator(GRAM_DATA); generator.setParameter(GramDataConstants.WORKFLOW_INSTANCE_ID, workflowInstanceID); generator.setParameter(GramDataConstants.NODE_ID, name); q = generator.deleteQuery(em); q.executeUpdate(); break; case EXECUTION_ERROR: generator = new QueryGenerator(EXECUTION_ERROR); generator.setParameter(ExecutionErrorConstants.ERROR_ID, name); q = generator.deleteQuery(em); q.executeUpdate(); break; case GFAC_JOB_DATA: generator = new QueryGenerator(GFAC_JOB_DATA); generator.setParameter(GFacJobDataConstants.LOCAL_JOB_ID, name); q = generator.deleteQuery(em); q.executeUpdate(); break; default: logger.error("Unsupported resource type for workflow data resource.", new IllegalArgumentException()); break; } em.getTransaction().commit(); em.close(); } public Resource get(ResourceType type, Object name) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator; Query q; switch (type) { case NODE_DATA: generator = new QueryGenerator(NODE_DATA); generator.setParameter(NodeDataConstants.WORKFLOW_INSTANCE_ID, workflowInstanceID); generator.setParameter(NodeDataConstants.NODE_ID, name); q = generator.selectQuery(em); Node_Data enodeDeata = (Node_Data)q.getSingleResult(); NodeDataResource nodeDataResource = (NodeDataResource)Utils.getResource(ResourceType.NODE_DATA, enodeDeata); em.getTransaction().commit(); em.close(); return nodeDataResource; case GRAM_DATA: generator = new QueryGenerator(GRAM_DATA); generator.setParameter(GramDataConstants.WORKFLOW_INSTANCE_ID, workflowInstanceID); generator.setParameter(GramDataConstants.NODE_ID, name); q = generator.selectQuery(em); Gram_Data egramData = (Gram_Data)q.getSingleResult(); GramDataResource gramDataResource = (GramDataResource)Utils.getResource(ResourceType.GRAM_DATA, egramData); em.getTransaction().commit(); em.close(); return gramDataResource; case EXECUTION_ERROR: generator = new QueryGenerator(EXECUTION_ERROR); generator.setParameter(ExecutionErrorConstants.ERROR_ID, name); q = generator.selectQuery(em); Execution_Error execution_error = (Execution_Error)q.getSingleResult(); ExecutionErrorResource executionErrorResource = (ExecutionErrorResource)Utils.getResource(ResourceType.EXECUTION_ERROR, execution_error); em.getTransaction().commit(); em.close(); return executionErrorResource; case GFAC_JOB_DATA: generator = new QueryGenerator(GFAC_JOB_DATA); generator.setParameter(GFacJobDataConstants.LOCAL_JOB_ID, name); q = generator.selectQuery(em); GFac_Job_Data gFac_job_data = (GFac_Job_Data)q.getSingleResult(); GFacJobDataResource gFacJobDataResource = (GFacJobDataResource)Utils.getResource(ResourceType.GFAC_JOB_DATA, gFac_job_data); em.getTransaction().commit(); em.close(); return gFacJobDataResource; default: em.getTransaction().commit(); em.close(); logger.error("Unsupported resource type for workflow data resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for workflow data resource."); } } public List<Resource> get(ResourceType type) { List<Resource> resourceList = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Query q; QueryGenerator generator; List<?> results; switch (type){ case NODE_DATA: generator = new QueryGenerator(NODE_DATA); generator.setParameter(NodeDataConstants.WORKFLOW_INSTANCE_ID, workflowInstanceID); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Node_Data nodeData = (Node_Data)result; NodeDataResource nodeDataResource = (NodeDataResource)Utils.getResource(ResourceType.NODE_DATA,nodeData); resourceList.add(nodeDataResource); } } break; case GRAM_DATA: generator = new QueryGenerator(GRAM_DATA); generator.setParameter(GramDataConstants.WORKFLOW_INSTANCE_ID, workflowInstanceID); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Gram_Data gramData = (Gram_Data)result; GramDataResource gramDataResource = (GramDataResource)Utils.getResource(ResourceType.GRAM_DATA, gramData); resourceList.add(gramDataResource); } } break; case EXECUTION_ERROR: generator = new QueryGenerator(EXECUTION_ERROR); generator.setParameter(ExecutionErrorConstants.WORKFLOW_ID, workflowInstanceID); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Execution_Error executionError = (Execution_Error)result; ExecutionErrorResource executionErrorResource = (ExecutionErrorResource)Utils.getResource(ResourceType.EXECUTION_ERROR, executionError); resourceList.add(executionErrorResource); } } break; case GFAC_JOB_DATA: generator = new QueryGenerator(GFAC_JOB_DATA); generator.setParameter(GFacJobDataConstants.EXPERIMENT_ID, experimentID); generator.setParameter(GFacJobDataConstants.WORKFLOW_INSTANCE_ID, workflowInstanceID); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { GFac_Job_Data gFac_job_data = (GFac_Job_Data)result; GFacJobDataResource gFacJobDataResource = (GFacJobDataResource)Utils.getResource(ResourceType.GFAC_JOB_DATA, gFac_job_data); resourceList.add(gFacJobDataResource); } } break; default: em.getTransaction().commit(); em.close(); logger.error("Unsupported resource type for workflow data resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for workflow data resource."); } em.getTransaction().commit(); em.close(); return resourceList; } public List<Resource> getGFacJobs(){ return get(ResourceType.GFAC_JOB_DATA); } public void save() { if(lastUpdatedTime == null){ java.util.Date date= new java.util.Date(); lastUpdatedTime = new Timestamp(date.getTime()); } EntityManager em = ResourceUtils.getEntityManager(); Workflow_Data existingWFData = em.find(Workflow_Data.class, workflowInstanceID); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Workflow_Data workflowData = new Workflow_Data(); Experiment_Data expData = em.find(Experiment_Data.class, experimentID); workflowData.setExperiment_data(expData); workflowData.setWorkflow_instanceID(workflowInstanceID); workflowData.setLast_update_time(lastUpdatedTime); workflowData.setStart_time(startTime); workflowData.setTemplate_name(templateName); workflowData.setStatus(status); if(existingWFData != null){ existingWFData.setExperiment_data(expData); existingWFData.setLast_update_time(lastUpdatedTime); existingWFData.setStart_time(startTime); existingWFData.setStatus(status); existingWFData.setTemplate_name(templateName); workflowData = em.merge(existingWFData); }else { em.persist(workflowData); } em.getTransaction().commit(); em.close(); } public boolean isNodeExists(String nodeId){ return isExists(ResourceType.NODE_DATA, nodeId); } public boolean isGramDataExists(String nodeId){ return isExists(ResourceType.GRAM_DATA, nodeId); } public NodeDataResource getNodeData(String nodeId){ return (NodeDataResource) get(ResourceType.NODE_DATA,nodeId); } public GramDataResource getGramData(String nodeId){ return (GramDataResource) get(ResourceType.GRAM_DATA,nodeId); } public List<NodeDataResource> getNodeData(){ return getResourceList(get(ResourceType.NODE_DATA),NodeDataResource.class); } public List<GramDataResource> getGramData(){ return getResourceList(get(ResourceType.GRAM_DATA),GramDataResource.class); } public NodeDataResource createNodeData(String nodeId){ NodeDataResource data=(NodeDataResource)create(ResourceType.NODE_DATA); data.setNodeID(nodeId); return data; } public GramDataResource createGramData(String nodeId){ GramDataResource data=(GramDataResource)create(ResourceType.GRAM_DATA); data.setNodeID(nodeId); return data; } public void removeNodeData(String nodeId){ remove(ResourceType.NODE_DATA, nodeId); } public void removeGramData(String nodeId){ remove(ResourceType.GRAM_DATA, nodeId); } }
9,434
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/GatewayResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.*; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GatewayResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(GatewayResource.class); private String gatewayName; private String owner; /** * * @param gatewayName gateway name */ public GatewayResource(String gatewayName) { setGatewayName(gatewayName); } /** * */ public GatewayResource() { } /** * * @return gateway name */ public String getGatewayName() { return gatewayName; } /** * * @param gatewayName */ public void setGatewayName(String gatewayName) { this.gatewayName = gatewayName; } /** * * @return owner of the gateway */ public String getOwner() { return owner; } /** * * @param owner owner of the gateway */ public void setOwner(String owner) { this.owner = owner; } /** * Gateway is at the root level. So it can populate his child resources. * Project, User, Published Workflows, User workflows, Host descriptors, * Service Descriptors, Application descriptors and Experiments are all * its children * @param type resource type of the children * @return specific child resource type */ public Resource create(ResourceType type) { switch (type) { case PROJECT: ProjectResource projectResource = new ProjectResource(); projectResource.setGateway(this); return projectResource; case USER: UserResource userResource = new UserResource(); userResource.setGatewayName(this.getGatewayName()); return userResource; case PUBLISHED_WORKFLOW: PublishWorkflowResource publishWorkflowResource = new PublishWorkflowResource(); publishWorkflowResource.setGateway(this); return publishWorkflowResource; case USER_WORKFLOW: UserWorkflowResource userWorkflowResource = new UserWorkflowResource(); userWorkflowResource.setGateway(this); return userWorkflowResource; case HOST_DESCRIPTOR: HostDescriptorResource hostDescriptorResource = new HostDescriptorResource(); hostDescriptorResource.setGatewayName(gatewayName); return hostDescriptorResource; case SERVICE_DESCRIPTOR: ServiceDescriptorResource serviceDescriptorResource = new ServiceDescriptorResource(); serviceDescriptorResource.setGatewayName(gatewayName); return serviceDescriptorResource; case APPLICATION_DESCRIPTOR: ApplicationDescriptorResource applicationDescriptorResource = new ApplicationDescriptorResource(); applicationDescriptorResource.setGatewayName(gatewayName); return applicationDescriptorResource; case EXPERIMENT: ExperimentResource experimentResource =new ExperimentResource(); experimentResource.setGateway(this); return experimentResource; case GATEWAY_WORKER: WorkerResource workerResource = new WorkerResource(); workerResource.setGateway(this); return workerResource; default: logger.error("Unsupported resource type for gateway resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for gateway resource."); } } /** * Child resources can be removed from a gateway * @param type child resource type * @param name child resource name */ public void remove(ResourceType type, Object name) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Query q; QueryGenerator generator; switch (type){ case USER: generator = new QueryGenerator(USERS); generator.setParameter(UserConstants.USERNAME, name); q = generator.deleteQuery(em); q.executeUpdate(); break; case PUBLISHED_WORKFLOW: generator = new QueryGenerator(PUBLISHED_WORKFLOW); generator.setParameter(PublishedWorkflowConstants.PUBLISH_WORKFLOW_NAME, name); generator.setParameter(PublishedWorkflowConstants.GATEWAY_NAME, gatewayName); q = generator.deleteQuery(em); q.executeUpdate(); break; case HOST_DESCRIPTOR: generator = new QueryGenerator(HOST_DESCRIPTOR); generator.setParameter(HostDescriptorConstants.HOST_DESC_ID, name); generator.setParameter(HostDescriptorConstants.GATEWAY_NAME, gatewayName); q = generator.deleteQuery(em); q.executeUpdate(); break; case SERVICE_DESCRIPTOR: generator = new QueryGenerator(SERVICE_DESCRIPTOR); generator.setParameter(ServiceDescriptorConstants.SERVICE_DESC_ID, name); generator.setParameter(ServiceDescriptorConstants.GATEWAY_NAME, gatewayName); q = generator.deleteQuery(em); q.executeUpdate(); break; case EXPERIMENT: generator = new QueryGenerator(EXPERIMENT); generator.setParameter(ExperimentConstants.EXPERIMENT_ID, name); generator.setParameter(ExperimentConstants.GATEWAY_NAME, gatewayName); q = generator.deleteQuery(em); q.executeUpdate(); break; case APPLICATION_DESCRIPTOR: generator = new QueryGenerator(APPLICATION_DESCRIPTOR); generator.setParameter(ApplicationDescriptorConstants.APPLICATION_DESC_ID, name); generator.setParameter(ApplicationDescriptorConstants.GATEWAY_NAME, gatewayName); q = generator.deleteQuery(em); q.executeUpdate(); break; default: logger.error("Unsupported resource type for gateway resource.", new IllegalArgumentException()); break; } em.getTransaction().commit(); em.close(); } /** * Gateway can get information of his children * @param type child resource type * @param name child resource name * @return specific child resource type */ public Resource get(ResourceType type, Object name) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator; Query q; switch (type) { case USER: generator = new QueryGenerator(GATEWAY_WORKER); generator.setParameter(GatewayWorkerConstants.USERNAME, name); generator.setParameter(GatewayWorkerConstants.GATEWAY_NAME, gatewayName); q = generator.selectQuery(em); Gateway_Worker worker = (Gateway_Worker) q.getSingleResult(); WorkerResource workerResource = (WorkerResource)Utils.getResource(ResourceType.GATEWAY_WORKER, worker); em.getTransaction().commit(); em.close(); return workerResource; case PUBLISHED_WORKFLOW: generator = new QueryGenerator(PUBLISHED_WORKFLOW); generator.setParameter(PublishedWorkflowConstants.PUBLISH_WORKFLOW_NAME, name); generator.setParameter(PublishedWorkflowConstants.GATEWAY_NAME, gatewayName); q = generator.selectQuery(em); Published_Workflow ePub_workflow = (Published_Workflow) q.getSingleResult(); PublishWorkflowResource publishWorkflowResource = (PublishWorkflowResource)Utils.getResource(ResourceType.PUBLISHED_WORKFLOW, ePub_workflow); em.getTransaction().commit(); em.close(); return publishWorkflowResource; case HOST_DESCRIPTOR: generator = new QueryGenerator(HOST_DESCRIPTOR); generator.setParameter(HostDescriptorConstants.HOST_DESC_ID, name); generator.setParameter(HostDescriptorConstants.GATEWAY_NAME, gatewayName); q = generator.selectQuery(em); Host_Descriptor eHostDesc = (Host_Descriptor) q.getSingleResult(); HostDescriptorResource hostDescriptorResource = (HostDescriptorResource)Utils.getResource(ResourceType.HOST_DESCRIPTOR, eHostDesc); em.getTransaction().commit(); em.close(); return hostDescriptorResource; case EXPERIMENT: generator = new QueryGenerator(EXPERIMENT); generator.setParameter(ExperimentConstants.EXPERIMENT_ID, name); generator.setParameter(ExperimentConstants.GATEWAY_NAME, gatewayName); q = generator.selectQuery(em); Experiment experiment = (Experiment)q.getSingleResult(); ExperimentResource experimentResource = (ExperimentResource)Utils.getResource(ResourceType.EXPERIMENT, experiment); em.getTransaction().commit(); em.close(); return experimentResource; case SERVICE_DESCRIPTOR: generator = new QueryGenerator(SERVICE_DESCRIPTOR); generator.setParameter(ServiceDescriptorConstants.SERVICE_DESC_ID, name); generator.setParameter(ServiceDescriptorConstants.GATEWAY_NAME, gatewayName); q = generator.selectQuery(em); Service_Descriptor eServiceDesc = (Service_Descriptor) q.getSingleResult(); ServiceDescriptorResource serviceDescriptorResource = (ServiceDescriptorResource)Utils.getResource(ResourceType.SERVICE_DESCRIPTOR, eServiceDesc); em.getTransaction().commit(); em.close(); return serviceDescriptorResource; case APPLICATION_DESCRIPTOR: generator = new QueryGenerator(APPLICATION_DESCRIPTOR); generator.setParameter(ApplicationDescriptorConstants.APPLICATION_DESC_ID, name); generator.setParameter(ApplicationDescriptorConstants.GATEWAY_NAME, gatewayName); q = generator.selectQuery(em); Application_Descriptor eAppDesc = (Application_Descriptor) q.getSingleResult(); ApplicationDescriptorResource applicationDescriptorResource = (ApplicationDescriptorResource)Utils.getResource(ResourceType.APPLICATION_DESCRIPTOR, eAppDesc); em.getTransaction().commit(); em.close(); return applicationDescriptorResource; default: em.getTransaction().commit(); em.close(); logger.error("Unsupported resource type for gateway resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for gateway resource."); } } /** * * @param type child resource type * @return list of child resources */ public List<Resource> get(ResourceType type) { List<Resource> resourceList = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Query q; QueryGenerator generator; List results; switch (type){ case PROJECT: generator = new QueryGenerator(PROJECT); Gateway gatewayModel = em.find(Gateway.class, gatewayName); generator.setParameter("gateway", gatewayModel); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Project project = (Project) result; ProjectResource projectResource = (ProjectResource)Utils.getResource(ResourceType.PROJECT, project); resourceList.add(projectResource); } } break; case GATEWAY_WORKER: generator = new QueryGenerator(GATEWAY_WORKER); generator.setParameter(GatewayWorkerConstants.GATEWAY_NAME, gatewayName); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Gateway_Worker gatewayWorker = (Gateway_Worker) result; WorkerResource workerResource = (WorkerResource)Utils.getResource(ResourceType.GATEWAY_WORKER, gatewayWorker); resourceList.add(workerResource); } } break; case PUBLISHED_WORKFLOW : generator = new QueryGenerator(PUBLISHED_WORKFLOW); generator.setParameter(PublishedWorkflowConstants.GATEWAY_NAME, gatewayName); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Published_Workflow publishedWorkflow = (Published_Workflow) result; PublishWorkflowResource publishWorkflowResource = (PublishWorkflowResource)Utils.getResource(ResourceType.PUBLISHED_WORKFLOW, publishedWorkflow); resourceList.add(publishWorkflowResource); } } break; case HOST_DESCRIPTOR: generator = new QueryGenerator(HOST_DESCRIPTOR); generator.setParameter(HostDescriptorConstants.GATEWAY_NAME, gatewayName); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Host_Descriptor hostDescriptor = (Host_Descriptor) result; HostDescriptorResource hostDescriptorResource = (HostDescriptorResource)Utils.getResource(ResourceType.HOST_DESCRIPTOR, hostDescriptor); resourceList.add(hostDescriptorResource); } } break; case SERVICE_DESCRIPTOR: generator = new QueryGenerator(SERVICE_DESCRIPTOR); generator.setParameter(ServiceDescriptorConstants.GATEWAY_NAME, gatewayName); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Service_Descriptor serviceDescriptor = (Service_Descriptor) result; ServiceDescriptorResource serviceDescriptorResource = (ServiceDescriptorResource)Utils.getResource(ResourceType.SERVICE_DESCRIPTOR, serviceDescriptor); resourceList.add(serviceDescriptorResource); } } break; case APPLICATION_DESCRIPTOR: generator = new QueryGenerator(APPLICATION_DESCRIPTOR); generator.setParameter(ApplicationDescriptorConstants.GATEWAY_NAME, gatewayName); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Application_Descriptor applicationDescriptor = (Application_Descriptor) result; ApplicationDescriptorResource applicationDescriptorResource = (ApplicationDescriptorResource)Utils.getResource(ResourceType.APPLICATION_DESCRIPTOR, applicationDescriptor); resourceList.add(applicationDescriptorResource); } } break; case EXPERIMENT: generator = new QueryGenerator(EXPERIMENT); generator.setParameter(ExperimentConstants.GATEWAY_NAME, gatewayName); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Experiment experiment = (Experiment) result; ExperimentResource experimentResource = (ExperimentResource)Utils.getResource(ResourceType.EXPERIMENT, experiment); resourceList.add(experimentResource); } } break; case USER: generator = new QueryGenerator(USERS); q = generator.selectQuery(em); for (Object o : q.getResultList()) { Users user = (Users) o; UserResource userResource = (UserResource)Utils.getResource(ResourceType.USER, user); resourceList.add(userResource); } break; default: em.getTransaction().commit(); em.close(); logger.error("Unsupported resource type for gateway resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for gateway resource."); } em.getTransaction().commit(); em.close(); return resourceList; } /** * save the gateway to the database */ public void save() { EntityManager em = ResourceUtils.getEntityManager(); Gateway existingGateway = em.find(Gateway.class, gatewayName); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Gateway gateway = new Gateway(); gateway.setGateway_name(gatewayName); gateway.setOwner(owner); if (existingGateway != null) { existingGateway.setOwner(owner); gateway = em.merge(existingGateway); } else { em.persist(gateway); } em.getTransaction().commit(); em.close(); } /** * check whether child resource already exist in the database * @param type child resource type * @param name name of the child resource * @return true or false */ public boolean isExists(ResourceType type, Object name) { EntityManager em; Query q; Number count; switch (type){ case USER: em = ResourceUtils.getEntityManager(); Gateway_Worker existingWorker = em.find(Gateway_Worker.class, new Gateway_Worker_PK(gatewayName, name.toString())); em.close(); return existingWorker!= null; case PUBLISHED_WORKFLOW: em = ResourceUtils.getEntityManager(); Published_Workflow existingWf = em.find(Published_Workflow.class, new Published_Workflow_PK(gatewayName, name.toString())); em.close(); boolean a = existingWf != null; return existingWf != null; case HOST_DESCRIPTOR: em = ResourceUtils.getEntityManager(); Host_Descriptor existingHostDesc = em.find(Host_Descriptor.class, new Host_Descriptor_PK(gatewayName, name.toString())); em.close(); return existingHostDesc != null; case SERVICE_DESCRIPTOR: em = ResourceUtils.getEntityManager(); Service_Descriptor existingServiceDesc = em.find(Service_Descriptor.class, new Service_Descriptor_PK(gatewayName, name.toString())); em.close(); return existingServiceDesc != null; case APPLICATION_DESCRIPTOR: em = ResourceUtils.getEntityManager(); Application_Descriptor existingAppDesc = em.find(Application_Descriptor.class, new Application_Descriptor_PK(gatewayName, name.toString())); em.close(); return existingAppDesc != null; case EXPERIMENT: em = ResourceUtils.getEntityManager(); Experiment existingExp = em.find(Experiment.class, name.toString()); em.close(); return existingExp != null; default: logger.error("Unsupported resource type for gateway resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for gateway resource."); } } /** * * @param descriptorName host descriptor name * @return whether host descriptor already available */ public boolean isHostDescriptorExists(String descriptorName){ return isExists(ResourceType.HOST_DESCRIPTOR, descriptorName); } /** * * @param hostDescriptorName host descriptor name * @return HostDescriptorResource */ public HostDescriptorResource createHostDescriptorResource(String hostDescriptorName){ HostDescriptorResource hdr = (HostDescriptorResource)create(ResourceType.HOST_DESCRIPTOR); hdr.setHostDescName(hostDescriptorName); return hdr; } /** * * @param hostDescriptorName host descriptor name * @return HostDescriptorResource */ public HostDescriptorResource getHostDescriptorResource(String hostDescriptorName){ return (HostDescriptorResource)get(ResourceType.HOST_DESCRIPTOR,hostDescriptorName); } /** * * @param descriptorName host descriptor name */ public void removeHostDescriptor(String descriptorName){ remove(ResourceType.HOST_DESCRIPTOR, descriptorName); } /** * * @return list of host descriptors available for the gateway */ public List<HostDescriptorResource> getHostDescriptorResources(){ List<HostDescriptorResource> results=new ArrayList<HostDescriptorResource>(); List<Resource> list = get(ResourceType.HOST_DESCRIPTOR); for (Resource resource : list) { results.add((HostDescriptorResource) resource); } return results; } /** * * @param descriptorName service descriptor name * @return whether service descriptor already available */ public boolean isServiceDescriptorExists(String descriptorName){ return isExists(ResourceType.SERVICE_DESCRIPTOR, descriptorName); } /** * * @param descriptorName service descriptor name * @return ServiceDescriptorResource */ public ServiceDescriptorResource createServiceDescriptorResource(String descriptorName){ ServiceDescriptorResource hdr = (ServiceDescriptorResource)create(ResourceType.SERVICE_DESCRIPTOR); hdr.setServiceDescName(descriptorName); return hdr; } /** * * @param descriptorName service descriptor name * @return ServiceDescriptorResource */ public ServiceDescriptorResource getServiceDescriptorResource(String descriptorName){ return (ServiceDescriptorResource)get(ResourceType.SERVICE_DESCRIPTOR,descriptorName); } /** * * @param descriptorName Service descriptor name */ public void removeServiceDescriptor(String descriptorName){ remove(ResourceType.SERVICE_DESCRIPTOR, descriptorName); } /** * * @return list of service descriptors for the gateway */ public List<ServiceDescriptorResource> getServiceDescriptorResources(){ List<ServiceDescriptorResource> results=new ArrayList<ServiceDescriptorResource>(); List<Resource> list = get(ResourceType.SERVICE_DESCRIPTOR); for (Resource resource : list) { results.add((ServiceDescriptorResource) resource); } return results; } /** * * @param descriptorName application descriptor name * @return whether application descriptor already available */ public boolean isApplicationDescriptorExists(String descriptorName){ return isExists(ResourceType.APPLICATION_DESCRIPTOR, descriptorName); } /** * * @param descriptorName application descriptor name * @return ApplicationDescriptorResource */ public ApplicationDescriptorResource createApplicationDescriptorResource(String descriptorName){ ApplicationDescriptorResource hdr = (ApplicationDescriptorResource)create(ResourceType.APPLICATION_DESCRIPTOR); hdr.setName(descriptorName); return hdr; } /** * * @param descriptorName application descriptor name * @return ApplicationDescriptorResource */ public ApplicationDescriptorResource getApplicationDescriptorResource(String descriptorName){ return (ApplicationDescriptorResource)get(ResourceType.APPLICATION_DESCRIPTOR,descriptorName); } /** * * @param descriptorName application descriptor name */ public void removeApplicationDescriptor(String descriptorName){ remove(ResourceType.APPLICATION_DESCRIPTOR, descriptorName); } /** * * @return list of application descriptors for the gateway */ public List<ApplicationDescriptorResource> getApplicationDescriptorResources(){ List<ApplicationDescriptorResource> results=new ArrayList<ApplicationDescriptorResource>(); List<Resource> list = get(ResourceType.APPLICATION_DESCRIPTOR); for (Resource resource : list) { results.add((ApplicationDescriptorResource) resource); } return results; } /** * * @param serviceName service descriptor name * @param hostName host descriptor name * @return list of application descriptors for the gateway */ public List<ApplicationDescriptorResource> getApplicationDescriptorResources(String serviceName,String hostName){ EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); String qString = "SELECT p FROM Application_Descriptor p WHERE " + "p.gateway_name =:gate_name"; if (hostName!=null){ qString+=" and p.host_descriptor_ID =:host_name"; } if (serviceName!=null){ qString+=" and p.service_descriptor_ID =:service_name"; } Query q = em.createQuery(qString); q.setParameter("gate_name", gatewayName); if (serviceName!=null){ q.setParameter("service_name", serviceName); } if (hostName!=null){ q.setParameter("host_name",hostName); } List<?> results = q.getResultList(); List<ApplicationDescriptorResource> resourceList = new ArrayList<ApplicationDescriptorResource>(); if (results.size() != 0) { for (Object result : results) { Application_Descriptor applicationDescriptor = (Application_Descriptor) result; ApplicationDescriptorResource applicationDescriptorResource = new ApplicationDescriptorResource( applicationDescriptor.getApplication_descriptor_ID(), applicationDescriptor.getGateway().getGateway_name()); applicationDescriptorResource.setContent(new String(applicationDescriptor.getApplication_descriptor_xml())); applicationDescriptorResource.setUpdatedUser(applicationDescriptor.getUser().getUser_name()); applicationDescriptorResource.setHostDescName(applicationDescriptor.getHost_descriptor_ID()); applicationDescriptorResource.setServiceDescName(applicationDescriptor.getService_descriptor_ID()); resourceList.add(applicationDescriptorResource); } } em.getTransaction().commit(); em.close(); return resourceList; } /** * * @param workflowTemplateName published workflow template name * @return boolean - whether workflow with the same name exists */ public boolean isPublishedWorkflowExists(String workflowTemplateName){ return isExists(ResourceType.PUBLISHED_WORKFLOW, workflowTemplateName); } /** * * @param workflowTemplateName published workflow template name * @return publish workflow resource */ public PublishWorkflowResource createPublishedWorkflow(String workflowTemplateName){ PublishWorkflowResource publishedWorkflowResource = (PublishWorkflowResource)create(ResourceType.PUBLISHED_WORKFLOW); publishedWorkflowResource.setName(workflowTemplateName); publishedWorkflowResource.setPath("/"); publishedWorkflowResource.setVersion("1.0"); return publishedWorkflowResource; } /** * * @param workflowTemplateName published workflow template name * @return publish workflow resource */ public PublishWorkflowResource getPublishedWorkflow(String workflowTemplateName){ return (PublishWorkflowResource)get(ResourceType.PUBLISHED_WORKFLOW,workflowTemplateName); } /** * * @return list of publish workflows for the gateway */ public List<PublishWorkflowResource> getPublishedWorkflows(){ List<PublishWorkflowResource> result=new ArrayList<PublishWorkflowResource>(); List<Resource> list = get(ResourceType.PUBLISHED_WORKFLOW); for (Resource resource : list) { result.add((PublishWorkflowResource) resource); } return result; } /** * * @param workflowTemplateName published workflow template name */ public void removePublishedWorkflow(String workflowTemplateName){ remove(ResourceType.PUBLISHED_WORKFLOW, workflowTemplateName); } }
9,435
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/ConfigurationResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Lock; import javax.persistence.EntityManager; import javax.persistence.Query; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.Configuration; import org.apache.airavata.persistance.registry.jpa.model.Configuration_PK; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ConfigurationResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(ConfigurationResource.class); private String configKey; private String configVal; private Timestamp expireDate; private String categoryID = ConfigurationConstants.CATEGORY_ID_DEFAULT_VALUE; public ConfigurationResource() { } /** * * @param configKey configuration key * @param configVal configuration value */ public ConfigurationResource(String configKey, String configVal) { this.configKey = configKey; this.configVal = configVal; } /** * Since Configuration does not depend on any other data structures at the * system, this method is not valid * @param type child resource types * @return UnsupportedOperationException */ public Resource create(ResourceType type) { logger.error("Unsupported operation for configuration resource " + "since there are no child resources generated by configuration resource.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * Since Configuration does not depend on any other data structures at the * system, this method is not valid * @param type child resource types * @param name name of the child resource * throws UnsupportedOperationException */ public void remove(ResourceType type, Object name) { logger.error("Unsupported operation for configuration resource " + "since there are no child resources generated by configuration resource.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * Since Configuration does not depend on any other data structures at the * system, this method is not valid * @param type child resource types * @param name name of the child resource * @return UnsupportedOperationException */ public Resource get(ResourceType type, Object name) { logger.error("Unsupported operation for configuration resource " + "since there are no child resources generated by configuration resource.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * key should be the configuration name * @param keys names * @return list of ConfigurationResources */ public List<Resource> populate(Object[] keys) { List<Resource> list = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator queryGenerator = new QueryGenerator(CONFIGURATION); queryGenerator.setParameter(ConfigurationConstants.CONFIG_KEY, keys[0]); Query q = queryGenerator.selectQuery(em); List resultList = q.getResultList(); if (resultList.size() != 0) { for (Object result : resultList) { Configuration configuration = (Configuration) result; ConfigurationResource configurationResource = (ConfigurationResource)Utils.getResource(ResourceType.CONFIGURATION, configuration); list.add(configurationResource); } } em.getTransaction().commit(); em.close(); return list; } /** * * Since Configuration does not depend on any other data structures at the * system, this method is not valid * @param type child resource types * @return UnsupportedOperationException */ public List<Resource> get(ResourceType type) { logger.error("Unsupported operation for configuration resource " + "since there are no child resources generated by configuration resource.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * * @param expireDate expire date of the configuration */ public void setExpireDate(Timestamp expireDate) { this.expireDate = expireDate; } /** * save configuration to database */ public synchronized void save() { Lock lock = ResourceUtils.getLock(); lock.lock(); try { EntityManager em = ResourceUtils.getEntityManager(); //whether existing Configuration existing = em.find(Configuration.class, new Configuration_PK(configKey, configVal, categoryID)); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Configuration configuration = new Configuration(); configuration.setConfig_key(configKey); configuration.setConfig_val(configVal); configuration.setExpire_date(expireDate); configuration.setCategory_id(categoryID); if (existing != null) { existing.setExpire_date(expireDate); existing.setCategory_id(categoryID); configuration = em.merge(existing); } else { em.merge(configuration); } em.getTransaction().commit(); em.close(); } finally { lock.unlock(); } } /** * Since Configuration does not depend on any other data structures at the * system, this method is not valid * @param type child resource types * @param name of the child resource * @return UnsupportedOperationException */ public boolean isExists(ResourceType type, Object name) { logger.error("Unsupported operation for configuration resource " + "since there are no child resources generated by configuration resource.. ", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * * @return configuration value */ public String getConfigVal() { return configVal; } /** * * @param configKey configuration key */ public void setConfigKey(String configKey) { this.configKey = configKey; } /** * * @param configVal configuration value */ public void setConfigVal(String configVal) { this.configVal = configVal; } public String getCategoryID() { return categoryID; } public void setCategoryID(String categoryID) { this.categoryID = categoryID; } }
9,436
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/ExperimentDataRetriever.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.registry.api.exception.worker.ExperimentLazyLoadedException; import org.apache.airavata.registry.api.impl.ExperimentDataImpl; import org.apache.airavata.registry.api.impl.WorkflowExecutionDataImpl; import org.apache.airavata.registry.api.workflow.*; import org.apache.airavata.registry.api.workflow.WorkflowExecutionStatus.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.*; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.Date; public class ExperimentDataRetriever { private static final Logger logger = LoggerFactory.getLogger(ExperimentDataRetriever.class); public ExperimentData getExperiment(String experimentId){ String connectionURL = Utils.getJDBCURL(); Connection connection = null; ResultSet rs = null; Statement statement; List<WorkflowExecution> experimentWorkflowInstances = new ArrayList<WorkflowExecution>(); ExperimentData experimentData = null; try { Class.forName(Utils.getJDBCDriver()).newInstance(); connection = DriverManager.getConnection(connectionURL, Utils.getJDBCUser(), Utils.getJDBCPassword()); statement = connection.createStatement(); String queryString = "SELECT e.experiment_ID, ed.name, ed.username, em.metadata, " + "wd.workflow_instanceID, wd.template_name, wd.status, wd.start_time," + "wd.last_update_time, nd.node_id, nd.inputs, nd.outputs, " + "e.project_name, e.submitted_date, nd.node_type, nd.status," + "nd.start_time, nd.last_update_time " + "FROM Experiment e " + "LEFT JOIN Experiment_Data ed " + "ON e.experiment_ID = ed.experiment_ID " + "LEFT JOIN Experiment_Metadata em " + "ON ed.experiment_ID = em.experiment_ID " + "LEFT JOIN Workflow_Data wd " + "ON e.experiment_ID = wd.experiment_ID " + "LEFT JOIN Node_Data nd " + "ON wd.workflow_instanceID = nd.workflow_instanceID " + "WHERE e.experiment_ID ='" + experimentId + "'"; rs = statement.executeQuery(queryString); if (rs != null){ while (rs.next()) { if(experimentData == null){ experimentData = new ExperimentDataImpl(); experimentData.setExperimentId(rs.getString(1)); experimentData.setExperimentName(rs.getString(2)); experimentData.setUser(rs.getString(3)); experimentData.setMetadata(rs.getString(4)); experimentData.setTopic(rs.getString(1)); } fillWorkflowInstanceData(experimentData, rs, experimentWorkflowInstances); } } if(rs != null){ rs.close(); } statement.close(); connection.close(); } catch (InstantiationException e) { logger.error(e.getMessage(), e); } catch (IllegalAccessException e) { logger.error(e.getMessage(), e); } catch (ClassNotFoundException e) { logger.error(e.getMessage(), e); } catch (SQLException e){ logger.error(e.getMessage()); }catch (ParseException e) { logger.error(e.getMessage(), e); } catch (ExperimentLazyLoadedException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return experimentData; } private void fillWorkflowInstanceData (ExperimentData experimentData, ResultSet rs, List<WorkflowExecution> workflowInstances) throws SQLException, ExperimentLazyLoadedException, ParseException { WorkflowExecutionDataImpl workflowInstanceData = (WorkflowExecutionDataImpl)experimentData.getWorkflowExecutionData(rs.getString(5)); if (workflowInstanceData == null){ WorkflowExecution workflowInstance = new WorkflowExecution(experimentData.getExperimentId(), rs.getString(5)); workflowInstance.setTemplateName(rs.getString(6)); workflowInstance.setExperimentId(rs.getString(1)); workflowInstance.setWorkflowExecutionId(rs.getString(5)); workflowInstances.add(workflowInstance); Date lastUpdateDate = getTime(rs.getString(9)); String wdStatus = rs.getString(7); WorkflowExecutionStatus workflowExecutionStatus = new WorkflowExecutionStatus(workflowInstance, createExecutionStatus(wdStatus),lastUpdateDate); workflowInstanceData = new WorkflowExecutionDataImpl(null, workflowInstance, workflowExecutionStatus, null); ExperimentDataImpl expData = (ExperimentDataImpl) experimentData; workflowInstanceData.setExperimentData(expData); // Set the last updated workflow's status and time as the experiment's status if(expData.getExecutionStatus()!=null) { if(expData.getExecutionStatus().getStatusUpdateTime().compareTo(workflowExecutionStatus.getStatusUpdateTime())<0) { expData.setExecutionStatus(workflowExecutionStatus); } } else { expData.setExecutionStatus(workflowExecutionStatus); } experimentData.getWorkflowExecutionDataList().add(workflowInstanceData); } WorkflowInstanceNode workflowInstanceNode = new WorkflowInstanceNode(workflowInstanceData.getWorkflowExecution(), rs.getString(10)); NodeExecutionData workflowInstanceNodeData = new NodeExecutionData(workflowInstanceNode); String inputData = getStringValue(11, rs); String outputData = getStringValue(12, rs); workflowInstanceNodeData.setInput(inputData); workflowInstanceNodeData.setOutput(outputData); workflowInstanceNodeData.setStatus(createExecutionStatus(rs.getString(16)), getTime(rs.getString(18))); workflowInstanceNodeData.setType(WorkflowNodeType.getType(rs.getString(15)).getNodeType()); workflowInstanceData.getNodeDataList().add(workflowInstanceNodeData); } private State createExecutionStatus (String status){ return status == null ? State.UNKNOWN : State.valueOf(status); } private String getStringValue (int parameterNumber, ResultSet rs) throws SQLException { Blob input = rs.getBlob(parameterNumber); if (input != null){ byte[] inputBytes = input.getBytes(1, (int) input.length()); String inputData = new String(inputBytes); return inputData; } return null; } private Date getTime (String date) throws ParseException { if (date != null){ DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return dateFormat.parse(date); } return null; } public List<String> getExperimentIdByUser(String user){ List<String> result=new ArrayList<String>(); String connectionURL = Utils.getJDBCURL(); Connection connection = null; ResultSet rs = null; Statement statement = null; try { String jdbcDriver = Utils.getJDBCDriver(); Class.forName(jdbcDriver).newInstance(); connection = DriverManager.getConnection(connectionURL, Utils.getJDBCUser(), Utils.getJDBCPassword()); statement = connection.createStatement(); // FIXME : pass user ID as a regular expression String queryString = "SELECT ed.experiment_ID FROM Experiment_Data ed " + "LEFT JOIN Experiment e " + "ON ed.experiment_ID = e.experiment_ID " + "WHERE ed.username ='" + user + "'"; rs = statement.executeQuery(queryString); if(rs != null){ while (rs.next()) { result.add(rs.getString(1)); } } if(rs != null){ rs.close(); } statement.close(); connection.close(); } catch (InstantiationException e) { logger.error(e.getMessage(), e); } catch (IllegalAccessException e) { logger.error(e.getMessage(), e); } catch (ClassNotFoundException e) { logger.error(e.getMessage(), e); } catch (SQLException e){ logger.error(e.getMessage(), e); } return result; } public String getExperimentName(String experimentId){ String connectionURL = Utils.getJDBCURL(); Connection connection; Statement statement; ResultSet rs; try { Class.forName(Utils.getJDBCDriver()).newInstance(); connection = DriverManager.getConnection(connectionURL, Utils.getJDBCUser(), Utils.getJDBCPassword()); statement = connection.createStatement(); String queryString = "SELECT ed.name FROM Experiment e " + "LEFT JOIN Experiment_Data ed " + "ON e.experiment_ID = ed.experiment_ID " + "WHERE e.experiment_ID='" + experimentId + "'"; rs = statement.executeQuery(queryString); if(rs != null){ while (rs.next()) { return rs.getString(1); } } if(rs != null){ rs.close(); } statement.close(); connection.close(); } catch (InstantiationException e) { logger.error(e.getMessage(), e); } catch (IllegalAccessException e) { logger.error(e.getMessage(), e); } catch (ClassNotFoundException e) { logger.error(e.getMessage(), e); } catch (SQLException e){ logger.error(e.getMessage(), e); } return null; } public List<ExperimentData> getExperiments(String user) { String connectionURL = Utils.getJDBCURL(); Connection connection = null; ResultSet rs = null; Statement statement; Map<String, ExperimentData> experimentDataMap = new HashMap<String, ExperimentData>(); List<ExperimentData> experimentDataList = new ArrayList<ExperimentData>(); List<WorkflowExecution> experimentWorkflowInstances = new ArrayList<WorkflowExecution>(); try { Class.forName(Utils.getJDBCDriver()).newInstance(); connection = DriverManager.getConnection(connectionURL, Utils.getJDBCUser(), Utils.getJDBCPassword()); statement = connection.createStatement(); String queryString = "SELECT e.experiment_ID, ed.name, ed.username, em.metadata, " + "wd.workflow_instanceID, wd.template_name, wd.status, wd.start_time," + "wd.last_update_time, nd.node_id, nd.inputs, nd.outputs, " + "e.project_name, e.submitted_date, nd.node_type, nd.status," + "nd.start_time, nd.last_update_time" + " FROM Experiment e INNER JOIN Experiment_Data ed " + "ON e.experiment_ID = ed.experiment_ID " + "LEFT JOIN Experiment_Metadata em " + "ON ed.experiment_ID = em.experiment_ID " + "LEFT JOIN Workflow_Data wd " + "ON e.experiment_ID = wd.experiment_ID " + "LEFT JOIN Node_Data nd " + "ON wd.workflow_instanceID = nd.workflow_instanceID " + "WHERE ed.username='" + user + "'"; rs = statement.executeQuery(queryString); if (rs != null) { while (rs.next()) { ExperimentData experimentData = null; if (experimentDataMap.containsKey(rs.getString(1))) { experimentData = experimentDataMap.get(rs.getString(1)); }else{ experimentData = new ExperimentDataImpl(); experimentData.setExperimentId(rs.getString(1)); experimentData.setExperimentName(rs.getString(2)); experimentData.setUser(rs.getString(3)); experimentData.setMetadata(rs.getString(4)); experimentData.setTopic(rs.getString(1)); experimentDataMap.put(experimentData.getExperimentId(),experimentData); experimentDataList.add(experimentData); } fillWorkflowInstanceData(experimentData, rs, experimentWorkflowInstances); } } if (rs != null) { rs.close(); } statement.close(); connection.close(); } catch (InstantiationException e) { logger.error(e.getMessage(), e); } catch (IllegalAccessException e) { logger.error(e.getMessage(), e); } catch (ClassNotFoundException e) { logger.error(e.getMessage(), e); } catch (SQLException e) { logger.error(e.getMessage(), e); } catch (ExperimentLazyLoadedException e) { logger.error(e.getMessage(), e); } catch (ParseException e) { logger.error(e.getMessage(), e); } return experimentDataList; } public List<ExperimentData> getExperiments(HashMap<String, String> params) { String connectionURL = Utils.getJDBCURL(); Connection connection = null; ResultSet rs = null; Statement statement; Map<String, ExperimentData> experimentDataMap = new HashMap<String, ExperimentData>(); List<ExperimentData> experimentDataList = new ArrayList<ExperimentData>(); List<WorkflowExecution> experimentWorkflowInstances = new ArrayList<WorkflowExecution>(); try { Class.forName(Utils.getJDBCDriver()).newInstance(); connection = DriverManager.getConnection(connectionURL, Utils.getJDBCUser(), Utils.getJDBCPassword()); statement = connection.createStatement(); String queryString = "SELECT e.experiment_ID, ed.name, ed.username, em.metadata, " + "wd.workflow_instanceID, wd.template_name, wd.status, wd.start_time," + "wd.last_update_time, nd.node_id, nd.inputs, nd.outputs, " + "e.project_name, e.submitted_date, nd.node_type, nd.status," + "nd.start_time, nd.last_update_time" + " FROM Experiment e INNER JOIN Experiment_Data ed " + "ON e.experiment_ID = ed.experiment_ID " + "LEFT JOIN Experiment_Metadata em " + "ON ed.experiment_ID = em.experiment_ID " + "LEFT JOIN Workflow_Data wd " + "ON e.experiment_ID = wd.experiment_ID " + "LEFT JOIN Node_Data nd " + "ON wd.workflow_instanceID = nd.workflow_instanceID "; DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if(params.keySet().size()>0) { queryString += "WHERE "; String username = params.get("username"); String from = params.get("fromDate"); String to = params.get("toDate"); if(username!=null && !username.isEmpty()) { queryString += "ed.username='" + username + "'"; if((from!=null && !from.isEmpty()) || (to!=null && !to.isEmpty())) { queryString += " AND "; } } if(from!=null && !from.isEmpty()) { Date fromDate = dateFormat.parse(from); Timestamp fromTime = new Timestamp(fromDate.getTime()); queryString += "e.submitted_date>='" + fromTime + "'"; if(to!=null && to!="") { queryString += " AND "; } } if(to!=null && !to.isEmpty()) { Date toDate = dateFormat.parse(to); Timestamp toTime = new Timestamp(toDate.getTime()); queryString += "e.submitted_date<='" + toTime + "'"; } } rs = statement.executeQuery(queryString); if (rs != null) { while (rs.next()) { ExperimentData experimentData = null; if (experimentDataMap.containsKey(rs.getString(1))) { experimentData = experimentDataMap.get(rs.getString(1)); }else{ experimentData = new ExperimentDataImpl(); experimentData.setExperimentId(rs.getString(1)); experimentData.setExperimentName(rs.getString(2)); experimentData.setUser(rs.getString(3)); experimentData.setMetadata(rs.getString(4)); experimentData.setTopic(rs.getString(1)); experimentDataMap.put(experimentData.getExperimentId(),experimentData); experimentDataList.add(experimentData); } fillWorkflowInstanceData(experimentData, rs, experimentWorkflowInstances); } } if (rs != null) { rs.close(); } statement.close(); connection.close(); } catch (InstantiationException e) { logger.error(e.getMessage(), e); } catch (IllegalAccessException e) { logger.error(e.getMessage(), e); } catch (ClassNotFoundException e) { logger.error(e.getMessage(), e); } catch (SQLException e) { logger.error(e.getMessage(), e); } catch (ExperimentLazyLoadedException e) { logger.error(e.getMessage(), e); } catch (ParseException e) { logger.error(e.getMessage(), e); } return experimentDataList; } public ExperimentData getExperimentMetaInformation(String experimentId){ String connectionURL = Utils.getJDBCURL(); Connection connection = null; ResultSet rs = null; Statement statement; List<WorkflowExecution> experimentWorkflowInstances = new ArrayList<WorkflowExecution>(); ExperimentData experimentData = null; try { Class.forName(Utils.getJDBCDriver()).newInstance(); connection = DriverManager.getConnection(connectionURL, Utils.getJDBCUser(), Utils.getJDBCPassword()); statement = connection.createStatement(); String queryString = "SELECT e.experiment_ID, ed.name, ed.username, em.metadata, " + "e.project_name, e.submitted_date " + "FROM Experiment e " + "LEFT JOIN Experiment_Data ed " + "ON e.experiment_ID = ed.experiment_ID " + "LEFT JOIN Experiment_Metadata em " + "ON ed.experiment_ID = em.experiment_ID " + "WHERE e.experiment_ID ='" + experimentId + "'"; rs = statement.executeQuery(queryString); if (rs != null){ while (rs.next()) { experimentData = new ExperimentDataImpl(true); experimentData.setExperimentId(rs.getString(1)); experimentData.setExperimentName(rs.getString(2)); experimentData.setUser(rs.getString(3)); experimentData.setMetadata(rs.getString(4)); experimentData.setTopic(rs.getString(1)); WorkflowExecution workflowInstance = new WorkflowExecution(experimentId, rs.getString(5)); workflowInstance.setTemplateName(rs.getString(6)); workflowInstance.setExperimentId(rs.getString(1)); workflowInstance.setWorkflowExecutionId(rs.getString(5)); experimentWorkflowInstances.add(workflowInstance); } } if(rs != null){ rs.close(); } statement.close(); connection.close(); } catch (InstantiationException e) { logger.error(e.getMessage(), e); } catch (IllegalAccessException e) { logger.error(e.getMessage(), e); } catch (ClassNotFoundException e) { logger.error(e.getMessage(), e); } catch (SQLException e){ logger.error(e.getMessage(), e); } return experimentData; } public boolean isExperimentNameExist(String experimentName){ String connectionURL = Utils.getJDBCURL(); Connection connection = null; ResultSet rs = null; Statement statement; try{ Class.forName(Utils.getJDBCDriver()).newInstance(); connection = DriverManager.getConnection(connectionURL, Utils.getJDBCUser(), Utils.getJDBCPassword()); statement = connection.createStatement(); String queryString = "SELECT name FROM Experiment_Data WHERE name='" + experimentName + "'"; rs = statement.executeQuery(queryString); if(rs != null){ while (rs.next()) { return true; } } if(rs != null){ rs.close(); } statement.close(); connection.close(); } catch (ClassNotFoundException e) { logger.error(e.getMessage(), e); } catch (SQLException e) { logger.error(e.getMessage(), e); } catch (InstantiationException e) { logger.error(e.getMessage(), e); } catch (IllegalAccessException e) { logger.error(e.getMessage(), e); } return false; } public List<ExperimentData> getAllExperimentMetaInformation(String user){ String connectionURL = Utils.getJDBCURL(); Connection connection = null; ResultSet rs = null; Statement statement; List<ExperimentData> experimentDataList = new ArrayList<ExperimentData>(); List<WorkflowExecution> experimentWorkflowInstances = new ArrayList<WorkflowExecution>(); ExperimentData experimentData = null; try { Class.forName(Utils.getJDBCDriver()).newInstance(); connection = DriverManager.getConnection(connectionURL, Utils.getJDBCUser(), Utils.getJDBCPassword()); statement = connection.createStatement(); //FIXME : pass user ID as a regular expression String queryString = "SELECT e.experiment_ID, ed.name, ed.username, em.metadata, " + "e.project_name, e.submitted_date " + "FROM Experiment e " + "LEFT JOIN Experiment_Data ed " + "ON e.experiment_ID = ed.experiment_ID " + "LEFT JOIN Experiment_Metadata em " + "ON ed.experiment_ID = em.experiment_ID " + "WHERE ed.username ='" + user + "'" + " ORDER BY e.submitted_date ASC"; rs = statement.executeQuery(queryString); if (rs != null){ while (rs.next()) { experimentData = new ExperimentDataImpl(true); experimentData.setExperimentId(rs.getString(1)); experimentData.setExperimentName(rs.getString(2)); experimentData.setUser(rs.getString(3)); experimentData.setMetadata(rs.getString(4)); experimentData.setTopic(rs.getString(1)); WorkflowExecution workflowInstance = new WorkflowExecution(rs.getString(1), rs.getString(5)); workflowInstance.setTemplateName(rs.getString(6)); workflowInstance.setExperimentId(rs.getString(1)); workflowInstance.setWorkflowExecutionId(rs.getString(5)); experimentWorkflowInstances.add(workflowInstance); experimentDataList.add(experimentData); } } if(rs != null){ rs.close(); } statement.close(); connection.close(); } catch (InstantiationException e) { logger.error(e.getMessage(), e); } catch (IllegalAccessException e) { logger.error(e.getMessage(), e); } catch (ClassNotFoundException e) { logger.error(e.getMessage(), e); } catch (SQLException e){ logger.error(e.getMessage(), e); } return experimentDataList; } }
9,437
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/GFacJobStatusResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.Experiment_Data; import org.apache.airavata.persistance.registry.jpa.model.GFac_Job_Data; import org.apache.airavata.persistance.registry.jpa.model.GFac_Job_Status; import org.apache.airavata.persistance.registry.jpa.model.Workflow_Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import java.sql.Timestamp; import java.util.List; public class GFacJobStatusResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(GFacJobStatusResource.class); private GFacJobDataResource gFacJobDataResource; private String localJobID; private Timestamp statusUpdateTime; private String status; public String getLocalJobID() { return localJobID; } public Timestamp getStatusUpdateTime() { return statusUpdateTime; } public String getStatus() { return status; } public void setLocalJobID(String localJobID) { this.localJobID = localJobID; } public void setStatusUpdateTime(Timestamp statusUpdateTime) { this.statusUpdateTime = statusUpdateTime; } public void setStatus(String status) { this.status = status; } public GFacJobDataResource getgFacJobDataResource() { return gFacJobDataResource; } public void setgFacJobDataResource(GFacJobDataResource gFacJobDataResource) { this.gFacJobDataResource = gFacJobDataResource; } @Override public Resource create(ResourceType type) { logger.error("Unsupported resource type for GFac Job status resource" ,new UnsupportedOperationException() ); throw new UnsupportedOperationException(); } @Override public void remove(ResourceType type, Object name) { logger.error("Unsupported resource type for GFac Job status resource" ,new UnsupportedOperationException() ); throw new UnsupportedOperationException(); } @Override public Resource get(ResourceType type, Object name) { logger.error("Unsupported resource type for GFac Job status resource" ,new UnsupportedOperationException() ); throw new UnsupportedOperationException(); } @Override public List<Resource> get(ResourceType type) { logger.error("Unsupported resource type for GFac Job status resource" ,new UnsupportedOperationException() ); throw new UnsupportedOperationException(); } @Override public void save() { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); GFac_Job_Status gFacJobStatus = new GFac_Job_Status(); GFac_Job_Data gFacJobData = em.find(GFac_Job_Data.class, localJobID); gFacJobStatus.setgFac_job_data(gFacJobData); gFacJobStatus.setLocal_Job_ID(localJobID); gFacJobStatus.setStatus_update_time(statusUpdateTime); gFacJobStatus.setStatus(status); em.persist(gFacJobStatus); em.getTransaction().commit(); em.close(); } }
9,438
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/NodeDataResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.*; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import javax.persistence.Query; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; public class NodeDataResource extends AbstractResource{ private final static Logger logger = LoggerFactory.getLogger(NodeDataResource.class); private WorkflowDataResource workflowDataResource; private String nodeID; private String nodeType; private String inputs; private String outputs; private String status; private Timestamp startTime; private Timestamp lastUpdateTime; private int executionIndex; public WorkflowDataResource getWorkflowDataResource() { return workflowDataResource; } public String getNodeID() { return nodeID; } public String getNodeType() { return nodeType; } public String getInputs() { return inputs; } public String getOutputs() { return outputs; } public String getStatus() { return status; } public Timestamp getStartTime() { return startTime; } public Timestamp getLastUpdateTime() { return lastUpdateTime; } public void setWorkflowDataResource(WorkflowDataResource workflowDataResource) { this.workflowDataResource = workflowDataResource; } public void setNodeID(String nodeID) { this.nodeID = nodeID; } public void setNodeType(String nodeType) { this.nodeType = nodeType; } public void setInputs(String inputs) { this.inputs = inputs; } public void setOutputs(String outputs) { this.outputs = outputs; } public void setStatus(String status) { this.status = status; } public void setStartTime(Timestamp startTime) { this.startTime = startTime; } public void setLastUpdateTime(Timestamp lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } public Resource create(ResourceType type) { switch (type){ case GFAC_JOB_DATA: GFacJobDataResource gFacJobDataResource = new GFacJobDataResource(); gFacJobDataResource.setWorkflowDataResource(workflowDataResource); gFacJobDataResource.setNodeID(nodeID); return gFacJobDataResource; default: logger.error("Unsupported resource type for node data resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for node data resource."); } } public void remove(ResourceType type, Object name) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Query q; QueryGenerator generator; switch (type){ case GFAC_JOB_DATA: generator = new QueryGenerator(GFAC_JOB_DATA); generator.setParameter(GFacJobDataConstants.LOCAL_JOB_ID, name); q = generator.deleteQuery(em); q.executeUpdate(); break; default: logger.error("Unsupported resource type for node data resource.", new IllegalArgumentException()); break; } em.getTransaction().commit(); em.close(); } public Resource get(ResourceType type, Object name) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator; Query q; switch (type) { case GFAC_JOB_DATA: generator = new QueryGenerator(GFAC_JOB_DATA); generator.setParameter(GFacJobDataConstants.LOCAL_JOB_ID, name); q = generator.selectQuery(em); GFac_Job_Data gFac_job_data = (GFac_Job_Data)q.getSingleResult(); GFacJobDataResource gFacJobDataResource = (GFacJobDataResource)Utils.getResource(ResourceType.GFAC_JOB_DATA, gFac_job_data); em.getTransaction().commit(); em.close(); return gFacJobDataResource; default: em.getTransaction().commit(); em.close(); logger.error("Unsupported resource type for node data resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for node data resource."); } } public List<Resource> getGFacJobs(){ return get(ResourceType.GFAC_JOB_DATA); } public List<Resource> get(ResourceType type) { List<Resource> resourceList = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Query q; QueryGenerator generator; List<?> results; switch (type){ case EXECUTION_ERROR: generator = new QueryGenerator(EXECUTION_ERROR); generator.setParameter(ExecutionErrorConstants.NODE_ID, nodeID); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { Execution_Error execution_error = (Execution_Error)result; ExecutionErrorResource executionErrorResource = (ExecutionErrorResource)Utils.getResource(ResourceType.EXECUTION_ERROR, execution_error); resourceList.add(executionErrorResource); } } break; case GFAC_JOB_DATA: generator = new QueryGenerator(GFAC_JOB_DATA); generator.setParameter(GFacJobDataConstants.EXPERIMENT_ID, workflowDataResource.getExperimentID()); generator.setParameter(GFacJobDataConstants.WORKFLOW_INSTANCE_ID, workflowDataResource.getWorkflowInstanceID()); generator.setParameter(GFacJobDataConstants.NODE_ID, nodeID); q = generator.selectQuery(em); results = q.getResultList(); if (results.size() != 0) { for (Object result : results) { GFac_Job_Data gFac_job_data = (GFac_Job_Data)result; GFacJobDataResource gFacJobDataResource = (GFacJobDataResource)Utils.getResource(ResourceType.GFAC_JOB_DATA, gFac_job_data); resourceList.add(gFacJobDataResource); } } break; default: em.getTransaction().commit(); em.close(); logger.error("Unsupported resource type for node data resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for node data resource."); } em.getTransaction().commit(); em.close(); return resourceList; } public void save() { if(lastUpdateTime == null){ java.util.Date date= new java.util.Date(); lastUpdateTime = new Timestamp(date.getTime()); } EntityManager em = ResourceUtils.getEntityManager(); Node_Data existingNodeData = em.find(Node_Data.class, new Node_DataPK(workflowDataResource.getWorkflowInstanceID(), nodeID, executionIndex)); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Node_Data nodeData = new Node_Data(); nodeData.setNode_id(nodeID); Workflow_Data workflow_data = em.find(Workflow_Data.class, workflowDataResource.getWorkflowInstanceID()); nodeData.setWorkflow_Data(workflow_data); byte[] inputsByte = null; if (inputs!=null) { inputsByte = inputs.getBytes(); nodeData.setInputs(inputsByte); } byte[] outputsByte = null; if (outputs!=null) { outputsByte = outputs.getBytes(); nodeData.setOutputs(outputsByte); } nodeData.setNode_type(nodeType); nodeData.setLast_update_time(lastUpdateTime); nodeData.setStart_time(startTime); nodeData.setStatus(status); nodeData.setExecution_index(executionIndex); if(existingNodeData != null){ existingNodeData.setInputs(inputsByte); existingNodeData.setOutputs(outputsByte); existingNodeData.setLast_update_time(lastUpdateTime); existingNodeData.setNode_type(nodeType); existingNodeData.setStart_time(startTime); existingNodeData.setStatus(status); existingNodeData.setExecution_index(executionIndex); nodeData = em.merge(existingNodeData); } else { em.persist(nodeData); } em.getTransaction().commit(); em.close(); } public int getExecutionIndex() { return executionIndex; } public void setExecutionIndex(int executionIndex) { this.executionIndex = executionIndex; } }
9,439
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/DBC.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; public class DBC { public static final class ExperimentData{ public static final String TABLE="Experiment_Data"; public static final String EXPERIMENT_ID = "experiment_ID"; public static final String EXPERIMENT_NAME = "name"; public static final String USER_NAME = "username"; } public static final class ExperimentMetadata{ public static final String TABLE="Experiment_Metadata"; public static final String EXPERIMENT_ID = "experiment_ID"; public static final String METADATA = "metadata"; } public static final class WorkflowData { public static final String TABLE="Workflow_Data"; public static final String EXPERIMENT_ID = "experiment_ID"; public static final String INSTANCE_ID = "workflow_instanceID"; public static final String TEMPLATE_NAME = "template_name"; public static final String STATUS = "status"; public static final String START_TIME = "start_time"; public static final String LAST_UPDATED = "last_update_time"; } public static final class NodeData { public static final String TABLE="Node_Data"; public static final String WORKFLOW_INSTANCE_ID = "workflow_instanceID"; public static final String NODE_ID = "node_id"; public static final String TYPE = "node_type"; public static final String INPUTS = "inputs"; public static final String OUTPUTS = "outputs"; public static final String STATUS = "status"; public static final String START_TIME = "start_time"; public static final String LAST_UPDATED = "last_update_time"; } public static final class GramData { public static final String TABLE="Gram_Data"; public static final String WORKFLOW_INSTANCE_ID = "workflow_instanceID"; public static final String NODE_ID = "node_id"; public static final String RSL = "rsl"; public static final String INVOKED_HOST = "invoked_host"; } }
9,440
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/ExecutionErrorResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import java.sql.Timestamp; import java.util.List; import javax.persistence.EntityManager; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.Execution_Error; import org.apache.airavata.persistance.registry.jpa.model.Experiment_Data; import org.apache.airavata.persistance.registry.jpa.model.Workflow_Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExecutionErrorResource extends AbstractResource { private final static Logger logger = LoggerFactory.getLogger(ExecutionErrorResource.class); private ExperimentDataResource experimentDataResource; private WorkflowDataResource workflowDataResource; private String nodeID; private String gfacJobID; private String sourceType; private Timestamp errorTime; private String errorMsg; private String errorDes; private String errorCode; private int errorID; private String errorReporter; private String errorLocation; private String actionTaken; private int errorReference; @Override public Resource create(ResourceType type) { logger.error("Unsupported resource type for node error resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } @Override public void remove(ResourceType type, Object name) { logger.error("Unsupported resource type for node error resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } @Override public Resource get(ResourceType type, Object name) { logger.error("Unsupported resource type for node error resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } @Override public List<Resource> get(ResourceType type) { logger.error("Unsupported resource type for node error resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } @Override public void save() { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Execution_Error execution_error = new Execution_Error(); execution_error.setNode_id(nodeID); Experiment_Data experiment_data = em.find(Experiment_Data.class, experimentDataResource.getExperimentID()); execution_error.setExperiment_data(experiment_data); Workflow_Data workflow_data = em.find(Workflow_Data.class, workflowDataResource.getWorkflowInstanceID()); execution_error.setExperiment_ID(experiment_data.getExperiment_ID()); execution_error.setWorkflow_Data(workflow_data); execution_error.setWorkflow_instanceID(workflow_data.getWorkflow_instanceID()); execution_error.setError_code(errorCode); execution_error.setError_date(errorTime); execution_error.setError_des(errorDes); execution_error.setError_msg(errorMsg); execution_error.setSource_type(sourceType); execution_error.setGfacJobID(gfacJobID); em.persist(execution_error); errorID = execution_error.getError_id(); // System.out.println("Error ID : " + errorID); em.getTransaction().commit(); em.close(); } public ExperimentDataResource getExperimentDataResource() { return experimentDataResource; } public WorkflowDataResource getWorkflowDataResource() { return workflowDataResource; } public String getNodeID() { return nodeID; } public String getGfacJobID() { return gfacJobID; } public String getSourceType() { return sourceType; } public Timestamp getErrorTime() { return errorTime; } public String getErrorMsg() { return errorMsg; } public String getErrorDes() { return errorDes; } public String getErrorCode() { return errorCode; } public void setExperimentDataResource(ExperimentDataResource experimentDataResource) { this.experimentDataResource = experimentDataResource; } public void setWorkflowDataResource(WorkflowDataResource workflowDataResource) { this.workflowDataResource = workflowDataResource; } public void setNodeID(String nodeID) { this.nodeID = nodeID; } public void setGfacJobID(String gfacJobID) { this.gfacJobID = gfacJobID; } public void setSourceType(String sourceType) { this.sourceType = sourceType; } public void setErrorTime(Timestamp errorTime) { this.errorTime = errorTime; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public void setErrorDes(String errorDes) { this.errorDes = errorDes; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public int getErrorID() { return errorID; } public void setErrorID(int errorID) { this.errorID = errorID; } public String getErrorReporter() { return errorReporter; } public String getErrorLocation() { return errorLocation; } public String getActionTaken() { return actionTaken; } public void setErrorReporter(String errorReporter) { this.errorReporter = errorReporter; } public void setErrorLocation(String errorLocation) { this.errorLocation = errorLocation; } public void setActionTaken(String actionTaken) { this.actionTaken = actionTaken; } public int getErrorReference() { return errorReference; } public void setErrorReference(int errorReference) { this.errorReference = errorReference; } }
9,441
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/GramDataResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.Gram_Data; import org.apache.airavata.persistance.registry.jpa.model.Gram_DataPK; import org.apache.airavata.persistance.registry.jpa.model.Node_Data; import org.apache.airavata.persistance.registry.jpa.model.Workflow_Data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.EntityManager; import java.util.List; public class GramDataResource extends AbstractResource{ private final static Logger logger = LoggerFactory.getLogger(GramDataResource.class); private WorkflowDataResource workflowDataResource; private String nodeID; private String rsl; private String invokedHost; private String localJobID; public String getNodeID() { return nodeID; } public String getRsl() { return rsl; } public String getInvokedHost() { return invokedHost; } public String getLocalJobID() { return localJobID; } public WorkflowDataResource getWorkflowDataResource() { return workflowDataResource; } public void setWorkflowDataResource(WorkflowDataResource workflowDataResource) { this.workflowDataResource = workflowDataResource; } public void setNodeID(String nodeID) { this.nodeID = nodeID; } public void setRsl(String rsl) { this.rsl = rsl; } public void setInvokedHost(String invokedHost) { this.invokedHost = invokedHost; } public void setLocalJobID(String localJobID) { this.localJobID = localJobID; } public Resource create(ResourceType type) { logger.error("Unsupported resource type for Gram data resource" ,new UnsupportedOperationException() ); throw new UnsupportedOperationException(); } public void remove(ResourceType type, Object name) { logger.error("Unsupported resource type for Gram data resource" ,new UnsupportedOperationException() ); throw new UnsupportedOperationException(); } public Resource get(ResourceType type, Object name) { logger.error("Unsupported resource type for Gram data resource" ,new UnsupportedOperationException() ); throw new UnsupportedOperationException(); } public List<Resource> get(ResourceType type) { logger.error("Unsupported resource type for Gram data resource" ,new UnsupportedOperationException() ); throw new UnsupportedOperationException(); } public void save() { EntityManager em = ResourceUtils.getEntityManager(); Gram_Data existingGramData = em.find(Gram_Data.class, new Gram_DataPK(workflowDataResource.getWorkflowInstanceID(), nodeID)); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Gram_Data gramData = new Gram_Data(); gramData.setNode_id(nodeID); Workflow_Data workflow_data = em.find(Workflow_Data.class, workflowDataResource.getWorkflowInstanceID()); gramData.setWorkflow_Data(workflow_data); gramData.setNode_id(nodeID); gramData.setInvoked_host(invokedHost); gramData.setLocal_Job_ID(localJobID); byte[] bytes = rsl.getBytes(); gramData.setRsl(bytes); if(existingGramData != null){ existingGramData.setInvoked_host(invokedHost); existingGramData.setLocal_Job_ID(localJobID); existingGramData.setRsl(bytes); gramData = em.merge(existingGramData); } else { em.persist(gramData); } em.getTransaction().commit(); em.close(); } }
9,442
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/resources/ExperimentResource.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.resources; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import org.apache.airavata.persistance.registry.jpa.Resource; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.persistance.registry.jpa.model.Experiment; import org.apache.airavata.persistance.registry.jpa.model.Experiment_Data; import org.apache.airavata.persistance.registry.jpa.model.Gateway; import org.apache.airavata.persistance.registry.jpa.model.Project; import org.apache.airavata.persistance.registry.jpa.model.Users; import org.apache.airavata.persistance.registry.jpa.utils.QueryGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExperimentResource extends AbstractResource { private static final Logger logger = LoggerFactory.getLogger(ExperimentResource.class); private WorkerResource worker; private String expID; private Timestamp submittedDate; private GatewayResource gateway; private ProjectResource project; /** * */ public ExperimentResource() { } /** * * @return experiment ID */ public String getExpID() { return expID; } /** * * @return submitted date */ public Timestamp getSubmittedDate() { return submittedDate; } /** * * @param submittedDate submitted date */ public void setSubmittedDate(Timestamp submittedDate) { this.submittedDate = submittedDate; } /** * Since experiments are at the leaf level, this method is not * valid for an experiment * @param type child resource types * @return UnsupportedOperationException */ public Resource create(ResourceType type) { switch (type){ case EXPERIMENT_DATA: ExperimentDataResource expDataResource = new ExperimentDataResource(); expDataResource.setUserName(getWorker().getUser()); expDataResource.setExperimentID(getExpID()); return expDataResource; default: logger.error("Unsupported resource type for experiment resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for experiment resource."); } } /** * * @param type child resource types * @param name name of the child resource * @return UnsupportedOperationException */ public void remove(ResourceType type, Object name) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Query q; QueryGenerator generator; switch (type){ case EXPERIMENT_DATA: generator = new QueryGenerator(EXPERIMENT_DATA); generator.setParameter(ExperimentDataConstants.EXPERIMENT_ID, name); q = generator.deleteQuery(em); q.executeUpdate(); break; } em.getTransaction().commit(); em.close(); } /** * * @param type child resource types * @param name name of the child resource * @return UnsupportedOperationException */ public Resource get(ResourceType type, Object name) { EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator generator; Query q; switch (type) { case EXPERIMENT_DATA: generator = new QueryGenerator(EXPERIMENT_DATA); generator.setParameter(ExperimentDataConstants.EXPERIMENT_ID, name); q = generator.selectQuery(em); Experiment_Data experimentData = (Experiment_Data)q.getSingleResult(); ExperimentDataResource experimentDataResource = (ExperimentDataResource)Utils.getResource(ResourceType.EXPERIMENT_DATA, experimentData); em.getTransaction().commit(); em.close(); return experimentDataResource; default: em.getTransaction().commit(); em.close(); logger.error("Unsupported resource type for experiment resource.", new IllegalArgumentException()); throw new IllegalArgumentException("Unsupported resource type for experiment data resource."); } } /** * key should be the experiment ID * @param keys experiment ID * @return ExperimentResource */ public List<Resource> populate(Object[] keys) { List<Resource> list = new ArrayList<Resource>(); EntityManager em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); QueryGenerator queryGenerator = new QueryGenerator(EXPERIMENT); queryGenerator.setParameter(ExperimentConstants.EXPERIMENT_ID, keys[0]); Query q = queryGenerator.selectQuery(em); Experiment experiment = (Experiment)q.getSingleResult(); ExperimentResource experimentResource = (ExperimentResource)Utils.getResource(ResourceType.EXPERIMENT, experiment); em.getTransaction().commit(); em.close(); list.add(experimentResource); return list; } /** * * @param type child resource types * @return UnsupportedOperationException */ public List<Resource> get(ResourceType type) { logger.error("Unsupported resource type for experiment resource.", new UnsupportedOperationException()); throw new UnsupportedOperationException(); } /** * save experiment */ public void save() { EntityManager em = ResourceUtils.getEntityManager(); Experiment existingExp = em.find(Experiment.class, expID); em.close(); em = ResourceUtils.getEntityManager(); em.getTransaction().begin(); Experiment experiment = new Experiment(); Project projectmodel = em.find(Project.class, project.getName()); experiment.setProject(projectmodel); Users user = em.find(Users.class, getWorker().getUser()); Gateway gateway = em.find(Gateway.class, getGateway().getGatewayName()); experiment.setProject(projectmodel); experiment.setExperiment_ID(getExpID()); experiment.setUser(user); experiment.setGateway(gateway); experiment.setSubmitted_date(submittedDate); if(existingExp != null){ existingExp.setGateway(gateway); existingExp.setProject(projectmodel); existingExp.setUser(user); existingExp.setSubmitted_date(submittedDate); experiment = em.merge(existingExp); } else{ em.merge(experiment); } em.getTransaction().commit(); em.close(); } /** * * @param expID experiment ID */ public void setExpID(String expID) { this.expID = expID; } /** * * @return gatewayResource */ public GatewayResource getGateway() { return gateway; } /** * * @param gateway gateway */ public void setGateway(GatewayResource gateway) { this.gateway = gateway; } /** * * @return worker for the gateway */ public WorkerResource getWorker() { return worker; } /** * * @param worker gateway worker */ public void setWorker(WorkerResource worker) { this.worker = worker; } /** * * @return project */ public ProjectResource getProject() { return project; } /** * * @param project project */ public void setProject(ProjectResource project) { this.project = project; } public ExperimentDataResource getData(){ if (isExists(ResourceType.EXPERIMENT_DATA, getExpID())){ return (ExperimentDataResource) get(ResourceType.EXPERIMENT_DATA, getExpID()); }else{ ExperimentDataResource data = (ExperimentDataResource) create(ResourceType.EXPERIMENT_DATA); data.save(); return data; } } }
9,443
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/utils/QueryGenerator.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.utils; import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.Query; public class QueryGenerator { private String tableName; private Map<String,Object> matches=new HashMap<String, Object>(); private static final String SELECT_OBJ="p"; private static final String DELETE_OBJ="p"; private static final String TABLE_OBJ="p"; // // public QueryGenerator(String tableName) { // setTableName(tableName); // } public QueryGenerator(String tableName, Object[]...params) { setTableName(tableName); for (Object[] param : params) { addMatch(param[0].toString(), param[1]); } } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public void addMatch(String colName, Object matchValue){ matches.put(colName, matchValue); } public void setParameter(String colName, Object matchValue){ addMatch(colName, matchValue); } public Query selectQuery(EntityManager entityManager){ String queryString="SELECT "+ SELECT_OBJ + " FROM " +getTableName()+" "+TABLE_OBJ; return generateQueryWithParameters(entityManager, queryString); } // public Query countQuery(EntityManager entityManager){ // SELECT COUNT(p.host_descriptor_ID) FROM Host_Descriptor p WHERE p.gateway_name =:gate_ID and p.host_descriptor_ID =:host_desc_name") // String queryString="SELECT COUNT("+ SELECT_OBJ + " FROM " +getTableName()+" "+TABLE_OBJ; // return generateQueryWithParameters(entityManager, queryString); // } public Query deleteQuery(EntityManager entityManager){ String queryString="Delete FROM "+getTableName()+" "+TABLE_OBJ; return generateQueryWithParameters(entityManager, queryString); } private Query generateQueryWithParameters(EntityManager entityManager, String queryString) { Map<String,Object> queryParameters=new HashMap<String, Object>(); if (matches.size()>0){ String matchString = ""; int paramCount=0; for (String colName : matches.keySet()) { String paramName="param"+paramCount; queryParameters.put(paramName, matches.get(colName)); if (!matchString.equals("")){ matchString+=" AND "; } matchString+=TABLE_OBJ+"."+colName+" =:"+paramName; paramCount++; } queryString+=" WHERE "+matchString; } Query query = entityManager.createQuery(queryString); for (String paramName : queryParameters.keySet()) { query.setParameter(paramName, queryParameters.get(paramName)); } return query; } }
9,444
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Application_Descriptor.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.*; @Entity @IdClass(Application_Descriptor_PK.class) public class Application_Descriptor { @Id private String application_descriptor_ID; @Id private String gateway_name; private String host_descriptor_ID; private String service_descriptor_ID; @Lob private byte[] application_descriptor_xml; @ManyToOne(cascade=CascadeType.PERSIST) @JoinColumn(name = "gateway_name") private Gateway gateway; @ManyToOne(cascade=CascadeType.PERSIST) @JoinColumn(name = "updated_user", referencedColumnName = "user_name") private Users user; public String getApplication_descriptor_ID() { return application_descriptor_ID; } public byte[] getApplication_descriptor_xml() { return application_descriptor_xml; } public Gateway getGateway() { return gateway; } public String getHost_descriptor_ID() { return host_descriptor_ID; } public String getService_descriptor_ID() { return service_descriptor_ID; } public void setHost_descriptor_ID(String host_descriptor_ID) { this.host_descriptor_ID = host_descriptor_ID; } public void setService_descriptor_ID(String service_descriptor_ID) { this.service_descriptor_ID = service_descriptor_ID; } public void setApplication_descriptor_ID(String application_descriptor_ID) { this.application_descriptor_ID = application_descriptor_ID; } public void setApplication_descriptor_xml(byte[] application_descriptor_xml) { this.application_descriptor_xml = application_descriptor_xml; } public void setGateway(Gateway gateway) { this.gateway = gateway; } public Users getUser() { return user; } public void setUser(Users user) { this.user = user; } public String getGateway_name() { return gateway_name; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } }
9,445
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Host_Descriptor.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.*; @Entity @IdClass(Host_Descriptor_PK.class) public class Host_Descriptor { @Id private String host_descriptor_ID; @Id private String gateway_name; @Lob private byte[] host_descriptor_xml; @ManyToOne(cascade=CascadeType.MERGE) @JoinColumn(name = "gateway_name") private Gateway gateway; @ManyToOne (cascade=CascadeType.MERGE) @JoinColumn(name = "updated_user", referencedColumnName = "user_name") private Users user; public String getHost_descriptor_ID() { return host_descriptor_ID; } public byte[] getHost_descriptor_xml() { return host_descriptor_xml; } public Gateway getGateway() { return gateway; } public String getGateway_name() { return gateway_name; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } public void setHost_descriptor_ID(String host_descriptor_ID) { this.host_descriptor_ID = host_descriptor_ID; } public void setHost_descriptor_xml(byte[] host_descriptor_xml) { this.host_descriptor_xml = host_descriptor_xml; } public void setGateway(Gateway gateway) { this.gateway = gateway; } public Users getUser() { return user; } public void setUser(Users user) { this.user = user; } }
9,446
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Published_Workflow.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.*; import java.sql.Timestamp; @Entity @IdClass(Published_Workflow_PK.class) public class Published_Workflow { @Id private String publish_workflow_name; @Id private String gateway_name; @ManyToOne(cascade= CascadeType.MERGE) @JoinColumn(name = "gateway_name") private Gateway gateway; private String version; private Timestamp published_date; @Lob private byte[] workflow_content; private String path; @ManyToOne(cascade=CascadeType.MERGE) @JoinColumn(name = "created_user", referencedColumnName = "user_name") private Users user; public String getPublish_workflow_name() { return publish_workflow_name; } public String getVersion() { return version; } public Timestamp getPublished_date() { return published_date; } public byte[] getWorkflow_content() { return workflow_content; } public Gateway getGateway() { return gateway; } public void setPublish_workflow_name(String publish_workflow_name) { this.publish_workflow_name = publish_workflow_name; } public void setVersion(String version) { this.version = version; } public void setPublished_date(Timestamp published_date) { this.published_date = published_date; } public void setWorkflow_content(byte[] workflow_content) { this.workflow_content = workflow_content; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getGateway_name() { return gateway_name; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } public Users getUser() { return user; } public void setUser(Users user) { this.user = user; } public void setGateway(Gateway gateway) { this.gateway = gateway; } }
9,447
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Configuration_PK.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; public class Configuration_PK { private String config_key; private String config_val; private String category_id; public Configuration_PK(String config_key, String config_val, String category_id) { this.config_key = config_key; this.config_val = config_val; this.category_id = category_id; } public Configuration_PK() { ; } @Override public boolean equals(Object o) { return false; } @Override public int hashCode() { return 1; } public String getConfig_key() { return config_key; } public void setConfig_key(String config_key) { this.config_key = config_key; } public void setConfig_val(String config_val) { this.config_val = config_val; } public String getConfig_val() { return config_val; } public String getCategory_id() { return category_id; } public void setCategory_id(String category_id) { this.category_id = category_id; } }
9,448
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Experiment_Metadata.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Lob; @Entity public class Experiment_Metadata { @Id private String experiment_ID; @Lob private byte[] metadata; public String getExperiment_ID() { return experiment_ID; } public byte[] getMetadata() { return metadata; } public void setMetadata(byte[] metadata) { this.metadata = metadata; } public void setExperiment_ID(String experiment_ID) { this.experiment_ID = experiment_ID; } }
9,449
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Gram_DataPK.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; public class Gram_DataPK { private String workflow_instanceID; private String node_id; public Gram_DataPK() { ; } public Gram_DataPK(String workflow_instanceID, String node_id) { this.workflow_instanceID = workflow_instanceID; this.node_id = node_id; } @Override public boolean equals(Object o) { return false; } @Override public int hashCode() { return 1; } public String getWorkflow_instanceID() { return workflow_instanceID; } public void setWorkflow_instanceID(String workflow_instanceID) { this.workflow_instanceID = workflow_instanceID; } public String getNode_id() { return node_id; } public void setNode_id(String node_id) { this.node_id = node_id; } }
9,450
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/GFac_Job_Data.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.*; import java.sql.Timestamp; @Entity public class GFac_Job_Data { private String experiment_ID; private String workflow_instanceID; private String node_id; private String application_descriptor_ID; private String host_descriptor_ID; private String service_descriptor_ID; @Lob private String job_data; @Id private String local_Job_ID; private Timestamp submitted_time; private Timestamp status_update_time; private String status; @Lob private String metadata; @ManyToOne() @JoinColumn(name = "experiment_ID") private Experiment_Data experiment_data; @ManyToOne() @JoinColumn(name = "workflow_instanceID") private Workflow_Data workflow_Data; public String getExperiment_ID() { return experiment_ID; } public String getWorkflow_instanceID() { return workflow_instanceID; } public String getNode_id() { return node_id; } public String getApplication_descriptor_ID() { return application_descriptor_ID; } public String getHost_descriptor_ID() { return host_descriptor_ID; } public String getService_descriptor_ID() { return service_descriptor_ID; } public String getJob_data() { return job_data; } public String getLocal_Job_ID() { return local_Job_ID; } public Timestamp getSubmitted_time() { return submitted_time; } public Timestamp getStatus_update_time() { return status_update_time; } public String getStatus() { return status; } public String getMetadata() { return metadata; } public Experiment_Data getExperiment_data() { return experiment_data; } public Workflow_Data getWorkflow_Data() { return workflow_Data; } public void setExperiment_ID(String experiment_ID) { this.experiment_ID = experiment_ID; } public void setWorkflow_instanceID(String workflow_instanceID) { this.workflow_instanceID = workflow_instanceID; } public void setNode_id(String node_id) { this.node_id = node_id; } public void setApplication_descriptor_ID(String application_descriptor_ID) { this.application_descriptor_ID = application_descriptor_ID; } public void setHost_descriptor_ID(String host_descriptor_ID) { this.host_descriptor_ID = host_descriptor_ID; } public void setService_descriptor_ID(String service_descriptor_ID) { this.service_descriptor_ID = service_descriptor_ID; } public void setJob_data(String job_data) { this.job_data = job_data; } public void setLocal_Job_ID(String local_Job_ID) { this.local_Job_ID = local_Job_ID; } public void setSubmitted_time(Timestamp submitted_time) { this.submitted_time = submitted_time; } public void setStatus_update_time(Timestamp status_update_time) { this.status_update_time = status_update_time; } public void setStatus(String status) { this.status = status; } public void setMetadata(String metadata) { this.metadata = metadata; } public void setExperiment_data(Experiment_Data experiment_data) { this.experiment_data = experiment_data; } public void setWorkflow_Data(Workflow_Data workflow_Data) { this.workflow_Data = workflow_Data; } }
9,451
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Node_Data.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import java.sql.Timestamp; import javax.persistence.*; @Entity @IdClass(Node_DataPK.class) public class Node_Data { @Id private String workflow_instanceID; @ManyToOne() @JoinColumn(name = "workflow_instanceID") private Workflow_Data workflow_Data; @Id private String node_id; @Id private int execution_index; private String node_type; @Lob private byte[] inputs; @Lob private byte[] outputs; private String status; private Timestamp start_time; private Timestamp last_update_time; public Workflow_Data getWorkflow_Data() { return workflow_Data; } public void setWorkflow_Data(Workflow_Data workflow_Data) { this.workflow_Data = workflow_Data; } public String getNode_id() { return node_id; } public void setNode_id(String node_id) { this.node_id = node_id; } public String getNode_type() { return node_type; } public void setNode_type(String node_type) { this.node_type = node_type; } public byte[] getInputs() { return inputs; } public void setInputs(byte[] inputs) { this.inputs = inputs; } public byte[] getOutputs() { return outputs; } public void setOutputs(byte[] outputs) { this.outputs = outputs; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Timestamp getStart_time() { return start_time; } public void setStart_time(Timestamp start_time) { this.start_time = start_time; } public Timestamp getLast_update_time() { return last_update_time; } public void setLast_update_time(Timestamp last_update_time) { this.last_update_time = last_update_time; } public String getWorkflow_instanceID() { return workflow_instanceID; } public void setWorkflow_instanceID(String workflow_instanceID) { this.workflow_instanceID = workflow_instanceID; } public int getExecution_index() { return execution_index; } public void setExecution_index(int execution_index) { this.execution_index = execution_index; } }
9,452
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Experiment.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.*; import java.sql.Timestamp; @Entity public class Experiment { @Id private String experiment_ID; private Timestamp submitted_date; private String user_name; private String gateway_name; private String project_name; @ManyToOne(cascade= CascadeType.MERGE) @JoinColumn(name = "user_name") private Users user; @ManyToOne(cascade=CascadeType.MERGE) @JoinColumn(name = "gateway_name") private Gateway gateway; @ManyToOne(cascade=CascadeType.MERGE) @JoinColumn(name = "project_name") private Project project; public String getExperiment_ID() { return experiment_ID; } public Timestamp getSubmitted_date() { return submitted_date; } public Users getUser() { return user; } public Project getProject() { return project; } public void setExperiment_ID(String experiment_ID) { this.experiment_ID = experiment_ID; } public void setSubmitted_date(Timestamp submitted_date) { this.submitted_date = submitted_date; } public void setUser(Users user) { this.user = user; } public void setProject(Project project) { this.project = project; } public Gateway getGateway() { return gateway; } public void setGateway(Gateway gateway) { this.gateway = gateway; } }
9,453
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Gateway.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Gateway { @Id private String gateway_name; private String owner; public String getGateway_name() { return gateway_name; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } }
9,454
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Configuration.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.*; import java.io.Serializable; import java.sql.Timestamp; @Entity @IdClass(Configuration_PK.class) public class Configuration implements Serializable { @Id private String config_key; @Id private String config_val; @Id private String category_id; private Timestamp expire_date; public String getConfig_key() { return config_key; } public String getConfig_val() { return config_val; } public Timestamp getExpire_date() { return expire_date; } public void setConfig_key(String config_key) { this.config_key = config_key; } public void setConfig_val(String config_val) { this.config_val = config_val; } public void setExpire_date(Timestamp expire_date) { this.expire_date = expire_date; } public String getCategory_id() { return category_id; } public void setCategory_id(String category_id) { this.category_id = category_id; } }
9,455
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Experiment_Data.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class Experiment_Data { @Id private String experiment_ID; private String name; private String username; /*@OneToMany(cascade=CascadeType.ALL, mappedBy = "Experiment_Data") private final List<Workflow_Data> workflows = new ArrayList<Workflow_Data>();*/ public String getExperiment_ID() { return experiment_ID; } public void setExperiment_ID(String experiment_ID) { this.experiment_ID = experiment_ID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } /*public List<Workflow_Data> getWorkflows() { return workflows; }*/ }
9,456
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Service_Descriptor.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.*; @Entity @IdClass(Service_Descriptor_PK.class) public class Service_Descriptor { @Id private String service_descriptor_ID; @Id private String gateway_name; @Lob private byte[] service_descriptor_xml; @ManyToOne(cascade=CascadeType.MERGE) @JoinColumn(name = "gateway_name") private Gateway gateway; @ManyToOne(cascade=CascadeType.MERGE) @JoinColumn(name = "updated_user", referencedColumnName = "user_name") private Users user; public String getService_descriptor_ID() { return service_descriptor_ID; } public byte[] getService_descriptor_xml() { return service_descriptor_xml; } public Gateway getGateway() { return gateway; } public void setService_descriptor_ID(String service_descriptor_ID) { this.service_descriptor_ID = service_descriptor_ID; } public void setService_descriptor_xml(byte[] service_descriptor_xml) { this.service_descriptor_xml = service_descriptor_xml; } public void setGateway(Gateway gateway) { this.gateway = gateway; } public Users getUser() { return user; } public void setUser(Users user) { this.user = user; } public String getGateway_name() { return gateway_name; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } }
9,457
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Host_Descriptor_PK.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; public class Host_Descriptor_PK { private String gateway_name; private String host_descriptor_ID; public Host_Descriptor_PK() { ; } public Host_Descriptor_PK(String gateway_name, String host_descriptor_ID) { this.gateway_name = gateway_name; this.host_descriptor_ID = host_descriptor_ID; } @Override public boolean equals(Object o) { return false; } @Override public int hashCode() { return 1; } public String getGateway_name() { return gateway_name; } public String getHost_descriptor_ID() { return host_descriptor_ID; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } public void setHost_descriptor_ID(String host_descriptor_ID) { this.host_descriptor_ID = host_descriptor_ID; } }
9,458
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Users.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity public class Users { @Id private String user_name; private String password; public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
9,459
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Gateway_Worker_PK.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; public class Gateway_Worker_PK { private String gateway_name; private String user_name; public Gateway_Worker_PK(String gateway_name, String user_name) { this.gateway_name = gateway_name; this.user_name = user_name; } public Gateway_Worker_PK() { ; } @Override public boolean equals(Object o) { return false; } @Override public int hashCode() { return 1; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public String getGateway_name() { return gateway_name; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } }
9,460
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Service_Descriptor_PK.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; public class Service_Descriptor_PK { private String gateway_name; private String service_descriptor_ID; public Service_Descriptor_PK() { ; } public Service_Descriptor_PK(String gateway_name, String service_descriptor_ID) { this.gateway_name = gateway_name; this.service_descriptor_ID = service_descriptor_ID; } @Override public boolean equals(Object o) { return false; } @Override public int hashCode() { return 1; } public String getGateway_name() { return gateway_name; } public String getService_descriptor_ID() { return service_descriptor_ID; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } public void setService_descriptor_ID(String service_descriptor_ID) { this.service_descriptor_ID = service_descriptor_ID; } }
9,461
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/User_Workflow.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.*; import java.sql.Timestamp; @Entity @IdClass(User_Workflow_PK.class) public class User_Workflow { @Id private String gateway_name; @Id private String owner; @Id private String template_name; @ManyToOne(cascade= CascadeType.MERGE) @JoinColumn(name = "gateway_name") private Gateway gateway; @ManyToOne(cascade=CascadeType.MERGE) @JoinColumn(name = "owner", referencedColumnName = "user_name") private Users user; private String path; private Timestamp last_updated_date; @Lob private byte[] workflow_graph; public String getTemplate_name() { return template_name; } public Users getUser() { return user; } public void setTemplate_name(String template_name) { this.template_name = template_name; } public void setUser(Users user) { this.user = user; } public Gateway getGateway() { return gateway; } public String getGateway_name() { return gateway_name; } public String getOwner() { return owner; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } public void setOwner(String owner) { this.owner = owner; } public String getPath() { return path; } public Timestamp getLast_updated_date() { return last_updated_date; } public byte[] getWorkflow_graph() { return workflow_graph; } public void setGateway(Gateway gateway) { this.gateway = gateway; } public void setPath(String path) { this.path = path; } public void setWorkflow_graph(byte[] workflow_graph) { this.workflow_graph = workflow_graph; } public void setLast_updated_date(Timestamp last_updated_date) { this.last_updated_date = last_updated_date; } }
9,462
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Application_Descriptor_PK.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; public class Application_Descriptor_PK { private String gateway_name; private String application_descriptor_ID; public Application_Descriptor_PK(String gateway_name, String application_descriptor_ID) { this.gateway_name = gateway_name; this.application_descriptor_ID = application_descriptor_ID; } public Application_Descriptor_PK() { ; } @Override public boolean equals(Object o) { return false; } @Override public int hashCode() { return 1; } public String getGateway_name() { return gateway_name; } public String getApplication_descriptor_ID() { return application_descriptor_ID; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } public void setApplication_descriptor_ID(String application_descriptor_ID) { this.application_descriptor_ID = application_descriptor_ID; } }
9,463
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Gateway_Worker.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.*; @Entity @IdClass(Gateway_Worker_PK.class) public class Gateway_Worker { @Id private String gateway_name; @Id private String user_name; @ManyToOne(cascade=CascadeType.MERGE) @JoinColumn(name = "gateway_name") private Gateway gateway; @ManyToOne(cascade=CascadeType.MERGE) @JoinColumn(name = "user_name") private Users user; public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } public void setGateway(Gateway gateway) { this.gateway = gateway; } public Gateway getGateway() { return gateway; } public Users getUser() { return user; } public void setUser(Users user) { this.user = user; } public String getGateway_name() { return gateway_name; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } }
9,464
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Project.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.*; @Entity public class Project { @Id private String project_name; @ManyToOne(cascade=CascadeType.MERGE) @JoinColumn(name = "gateway_name") private Gateway gateway; @ManyToOne(cascade=CascadeType.MERGE) @JoinColumn(name = "user_name") private Users users; public String getProject_name() { return project_name; } public Gateway getGateway() { return gateway; } public void setProject_name(String project_name) { this.project_name = project_name; } public void setGateway(Gateway gateway) { this.gateway = gateway; } public Users getUsers() { return users; } public void setUsers(Users users) { this.users = users; } }
9,465
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Published_Workflow_PK.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; public class Published_Workflow_PK { private String gateway_name; private String publish_workflow_name; public Published_Workflow_PK(String gateway_name, String publish_workflow_name) { this.gateway_name = gateway_name; this.publish_workflow_name = publish_workflow_name; } public Published_Workflow_PK() { ; } @Override public boolean equals(Object o) { return false; } @Override public int hashCode() { return 1; } public String getPublish_workflow_name() { return publish_workflow_name; } public void setPublish_workflow_name(String publish_workflow_name) { this.publish_workflow_name = publish_workflow_name; } public String getGateway_name() { return gateway_name; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } }
9,466
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Execution_Error.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import java.sql.Timestamp; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; @Entity public class Execution_Error { @Id @GeneratedValue private int error_id; private String experiment_ID; private String workflow_instanceID; private String node_id; private String gfacJobID; private String source_type; private Timestamp error_date; private String error_reporter; private String error_location; private String action_taken; private int error_reference; @ManyToOne() @JoinColumn(name = "experiment_ID") private Experiment_Data experiment_data; @ManyToOne() @JoinColumn(name = "workflow_instanceID") private Workflow_Data workflow_Data; @Lob private String error_msg; @Lob private String error_des; private String error_code; public String getWorkflow_instanceID() { return workflow_instanceID; } public String getNode_id() { return node_id; } public Workflow_Data getWorkflow_Data() { return workflow_Data; } public String getError_msg() { return error_msg; } public String getError_des() { return error_des; } public String getError_code() { return error_code; } public void setWorkflow_instanceID(String workflow_instanceID) { this.workflow_instanceID = workflow_instanceID; } public void setNode_id(String node_id) { this.node_id = node_id; } public void setWorkflow_Data(Workflow_Data workflow_Data) { this.workflow_Data = workflow_Data; } public void setError_msg(String error_msg) { this.error_msg = error_msg; } public void setError_des(String error_des) { this.error_des = error_des; } public void setError_code(String error_code) { this.error_code = error_code; } public int getError_id() { return error_id; } public String getExperiment_ID() { return experiment_ID; } public String getGfacJobID() { return gfacJobID; } public String getSource_type() { return source_type; } public Timestamp getError_date() { return error_date; } public Experiment_Data getExperiment_Data() { return experiment_data; } public void setError_id(int error_id) { this.error_id = error_id; } public void setExperiment_ID(String experiment_ID) { this.experiment_ID = experiment_ID; } public void setGfacJobID(String gfacJobID) { this.gfacJobID = gfacJobID; } public void setSource_type(String source_type) { this.source_type = source_type; } public void setError_date(Timestamp error_date) { this.error_date = error_date; } public void setExperiment_data(Experiment_Data experiment_data) { this.experiment_data = experiment_data; } public String getError_reporter() { return error_reporter; } public String getError_location() { return error_location; } public String getAction_taken() { return action_taken; } public Experiment_Data getExperiment_data() { return experiment_data; } public void setError_reporter(String error_reporter) { this.error_reporter = error_reporter; } public void setError_location(String error_location) { this.error_location = error_location; } public void setAction_taken(String action_taken) { this.action_taken = action_taken; } public int getError_reference() { return error_reference; } public void setError_reference(int error_reference) { this.error_reference = error_reference; } }
9,467
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Workflow_Data.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import java.sql.Timestamp; import javax.persistence.*; @Entity public class Workflow_Data { @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumn(name="experiment_ID") private Experiment_Data experiment_data; @Id private String workflow_instanceID; private String template_name; private String status; private Timestamp start_time; private Timestamp last_update_time; public String getWorkflow_instanceID() { return workflow_instanceID; } public void setWorkflow_instanceID(String workflow_instanceID) { this.workflow_instanceID = workflow_instanceID; } public String getTemplate_name() { return template_name; } public void setTemplate_name(String template_name) { this.template_name = template_name; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Timestamp getStart_time() { return start_time; } public void setStart_time(Timestamp start_time) { this.start_time = start_time; } public Timestamp getLast_update_time() { return last_update_time; } public void setLast_update_time(Timestamp last_update_time) { this.last_update_time = last_update_time; } public Experiment_Data getExperiment_data() { return experiment_data; } public void setExperiment_data(Experiment_Data experiment_data) { this.experiment_data = experiment_data; } }
9,468
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/GFac_Job_Status.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.*; import java.sql.Timestamp; @Entity public class GFac_Job_Status { private String local_Job_ID; private Timestamp status_update_time; private String status; @ManyToOne() @JoinColumn(name = "local_Job_ID") private GFac_Job_Data gFac_job_data; public String getLocal_Job_ID() { return local_Job_ID; } public Timestamp getStatus_update_time() { return status_update_time; } public String getStatus() { return status; } public void setLocal_Job_ID(String local_Job_ID) { this.local_Job_ID = local_Job_ID; } public void setStatus_update_time(Timestamp status_update_time) { this.status_update_time = status_update_time; } public void setStatus(String status) { this.status = status; } public GFac_Job_Data getgFac_job_data() { return gFac_job_data; } public void setgFac_job_data(GFac_Job_Data gFac_job_data) { this.gFac_job_data = gFac_job_data; } }
9,469
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Node_DataPK.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; public class Node_DataPK { private String workflow_instanceID; private String node_id; private int execution_index; public Node_DataPK() { ; } public Node_DataPK(String workflow_instanceID, String node_id, int execution_index) { this.workflow_instanceID = workflow_instanceID; this.node_id = node_id; this.execution_index = execution_index; } @Override public boolean equals(Object o) { return false; } @Override public int hashCode() { return 1; } public String getWorkflow_instanceID() { return workflow_instanceID; } public void setWorkflow_instanceID(String workflow_instanceID) { this.workflow_instanceID = workflow_instanceID; } public String getNode_id() { return node_id; } public void setNode_id(String node_id) { this.node_id = node_id; } public int getExecution_index() { return execution_index; } public void setExecution_index(int execution_index) { this.execution_index = execution_index; } }
9,470
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/User_Workflow_PK.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; public class User_Workflow_PK { private String template_name; private String gateway_name; private String owner; public User_Workflow_PK(String template_name, String owner, String gateway_name) { this.template_name = template_name; this.gateway_name = gateway_name; this.owner = owner; } public User_Workflow_PK() { ; } @Override public boolean equals(Object o) { return false; } @Override public int hashCode() { return 1; } public String getTemplate_name() { return template_name; } public String getGateway_name() { return gateway_name; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public void setTemplate_name(String template_name) { this.template_name = template_name; } public void setGateway_name(String gateway_name) { this.gateway_name = gateway_name; } }
9,471
0
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa
Create_ds/airavata-sandbox/registry/airavata-jpa-registry/src/main/java/org/apache/airavata/persistance/registry/jpa/model/Gram_Data.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.persistance.registry.jpa.model; import javax.persistence.*; @Entity @IdClass(Gram_DataPK.class) public class Gram_Data { @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumn(name = "workflow_instanceID") private Workflow_Data workflow_Data; @Id private String workflow_instanceID; @Id private String node_id; @Lob private byte[] rsl; private String invoked_host; private String local_Job_ID; public Workflow_Data getWorkflow_Data() { return workflow_Data; } public void setWorkflow_Data(Workflow_Data workflow_Data) { this.workflow_Data = workflow_Data; } public String getNode_id() { return node_id; } public void setNode_id(String node_id) { this.node_id = node_id; } public byte[] getRsl() { return rsl; } public void setRsl(byte[] rsl) { this.rsl = rsl; } public String getInvoked_host() { return invoked_host; } public void setInvoked_host(String invoked_host) { this.invoked_host = invoked_host; } public String getLocal_Job_ID() { return local_Job_ID; } public void setLocal_Job_ID(String local_Job_ID) { this.local_Job_ID = local_Job_ID; } public String getWorkflow_instanceID() { return workflow_instanceID; } public void setWorkflow_instanceID(String workflow_instanceID) { this.workflow_instanceID = workflow_instanceID; } }
9,472
0
Create_ds/airavata-sandbox/registry/airavata-registry-test/src/test/java/org/apache/airavata/registry/api
Create_ds/airavata-sandbox/registry/airavata-registry-test/src/test/java/org/apache/airavata/registry/api/test/AiravataRegistryAPITest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.registry.api.test; import junit.framework.TestCase; import org.apache.airavata.commons.gfac.type.ApplicationDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.persistance.registry.jpa.ResourceUtils; import org.apache.airavata.registry.api.*; import org.apache.airavata.registry.api.exception.RegistryException; import org.apache.airavata.registry.api.test.util.Initialize; import org.apache.airavata.registry.api.workflow.*; import org.apache.airavata.schemas.gfac.*; import java.net.URI; import java.sql.Date; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Map; public class AiravataRegistryAPITest extends TestCase { private AiravataRegistry2 registry; private Initialize initialize; @Override protected void setUp() throws Exception { initialize = new Initialize(); initialize.initializeDB(); registry = AiravataRegistryFactory.getRegistry(new Gateway("default"), new AiravataUser("admin")); } public void testAddConfiguration() throws Exception { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); registry.addConfiguration("configkey", "configval", currentTime); assertTrue("configuration add successfully", ResourceUtils.isConfigurationExists("configkey", "configval")); Object config = registry.getConfiguration("configkey"); ResourceUtils.removeConfiguration("configkey", "configval"); } public void testGetConfigurationList() throws Exception { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); registry.addConfiguration("configkey1", "configval1", currentTime); registry.addConfiguration("configkey1", "configval2", currentTime); List<Object> list = registry.getConfigurationList("configkey1"); assertTrue("configurations retrieved successfully", list.size() == 2); ResourceUtils.removeConfiguration("configkey1"); } public void testSetConfiguration() throws Exception { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); registry.addConfiguration("configkey1", "configval1", currentTime); registry.setConfiguration("configkey1", "configval1", currentTime); registry.setConfiguration("configkey2", "configval2", currentTime); assertTrue("Configuration updated successfully", ResourceUtils.isConfigurationExist("configkey1")); assertTrue("Configuration updated successfully", ResourceUtils.isConfigurationExist("configkey2")); ResourceUtils.removeConfiguration("configkey1"); ResourceUtils.removeConfiguration("configkey2"); } public void testRemoveAllConfiguration() throws RegistryException { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); registry.addConfiguration("configkey1", "configval1", currentTime); registry.addConfiguration("configkey1", "configval2", currentTime); registry.removeAllConfiguration("configkey1"); assertFalse("configurations removed successfully", ResourceUtils.isConfigurationExist("configkey1")); } public void testRemoveConfiguration() throws RegistryException { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); registry.addConfiguration("configkey1", "configval1", currentTime); registry.removeConfiguration("configkey1", "configval1"); assertFalse("comnfiguration removed successfully", ResourceUtils.isConfigurationExists("configkey1", "configval1")); } public void testGetGFacURIs() throws RegistryException { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); registry.addConfiguration("gfac.url", "http://192.168.17.1:8080/axis2/services/GFacService", currentTime); List<URI> gFacURIs = registry.getGFacURIs(); assertTrue("gfac urls retrieved successfully", gFacURIs.size() == 1); ResourceUtils.removeConfiguration("gfac.url"); } public void testGetWorkflowInterpreterURIs() throws RegistryException { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); registry.addConfiguration("interpreter.url", "http://192.168.17.1:8080/axis2/services/WorkflowInterpretor", currentTime); List<URI> interpreterURIs = registry.getWorkflowInterpreterURIs(); assertTrue("interpreter urls retrieved successfully", interpreterURIs.size() == 1); ResourceUtils.removeConfiguration("interpreter.url"); } public void testGetEventingServiceURI() throws RegistryException { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); registry.addConfiguration("eventing.url", "http://192.168.17.1:8080/axis2/services/EventingService", currentTime); URI eventingServiceURI = registry.getEventingServiceURI(); assertNotNull("eventing url retrieved successfully", eventingServiceURI); ResourceUtils.removeConfiguration("eventing.url"); } public void testGetMessageBoxURI() throws RegistryException { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); registry.addConfiguration("messagebox.url", "http://192.168.17.1:8080/axis2/services/MsgBoxService", currentTime); URI messageBoxURI = registry.getMessageBoxURI(); assertNotNull("message box url retrieved successfully", messageBoxURI); ResourceUtils.removeConfiguration("messagebox.url"); } public void testAddGFacURI() throws RegistryException { URI uri = URI.create("http://192.168.17.1:8080/axis2/services/GFacService"); registry.addGFacURI(uri); List<URI> gFacURIs = registry.getGFacURIs(); assertTrue("gfac url add successfully", gFacURIs.size() == 1); registry.removeConfiguration("gfac.url", "http://192.168.17.1:8080/axis2/services/GFacService"); } public void testAddWorkflowInterpreterURI() throws RegistryException { URI uri = URI.create("http://192.168.17.1:8080/axis2/services/WorkflowInterpretor"); registry.addWorkflowInterpreterURI(uri); List<URI> interpreterURIs = registry.getWorkflowInterpreterURIs(); assertTrue("interpreter url add successfully", interpreterURIs.size() == 1); registry.removeConfiguration("interpreter.url", "http://192.168.17.1:8080/axis2/services/WorkflowInterpretor"); } public void testSetEventingURI() throws RegistryException { URI uri = URI.create("http://192.168.17.1:8080/axis2/services/EventingService"); registry.setEventingURI(uri); URI eventingServiceURI = registry.getEventingServiceURI(); assertNotNull("eventing url added successfully", eventingServiceURI); registry.removeConfiguration("eventing.url", "http://192.168.17.1:8080/axis2/services/EventingService"); } public void testSetMessageBoxURI() throws RegistryException { URI uri = URI.create("http://192.168.17.1:8080/axis2/services/MsgBoxService"); registry.setMessageBoxURI(uri); URI messageBoxURI = registry.getMessageBoxURI(); assertNotNull("message box url added successfully", messageBoxURI); registry.removeConfiguration("messagebox.url", "http://192.168.17.1:8080/axis2/services/MsgBoxService"); } public void testAddGFacURIWithExpireDate() throws RegistryException { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); URI uri = URI.create("http://192.168.17.1:8080/axis2/services/GFacService"); registry.addGFacURI(uri, currentTime); List<URI> gFacURIs = registry.getGFacURIs(); assertTrue("gfac url add successfully", gFacURIs.size() == 1); registry.removeConfiguration("gfac.url", "http://192.168.17.1:8080/axis2/services/GFacService"); } public void testAddWorkflowInterpreterURIWithExpireDate() throws RegistryException { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); URI uri = URI.create("http://192.168.17.1:8080/axis2/services/WorkflowInterpretor"); registry.addWorkflowInterpreterURI(uri, currentTime); List<URI> interpreterURIs = registry.getWorkflowInterpreterURIs(); assertTrue("interpreter url add successfully", interpreterURIs.size() == 1); registry.removeConfiguration("interpreter.url", "http://192.168.17.1:8080/axis2/services/WorkflowInterpretor"); } public void testSetEventingURIWithExpireDate() throws RegistryException { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); URI uri = URI.create("http://192.168.17.1:8080/axis2/services/EventingService"); registry.setEventingURI(uri, currentTime); URI eventingServiceURI = registry.getEventingServiceURI(); assertNotNull("eventing url added successfully", eventingServiceURI); registry.removeConfiguration("eventing.url", "http://192.168.17.1:8080/axis2/services/EventingService"); } public void testSetMessageBoxURIWithExpireDate() throws RegistryException { Calendar calender = Calendar.getInstance(); java.util.Date d = calender.getTime(); Date currentTime = new Date(d.getTime()); URI uri = URI.create("http://192.168.17.1:8080/axis2/services/MsgBoxService"); registry.setMessageBoxURI(uri, currentTime); URI messageBoxURI = registry.getMessageBoxURI(); assertNotNull("message box url added successfully", messageBoxURI); registry.removeConfiguration("messagebox.url", "http://192.168.17.1:8080/axis2/services/MsgBoxService"); } public void testRemoveGFacURI() throws RegistryException { URI uri = URI.create("http://192.168.17.1:8080/axis2/services/GFacService"); registry.addGFacURI(uri); registry.removeGFacURI(uri); assertFalse("Gfac uri removed successfully", ResourceUtils.isConfigurationExist("gfac.url")); } public void testRemoveAllGFacURI() throws RegistryException { URI uri = URI.create("http://192.168.17.1:8080/axis2/services/GFacService"); registry.addGFacURI(uri); registry.removeAllGFacURI(); assertFalse("Gfac uri removed successfully", ResourceUtils.isConfigurationExist("gfac.url")); } public void testRemoveWorkflowInterpreterURI() throws RegistryException { URI uri = URI.create("http://192.168.17.1:8080/axis2/services/WorkflowInterpretor"); registry.addWorkflowInterpreterURI(uri); registry.removeWorkflowInterpreterURI(uri); assertFalse("workflow interpreter uri removed successfully", ResourceUtils.isConfigurationExist("interpreter.url")); } public void testRemoveAllWorkflowInterpreterURI() throws RegistryException { URI uri = URI.create("http://192.168.17.1:8080/axis2/services/WorkflowInterpretor"); registry.addWorkflowInterpreterURI(uri); registry.removeAllWorkflowInterpreterURI(); assertFalse("workflow interpreter uri removed successfully", ResourceUtils.isConfigurationExist("interpreter.url")); } public void testUnsetEventingURI() throws RegistryException { URI uri = URI.create("http://192.168.17.1:8080/axis2/services/EventingService"); registry.setEventingURI(uri); registry.unsetEventingURI(); assertNotNull("eventing url removed successfully", ResourceUtils.isConfigurationExist("eventing.url")); } public void testUnsetMessageBoxURI() throws RegistryException { URI uri = URI.create("http://192.168.17.1:8080/axis2/services/MsgBoxService"); registry.setMessageBoxURI(uri); registry.unsetMessageBoxURI(); assertNotNull("message url removed successfully", ResourceUtils.isConfigurationExist("messagebox.url")); } public void testIsHostDescriptorExists() throws Exception { HostDescription descriptor = new HostDescription(GlobusHostType.type); descriptor.getType().setHostName("testHost"); descriptor.getType().setHostAddress("testHostAddress"); registry.addHostDescriptor(descriptor); assertTrue("Host added successfully", registry.isHostDescriptorExists("testHost")); registry.removeHostDescriptor("testHost"); } public void testAddHostDescriptor() throws Exception { HostDescription descriptor = new HostDescription(GlobusHostType.type); descriptor.getType().setHostName("testHost"); descriptor.getType().setHostAddress("testHostAddress"); registry.addHostDescriptor(descriptor); assertTrue("Host added successfully", registry.isHostDescriptorExists("testHost")); registry.removeHostDescriptor("testHost"); } public void testUpdateHostDescriptor() throws Exception { HostDescription descriptor = new HostDescription(GlobusHostType.type); descriptor.getType().setHostName("testHost"); descriptor.getType().setHostAddress("testHostAddress"); registry.addHostDescriptor(descriptor); HostDescription hostDescriptor = registry.getHostDescriptor("testHost"); hostDescriptor.getType().setHostAddress("testHostAddress2"); registry.updateHostDescriptor(hostDescriptor); HostDescription testHost = registry.getHostDescriptor("testHost"); assertTrue("host updated successfully", testHost.getType().getHostAddress().equals("testHostAddress2")); registry.removeHostDescriptor("testHost"); } public void testGetHostDescriptor() throws Exception { HostDescription descriptor = new HostDescription(GlobusHostType.type); descriptor.getType().setHostName("testHost"); descriptor.getType().setHostAddress("testHostAddress"); registry.addHostDescriptor(descriptor); HostDescription hostDescriptor = registry.getHostDescriptor("testHost"); assertNotNull("host descriptor retrieved successfully", hostDescriptor); registry.removeHostDescriptor("testHost"); } public void testRemoveHostDescriptor() throws Exception { HostDescription descriptor = new HostDescription(GlobusHostType.type); descriptor.getType().setHostName("testHost"); descriptor.getType().setHostAddress("testHostAddress"); registry.addHostDescriptor(descriptor); registry.removeHostDescriptor("testHost"); assertFalse("host descriptor removed successfully", registry.isHostDescriptorExists("testHost")); } public void testGetHostDescriptors() throws Exception { HostDescription descriptor = new HostDescription(GlobusHostType.type); descriptor.getType().setHostName("testHost"); descriptor.getType().setHostAddress("testHostAddress"); registry.addHostDescriptor(descriptor); List<HostDescription> hostDescriptors = registry.getHostDescriptors(); assertTrue("host descriptors retrieved successfully", hostDescriptors.size() == 1); registry.removeHostDescriptor("testHost"); } public void testIsServiceDescriptorExists() throws Exception { ServiceDescription serviceDescription = new ServiceDescription(); List<InputParameterType> inputParameters = new ArrayList<InputParameterType>(); List<OutputParameterType> outputParameters = new ArrayList<OutputParameterType>(); serviceDescription.getType().setName("testServiceDesc"); serviceDescription.getType().setDescription("testDescription"); InputParameterType parameter = InputParameterType.Factory.newInstance(); parameter.setParameterName("input1"); parameter.setParameterDescription("testDesc"); ParameterType parameterType = parameter.addNewParameterType(); parameterType.setType(DataType.Enum.forString("testType")); parameterType.setName("testParamtype"); inputParameters.add(parameter); OutputParameterType outputParameter = OutputParameterType.Factory.newInstance(); outputParameter.setParameterName("input1"); outputParameter.setParameterDescription("testDesc"); ParameterType outputParaType = outputParameter.addNewParameterType(); outputParaType.setType(DataType.Enum.forString("testType")); outputParaType.setName("testParamtype"); outputParameters.add(outputParameter); serviceDescription.getType().setInputParametersArray(inputParameters.toArray(new InputParameterType[]{})); serviceDescription.getType().setOutputParametersArray(outputParameters.toArray(new OutputParameterType[]{})); registry.addServiceDescriptor(serviceDescription); assertTrue("Service desc exists", registry.isServiceDescriptorExists("testServiceDesc")); registry.removeServiceDescriptor("testServiceDesc"); } public void testAddServiceDescriptor() throws Exception { ServiceDescription serviceDescription = new ServiceDescription(); List<InputParameterType> inputParameters = new ArrayList<InputParameterType>(); List<OutputParameterType> outputParameters = new ArrayList<OutputParameterType>(); serviceDescription.getType().setName("testServiceDesc"); serviceDescription.getType().setDescription("testDescription"); InputParameterType parameter = InputParameterType.Factory.newInstance(); parameter.setParameterName("input1"); parameter.setParameterDescription("testDesc"); ParameterType parameterType = parameter.addNewParameterType(); parameterType.setType(DataType.Enum.forString("testType")); parameterType.setName("testParamtype"); inputParameters.add(parameter); OutputParameterType outputParameter = OutputParameterType.Factory.newInstance(); outputParameter.setParameterName("input1"); outputParameter.setParameterDescription("testDesc"); ParameterType outputParaType = outputParameter.addNewParameterType(); outputParaType.setType(DataType.Enum.forString("testType")); outputParaType.setName("testParamtype"); outputParameters.add(outputParameter); serviceDescription.getType().setInputParametersArray(inputParameters.toArray(new InputParameterType[]{})); serviceDescription.getType().setOutputParametersArray(outputParameters.toArray(new OutputParameterType[]{})); registry.addServiceDescriptor(serviceDescription); assertTrue("Service desc saved successfully", registry.isServiceDescriptorExists("testServiceDesc")); ServiceDescription serviceDescriptor = registry.getServiceDescriptor("testServiceDesc"); registry.removeServiceDescriptor("testServiceDesc"); } public void testUpdateServiceDescriptor() throws Exception { ServiceDescription serviceDescription = new ServiceDescription(); List<InputParameterType> inputParameters = new ArrayList<InputParameterType>(); List<OutputParameterType> outputParameters = new ArrayList<OutputParameterType>(); serviceDescription.getType().setName("testServiceDesc"); serviceDescription.getType().setDescription("testDescription1"); InputParameterType parameter = InputParameterType.Factory.newInstance(); parameter.setParameterName("input1"); parameter.setParameterDescription("testDesc"); ParameterType parameterType = parameter.addNewParameterType(); parameterType.setType(DataType.Enum.forString("testType")); parameterType.setName("testParamtype"); inputParameters.add(parameter); OutputParameterType outputParameter = OutputParameterType.Factory.newInstance(); outputParameter.setParameterName("input1"); outputParameter.setParameterDescription("testDesc"); ParameterType outputParaType = outputParameter.addNewParameterType(); outputParaType.setType(DataType.Enum.forString("testType")); outputParaType.setName("testParamtype"); outputParameters.add(outputParameter); serviceDescription.getType().setInputParametersArray(inputParameters.toArray(new InputParameterType[]{})); serviceDescription.getType().setOutputParametersArray(outputParameters.toArray(new OutputParameterType[]{})); registry.addServiceDescriptor(serviceDescription); ServiceDescription testServiceDesc = registry.getServiceDescriptor("testServiceDesc"); testServiceDesc.getType().setDescription("testDescription2"); parameter = InputParameterType.Factory.newInstance(); parameter.setParameterName("input2"); parameter.setParameterDescription("testDesc2"); parameterType = parameter.addNewParameterType(); parameterType.setType(DataType.Enum.forString("testType2")); parameterType.setName("testParamtype2"); inputParameters.add(parameter); outputParameter = OutputParameterType.Factory.newInstance(); outputParameter.setParameterName("input2"); outputParameter.setParameterDescription("testDesc2"); outputParaType = outputParameter.addNewParameterType(); outputParaType.setType(DataType.Enum.forString("testType2")); outputParaType.setName("testParamtype2"); outputParameters.add(outputParameter); testServiceDesc.getType().setInputParametersArray(inputParameters.toArray(new InputParameterType[]{})); testServiceDesc.getType().setOutputParametersArray(outputParameters.toArray(new OutputParameterType[]{})); registry.updateServiceDescriptor(testServiceDesc); assertTrue("Service updated successfully", registry.getServiceDescriptor("testServiceDesc").getType().getDescription().equals("testDescription2")); registry.removeServiceDescriptor("testServiceDesc"); } public void testGetServiceDescriptor() throws Exception { ServiceDescription serviceDescription = new ServiceDescription(); List<InputParameterType> inputParameters = new ArrayList<InputParameterType>(); List<OutputParameterType> outputParameters = new ArrayList<OutputParameterType>(); serviceDescription.getType().setName("testServiceDesc"); serviceDescription.getType().setDescription("testDescription1"); InputParameterType parameter = InputParameterType.Factory.newInstance(); parameter.setParameterName("input1"); parameter.setParameterDescription("testDesc"); ParameterType parameterType = parameter.addNewParameterType(); parameterType.setType(DataType.Enum.forString("testType")); parameterType.setName("testParamtype"); inputParameters.add(parameter); OutputParameterType outputParameter = OutputParameterType.Factory.newInstance(); outputParameter.setParameterName("input1"); outputParameter.setParameterDescription("testDesc"); ParameterType outputParaType = outputParameter.addNewParameterType(); outputParaType.setType(DataType.Enum.forString("testType")); outputParaType.setName("testParamtype"); outputParameters.add(outputParameter); serviceDescription.getType().setInputParametersArray(inputParameters.toArray(new InputParameterType[]{})); serviceDescription.getType().setOutputParametersArray(outputParameters.toArray(new OutputParameterType[]{})); registry.addServiceDescriptor(serviceDescription); ServiceDescription testServiceDesc = registry.getServiceDescriptor("testServiceDesc"); assertNotNull("service descriptor retrieved successfully", testServiceDesc); registry.removeServiceDescriptor("testServiceDesc"); } public void testRemoveServiceDescriptor() throws Exception { ServiceDescription serviceDescription = new ServiceDescription(); List<InputParameterType> inputParameters = new ArrayList<InputParameterType>(); List<OutputParameterType> outputParameters = new ArrayList<OutputParameterType>(); serviceDescription.getType().setName("testServiceDesc"); InputParameterType parameter = InputParameterType.Factory.newInstance(); parameter.setParameterName("input1"); parameter.setParameterDescription("testDesc"); ParameterType parameterType = parameter.addNewParameterType(); parameterType.setType(DataType.Enum.forString("testType")); parameterType.setName("testParamtype"); inputParameters.add(parameter); OutputParameterType outputParameter = OutputParameterType.Factory.newInstance(); outputParameter.setParameterName("input1"); outputParameter.setParameterDescription("testDesc"); ParameterType outputParaType = outputParameter.addNewParameterType(); outputParaType.setType(DataType.Enum.forString("testType")); outputParaType.setName("testParamtype"); outputParameters.add(outputParameter); serviceDescription.getType().setInputParametersArray(inputParameters.toArray(new InputParameterType[]{})); serviceDescription.getType().setOutputParametersArray(outputParameters.toArray(new OutputParameterType[]{})); registry.addServiceDescriptor(serviceDescription); registry.removeServiceDescriptor("testServiceDesc"); assertFalse("Service desc removed successfully", registry.isServiceDescriptorExists("testServiceDesc")); } public void testGetServiceDescriptors() throws Exception { ServiceDescription serviceDescription = new ServiceDescription(); List<InputParameterType> inputParameters = new ArrayList<InputParameterType>(); List<OutputParameterType> outputParameters = new ArrayList<OutputParameterType>(); serviceDescription.getType().setName("testServiceDesc"); InputParameterType parameter = InputParameterType.Factory.newInstance(); parameter.setParameterName("input1"); parameter.setParameterDescription("testDesc"); ParameterType parameterType = parameter.addNewParameterType(); parameterType.setType(DataType.Enum.forString("testType")); parameterType.setName("testParamtype"); inputParameters.add(parameter); OutputParameterType outputParameter = OutputParameterType.Factory.newInstance(); outputParameter.setParameterName("input1"); outputParameter.setParameterDescription("testDesc"); ParameterType outputParaType = outputParameter.addNewParameterType(); outputParaType.setType(DataType.Enum.forString("testType")); outputParaType.setName("testParamtype"); outputParameters.add(outputParameter); serviceDescription.getType().setInputParametersArray(inputParameters.toArray(new InputParameterType[]{})); serviceDescription.getType().setOutputParametersArray(outputParameters.toArray(new OutputParameterType[]{})); registry.addServiceDescriptor(serviceDescription); List<ServiceDescription> serviceDescriptors = registry.getServiceDescriptors(); assertTrue("Service desc retrieved successfully", serviceDescriptors.size() == 1); registry.removeServiceDescriptor("testServiceDesc"); } public void testIsApplicationDescriptorExists() throws Exception { ApplicationDescription applicationDescription = new ApplicationDescription(ApplicationDeploymentDescriptionType.type); ApplicationDeploymentDescriptionType.ApplicationName applicationName = applicationDescription.getType().addNewApplicationName(); applicationName.setStringValue("testApplication"); applicationDescription.getType().setApplicationName(applicationName); applicationDescription.getType().setInputDataDirectory("/bin"); applicationDescription.getType().setExecutableLocation("/bin/echo"); applicationDescription.getType().setOutputDataDirectory("/tmp"); registry.addApplicationDescriptor("testService", "testHost", applicationDescription); assertTrue("application descriptor exists", registry.isApplicationDescriptorExists("testService", "testHost", "testApplication")); registry.removeApplicationDescriptor("testService", "testHost", "testApplication"); } public void testAddApplicationDescriptorWithOtherDescriptors() throws Exception { ApplicationDescription applicationDescription = new ApplicationDescription(ApplicationDeploymentDescriptionType.type); ApplicationDeploymentDescriptionType.ApplicationName applicationName = applicationDescription.getType().addNewApplicationName(); applicationName.setStringValue("testApplication"); applicationDescription.getType().setApplicationName(applicationName); applicationDescription.getType().setInputDataDirectory("/bin"); applicationDescription.getType().setExecutableLocation("/bin/echo"); applicationDescription.getType().setOutputDataDirectory("/tmp"); HostDescription hostDescription = new HostDescription(GlobusHostType.type); hostDescription.getType().setHostName("testHost"); hostDescription.getType().setHostAddress("testHostAddress"); ServiceDescription serviceDescription = new ServiceDescription(); List<InputParameterType> inputParameters = new ArrayList<InputParameterType>(); List<OutputParameterType> outputParameters = new ArrayList<OutputParameterType>(); serviceDescription.getType().setName("testServiceDesc"); InputParameterType parameter = InputParameterType.Factory.newInstance(); parameter.setParameterName("input1"); parameter.setParameterDescription("testDesc"); ParameterType parameterType = parameter.addNewParameterType(); parameterType.setType(DataType.Enum.forString("testType")); parameterType.setName("testParamtype"); inputParameters.add(parameter); OutputParameterType outputParameter = OutputParameterType.Factory.newInstance(); outputParameter.setParameterName("input1"); outputParameter.setParameterDescription("testDesc"); ParameterType outputParaType = outputParameter.addNewParameterType(); outputParaType.setType(DataType.Enum.forString("testType")); outputParaType.setName("testParamtype"); outputParameters.add(outputParameter); serviceDescription.getType().setInputParametersArray(inputParameters.toArray(new InputParameterType[]{})); serviceDescription.getType().setOutputParametersArray(outputParameters.toArray(new OutputParameterType[]{})); registry.addApplicationDescriptor(serviceDescription, hostDescription, applicationDescription); assertTrue("application hostDescription added successfully", registry.isApplicationDescriptorExists("testServiceDesc", "testHost", "testApplication")); registry.removeApplicationDescriptor("testServiceDesc", "testHost", "testApplication"); } public void testAddApplicationDescriptor() throws Exception { ApplicationDescription applicationDescription = new ApplicationDescription(ApplicationDeploymentDescriptionType.type); ApplicationDeploymentDescriptionType.ApplicationName applicationName = applicationDescription.getType().addNewApplicationName(); applicationName.setStringValue("testApplication"); applicationDescription.getType().setApplicationName(applicationName); applicationDescription.getType().setInputDataDirectory("/bin"); applicationDescription.getType().setExecutableLocation("/bin/echo"); applicationDescription.getType().setOutputDataDirectory("/tmp"); registry.addApplicationDescriptor("testService", "testHost", applicationDescription); assertTrue("application descriptor added successfully", registry.isApplicationDescriptorExists("testService", "testHost", "testApplication")); registry.removeApplicationDescriptor("testService", "testHost", "testApplication"); } public void testUpdateApplicationDescriptorWithOtherDescriptors() throws Exception { ApplicationDescription applicationDescription = new ApplicationDescription(ApplicationDeploymentDescriptionType.type); ApplicationDeploymentDescriptionType.ApplicationName applicationName = applicationDescription.getType().addNewApplicationName(); applicationName.setStringValue("testApplication"); applicationDescription.getType().setApplicationName(applicationName); applicationDescription.getType().setInputDataDirectory("/bin"); applicationDescription.getType().setExecutableLocation("/bin/echo"); applicationDescription.getType().setOutputDataDirectory("/tmp"); HostDescription hostDescription = new HostDescription(GlobusHostType.type); hostDescription.getType().setHostName("testHost"); hostDescription.getType().setHostAddress("testHostAddress"); ServiceDescription serviceDescription = new ServiceDescription(); List<InputParameterType> inputParameters = new ArrayList<InputParameterType>(); List<OutputParameterType> outputParameters = new ArrayList<OutputParameterType>(); serviceDescription.getType().setName("testServiceDesc"); InputParameterType parameter = InputParameterType.Factory.newInstance(); parameter.setParameterName("input1"); parameter.setParameterDescription("testDesc"); ParameterType parameterType = parameter.addNewParameterType(); parameterType.setType(DataType.Enum.forString("testType")); parameterType.setName("testParamtype"); inputParameters.add(parameter); OutputParameterType outputParameter = OutputParameterType.Factory.newInstance(); outputParameter.setParameterName("input1"); outputParameter.setParameterDescription("testDesc"); ParameterType outputParaType = outputParameter.addNewParameterType(); outputParaType.setType(DataType.Enum.forString("testType")); outputParaType.setName("testParamtype"); outputParameters.add(outputParameter); serviceDescription.getType().setInputParametersArray(inputParameters.toArray(new InputParameterType[]{})); serviceDescription.getType().setOutputParametersArray(outputParameters.toArray(new OutputParameterType[]{})); registry.addApplicationDescriptor(serviceDescription, hostDescription, applicationDescription); ApplicationDescription applicationDescriptor = registry.getApplicationDescriptor("testServiceDesc", "testHost", "testApplication"); applicationDescriptor.getType().setExecutableLocation("/bin/echo1"); registry.udpateApplicationDescriptor(serviceDescription, hostDescription, applicationDescriptor); ApplicationDescription descriptor = registry.getApplicationDescriptor("testServiceDesc", "testHost", "testApplication"); String executableLocation = descriptor.getType().getExecutableLocation(); assertTrue("application descriptor updated successfully", executableLocation.equals("/bin/echo1")); registry.removeApplicationDescriptor("testServiceDesc", "testHost", "testApplication"); } public void testUpdateApplicationDescriptor() throws Exception { ApplicationDescription applicationDescription = new ApplicationDescription(ApplicationDeploymentDescriptionType.type); ApplicationDeploymentDescriptionType.ApplicationName applicationName = applicationDescription.getType().addNewApplicationName(); applicationName.setStringValue("testApplication"); applicationDescription.getType().setApplicationName(applicationName); applicationDescription.getType().setInputDataDirectory("/bin"); applicationDescription.getType().setExecutableLocation("/bin/echo"); applicationDescription.getType().setOutputDataDirectory("/tmp"); registry.addApplicationDescriptor("testService", "testHost", applicationDescription); ApplicationDescription applicationDescriptor = registry.getApplicationDescriptor("testService", "testHost", "testApplication"); applicationDescriptor.getType().setExecutableLocation("/bin/echo1"); registry.updateApplicationDescriptor("testService", "testHost", applicationDescriptor); ApplicationDescription descriptor = registry.getApplicationDescriptor("testService", "testHost", "testApplication"); String executableLocation = descriptor.getType().getExecutableLocation(); assertTrue("application descriptor updated successfully", executableLocation.equals("/bin/echo1")); registry.removeApplicationDescriptor("testService", "testHost", "testApplication"); } public void testGetApplicationDescriptor() throws Exception { ApplicationDescription applicationDescription = new ApplicationDescription(ApplicationDeploymentDescriptionType.type); ApplicationDeploymentDescriptionType.ApplicationName applicationName = applicationDescription.getType().addNewApplicationName(); applicationName.setStringValue("testApplication"); applicationDescription.getType().setApplicationName(applicationName); applicationDescription.getType().setInputDataDirectory("/bin"); applicationDescription.getType().setExecutableLocation("/bin/echo"); applicationDescription.getType().setOutputDataDirectory("/tmp"); registry.addApplicationDescriptor("testService", "testHost", applicationDescription); ApplicationDescription applicationDescriptor = registry.getApplicationDescriptor("testService", "testHost", "testApplication"); applicationDescriptor.getType().setExecutableLocation("/bin/echo1"); registry.updateApplicationDescriptor("testService", "testHost", applicationDescriptor); ApplicationDescription descriptor = registry.getApplicationDescriptor("testService", "testHost", "testApplication"); assertNotNull("application descriptor retrieved successfully", descriptor); registry.removeApplicationDescriptor("testService", "testHost", "testApplication"); } public void testGetApplicationDescriptorsForServiceAndHost() throws Exception { ApplicationDescription applicationDescription = new ApplicationDescription(ApplicationDeploymentDescriptionType.type); ApplicationDeploymentDescriptionType.ApplicationName applicationName = applicationDescription.getType().addNewApplicationName(); applicationName.setStringValue("testApplication"); applicationDescription.getType().setApplicationName(applicationName); applicationDescription.getType().setInputDataDirectory("/bin"); applicationDescription.getType().setExecutableLocation("/bin/echo"); applicationDescription.getType().setOutputDataDirectory("/tmp"); registry.addApplicationDescriptor("testService", "testHost", applicationDescription); ApplicationDescription description = registry.getApplicationDescriptors("testService", "testHost"); assertNotNull("application descriptor retrieved successfully", description); registry.removeApplicationDescriptor("testService", "testHost", "testApplication"); } public void testGetApplicationDescriptorsForService() throws Exception { ApplicationDescription applicationDescription = new ApplicationDescription(ApplicationDeploymentDescriptionType.type); ApplicationDeploymentDescriptionType.ApplicationName applicationName = applicationDescription.getType().addNewApplicationName(); applicationName.setStringValue("testApplication"); applicationDescription.getType().setApplicationName(applicationName); applicationDescription.getType().setInputDataDirectory("/bin"); applicationDescription.getType().setExecutableLocation("/bin/echo"); applicationDescription.getType().setOutputDataDirectory("/tmp"); registry.addApplicationDescriptor("testService", "testHost1", applicationDescription); registry.addApplicationDescriptor("testService", "testHost2", applicationDescription); Map<String,ApplicationDescription> applicationDescriptors = registry.getApplicationDescriptors("testService"); assertTrue("application retrieved successfully", applicationDescriptors.size()==2); registry.removeApplicationDescriptor("testService", "testHost1", "testApplication"); registry.removeApplicationDescriptor("testService", "testHost2", "testApplication"); } public void testGetApplicationDescriptors() throws Exception { ApplicationDescription applicationDescription = new ApplicationDescription(ApplicationDeploymentDescriptionType.type); ApplicationDeploymentDescriptionType.ApplicationName applicationName = applicationDescription.getType().addNewApplicationName(); applicationName.setStringValue("testApplication"); applicationDescription.getType().setApplicationName(applicationName); applicationDescription.getType().setInputDataDirectory("/bin"); applicationDescription.getType().setExecutableLocation("/bin/echo"); applicationDescription.getType().setOutputDataDirectory("/tmp"); registry.addApplicationDescriptor("testService", "testHost1", applicationDescription); registry.addApplicationDescriptor("testService", "testHost2", applicationDescription); Map<String[], ApplicationDescription> applicationDescriptors = registry.getApplicationDescriptors(); assertTrue("application retrieved successfully", applicationDescriptors.size()==2); registry.removeApplicationDescriptor("testService", "testHost1", "testApplication"); registry.removeApplicationDescriptor("testService", "testHost2", "testApplication"); } public void testRemoveApplicationDescriptor() throws Exception { ApplicationDescription applicationDescription = new ApplicationDescription(ApplicationDeploymentDescriptionType.type); ApplicationDeploymentDescriptionType.ApplicationName applicationName = applicationDescription.getType().addNewApplicationName(); applicationName.setStringValue("testApplication"); applicationDescription.getType().setApplicationName(applicationName); applicationDescription.getType().setInputDataDirectory("/bin"); applicationDescription.getType().setExecutableLocation("/bin/echo"); applicationDescription.getType().setOutputDataDirectory("/tmp"); registry.addApplicationDescriptor("testService", "testHost", applicationDescription); registry.removeApplicationDescriptor("testService", "testHost", "testApplication"); assertFalse("application descriptor removed successfully", registry.isApplicationDescriptorExists("testService", "testHost", "testApplication")); } public void testIsWorkspaceProjectExists() throws Exception { WorkspaceProject workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); assertTrue("workspace project exists", registry.isWorkspaceProjectExists("testProject")); registry.deleteWorkspaceProject("testProject"); } public void testAddWorkspaceProject() throws Exception { WorkspaceProject workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); assertTrue("workspace project added successfully", registry.isWorkspaceProjectExists("testProject")); registry.deleteWorkspaceProject("testProject"); } // public void testUpdateWorkspaceProject() throws Exception { // WorkspaceProject workspaceProject = new WorkspaceProject("testProject", registry); // registry.addWorkspaceProject(workspaceProject); // WorkspaceProject testProject = registry.getWorkspaceProject("testProject"); // testProject.setProjectName("testProject2"); // // registry.updateWorkspaceProject(testProject); // // assertTrue("workspace project updated", registry.isWorkspaceProjectExists("testProject2")); // registry.deleteWorkspaceProject("testProject2"); // } public void testDeleteWorkspaceProject() throws Exception { WorkspaceProject workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); registry.deleteWorkspaceProject("testProject"); assertFalse("workspace project deleted successfully", registry.isWorkspaceProjectExists("testProject")); } public void testGetWorkspaceProject() throws Exception { WorkspaceProject workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); WorkspaceProject testProject = registry.getWorkspaceProject("testProject"); assertNotNull("workspace project retrieved successfully", testProject); registry.deleteWorkspaceProject("testProject"); } public void testGetWorkspaceProjects() throws Exception { WorkspaceProject workspaceProject1 = new WorkspaceProject("testProject1", registry); registry.addWorkspaceProject(workspaceProject1); WorkspaceProject workspaceProject2 = new WorkspaceProject("testProject2", registry); registry.addWorkspaceProject(workspaceProject2); List<WorkspaceProject> workspaceProjects = registry.getWorkspaceProjects(); assertTrue("workspace projects retrieved successfully", workspaceProjects.size() == 2); registry.deleteWorkspaceProject("testProject1"); registry.deleteWorkspaceProject("testProject2"); } public void testAddExperiment() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExperiment"); registry.addExperiment("testProject", experiment); ExperimentData testExperiment = registry.getExperiment("testExperiment"); String user = testExperiment.getUser(); assertTrue("experiment saved successfully", registry.isExperimentExists("testExperiment")); registry.removeExperiment("testExperiment"); registry.deleteWorkspaceProject("testProject"); } public void testRemoveExperiment() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExperiment"); registry.addExperiment("testProject", experiment); registry.removeExperiment("testExperiment"); assertFalse("experiment removed successfully", registry.isExperimentExists("testExperiment")); registry.deleteWorkspaceProject("testProject"); } // public void testGetExperiments() throws Exception { // WorkspaceProject workspaceProject = null; // if(!registry.isWorkspaceProjectExists("testProject")) { // workspaceProject = new WorkspaceProject("testProject", registry); // registry.addWorkspaceProject(workspaceProject); // } // AiravataExperiment experiment1 = new AiravataExperiment(); // experiment1.setExperimentId("testExperiment1"); // Calendar calender = Calendar.getInstance(); // java.util.Date d = calender.getTime(); // Date currentTime = new Date(d.getTime()); // experiment1.setSubmittedDate(currentTime); // registry.addExperiment("testProject", experiment1); // // AiravataExperiment experiment2 = new AiravataExperiment(); // experiment2.setExperimentId("testExperiment2"); // experiment2.setSubmittedDate(currentTime); // registry.addExperiment("testProject", experiment2); // // List<AiravataExperiment> experiments = registry.getExperiments(); // // assertTrue("experiments retrieved successfully", experiments.size() == 2); // registry.removeExperiment("testExperiment1"); // registry.removeExperiment("testExperiment2"); // registry.deleteWorkspaceProject("testProject"); // } // public void testGetExperimentsForProject() throws Exception { // WorkspaceProject workspaceProject = null; // if(!registry.isWorkspaceProjectExists("testProject")) { // workspaceProject = new WorkspaceProject("testProject", registry); // registry.addWorkspaceProject(workspaceProject); // } // AiravataExperiment experiment1 = new AiravataExperiment(); // experiment1.setExperimentId("testExperiment1"); // experiment1.setProject(workspaceProject); // Calendar calender = Calendar.getInstance(); // java.util.Date d = calender.getTime(); // Date currentTime = new Date(d.getTime()); // experiment1.setSubmittedDate(currentTime); // registry.addExperiment("testProject", experiment1); // // AiravataExperiment experiment2 = new AiravataExperiment(); // experiment2.setExperimentId("testExperiment2"); // experiment2.setSubmittedDate(currentTime); // experiment2.setProject(workspaceProject); // registry.addExperiment("testProject", experiment2); // // List<AiravataExperiment> experiments = registry.getExperiments("testProject"); // // assertTrue("experiments retrieved successfully", experiments.size() == 2); // registry.removeExperiment("testExperiment1"); // registry.removeExperiment("testExperiment2"); // registry.deleteWorkspaceProject("testProject"); // } // public void testGetExperimentsDuringPeriod() throws Exception { // WorkspaceProject workspaceProject = null; // if(!registry.isWorkspaceProjectExists("testProject")) { // workspaceProject = new WorkspaceProject("testProject", registry); // registry.addWorkspaceProject(workspaceProject); // } // AiravataExperiment experiment1 = new AiravataExperiment(); // experiment1.setExperimentId("testExperiment1"); // Calendar calender = Calendar.getInstance(); // calender.set(Calendar.YEAR, 2012); // calender.set(Calendar.MONTH, Calendar.JANUARY); // calender.set(Calendar.DATE, 2); // java.util.Date d = calender.getTime(); // Date currentTime = new Date(d.getTime()); // experiment1.setSubmittedDate(currentTime); // experiment1.setProject(workspaceProject); // registry.addExperiment("testProject", experiment1); // // AiravataExperiment experiment2 = new AiravataExperiment(); // experiment2.setExperimentId("testExperiment2"); // Calendar c = Calendar.getInstance(); // java.util.Date date = c.getTime(); // Date experiment2Time = new Date(date.getTime()); // experiment2.setSubmittedDate(experiment2Time); // experiment2.setProject(workspaceProject); // registry.addExperiment("testProject", experiment2); // // Calendar a = Calendar.getInstance(); // a.set(Calendar.YEAR, 2012); // a.set(Calendar.MONTH, Calendar.JANUARY); // a.set(Calendar.DATE, 1); // java.util.Date da = a.getTime(); // Date ct = new Date(da.getTime()); // // Calendar aa = Calendar.getInstance(); // aa.set(Calendar.YEAR, 2012); // aa.set(Calendar.MONTH, Calendar.DECEMBER); // aa.set(Calendar.DATE, 1); // java.util.Date dda = aa.getTime(); // // List<AiravataExperiment> experiments = registry.getExperiments(ct, dda); // // assertTrue("experiments retrieved successfully", experiments.size() != 0); // registry.removeExperiment("testExperiment1"); // registry.removeExperiment("testExperiment2"); // registry.deleteWorkspaceProject("testProject"); // // } // public void testGetExperimentsPerProjectDuringPeriod() throws Exception { // WorkspaceProject workspaceProject = null; // if(!registry.isWorkspaceProjectExists("testProject")) { // workspaceProject = new WorkspaceProject("testProject", registry); // registry.addWorkspaceProject(workspaceProject); // } // AiravataExperiment experiment1 = new AiravataExperiment(); // experiment1.setExperimentId("testExperiment1"); // Calendar calender = Calendar.getInstance(); // calender.set(Calendar.YEAR, 2012); // calender.set(Calendar.MONTH, Calendar.JANUARY); // calender.set(Calendar.DATE, 2); // java.util.Date d = calender.getTime(); // Date currentTime = new Date(d.getTime()); // experiment1.setSubmittedDate(currentTime); // registry.addExperiment("testProject", experiment1); // // AiravataExperiment experiment2 = new AiravataExperiment(); // experiment2.setExperimentId("testExperiment2"); // Calendar c = Calendar.getInstance(); // java.util.Date date = c.getTime(); // Date experiment2Time = new Date(date.getTime()); // experiment2.setSubmittedDate(experiment2Time); // registry.addExperiment("testProject", experiment2); // // Calendar a = Calendar.getInstance(); // a.set(Calendar.YEAR, 2012); // a.set(Calendar.MONTH, Calendar.JANUARY); // a.set(Calendar.DATE, 1); // java.util.Date da = a.getTime(); // Date ct = new Date(da.getTime()); // // Calendar aa = Calendar.getInstance(); // aa.set(Calendar.YEAR, 2012); // aa.set(Calendar.MONTH, Calendar.DECEMBER); // aa.set(Calendar.DATE, 1); // java.util.Date dda = aa.getTime(); // // List<AiravataExperiment> experiments = registry.getExperiments("testProject", ct, dda); // // assertTrue("experiments retrieved successfully", experiments.size() == 2); // registry.removeExperiment("testExperiment1"); // registry.removeExperiment("testExperiment2"); // registry.deleteWorkspaceProject("testProject"); // // } public void testIsExperimentExists() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExperiment"); registry.addExperiment("testProject", experiment); assertTrue("experiment exists", registry.isExperimentExists("testExperiment")); registry.removeExperiment("testExperiment"); registry.deleteWorkspaceProject("testProject"); } public void testUpdateExperimentExecutionUser() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExperiment"); registry.addExperiment("testProject", experiment); registry.updateExperimentExecutionUser("testExperiment", "testUser"); ExperimentData testExperiment = registry.getExperiment("testExperiment"); assertTrue("execution user updated successfully", testExperiment.getUser().equals("testUser")); registry.removeExperiment("testExperiment"); registry.deleteWorkspaceProject("testProject"); } public void testGetExperimentExecutionUser() throws Exception { Calendar c = Calendar.getInstance(); java.util.Date date = c.getTime(); Date currentTime = new Date(date.getTime()); WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); experiment.setSubmittedDate(currentTime); registry.addExperiment("testProject", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); ExperimentData testExperiment = registry.getExperiment("testExp"); assertTrue("execution user retrieved successfully", testExperiment.getUser().equals("admin")); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject"); } public void testGetExperimentName() throws Exception { Calendar c = Calendar.getInstance(); java.util.Date date = c.getTime(); Date currentTime = new Date(date.getTime()); WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); experiment.setSubmittedDate(currentTime); registry.addExperiment("testProject", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testExperiment"); ExperimentData testExperiment = registry.getExperiment("testExp"); assertTrue("experiment name retrieved successfully", testExperiment.getExperimentName().equals("testExperiment")); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject"); } public void testUpdateExperimentName() throws Exception { Calendar c = Calendar.getInstance(); java.util.Date date = c.getTime(); Date currentTime = new Date(date.getTime()); WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); experiment.setSubmittedDate(currentTime); registry.addExperiment("testProject", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testExperiment"); ExperimentData testExperiment = registry.getExperiment("testExp"); assertTrue("experiment name updated successfully", testExperiment.getExperimentName().equals("testExperiment")); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject"); } public void testGetExperimentMetadata() throws Exception { Calendar c = Calendar.getInstance(); java.util.Date date = c.getTime(); Date currentTime = new Date(date.getTime()); WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); experiment.setSubmittedDate(currentTime); registry.addExperiment("testProject", experiment); registry.updateExperimentMetadata("testExp", "testMetadata"); assertTrue("experiment metadata retrieved successfully", registry.getExperimentMetadata("testExp").equals("testMetadata")); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject"); } public void testUpdateExperimentMetadata() throws Exception { Calendar c = Calendar.getInstance(); java.util.Date date = c.getTime(); Date currentTime = new Date(date.getTime()); WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); experiment.setSubmittedDate(currentTime); registry.addExperiment("testProject", experiment); registry.updateExperimentMetadata("testExp", "testMetadata"); assertTrue("experiment metadata updated successfully", registry.getExperimentMetadata("testExp").equals("testMetadata")); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject"); } public void testGetWorkflowExecutionTemplateName() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); registry.addExperiment("testProject", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testexperiment"); ExperimentData experimentData = registry.getExperiment("testExp"); registry.addWorkflowInstance("testExp", "testWorkflow1", "template1"); String testWorkflow = registry.getWorkflowExecutionTemplateName("testWorkflow1"); assertTrue("workflow execution template name retrieved successfully", testWorkflow.equals("template1")); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject"); } public void testSetWorkflowInstanceTemplateName() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); registry.addExperiment("testProject", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testexperiment"); ExperimentData experimentData = registry.getExperiment("testExp"); registry.addWorkflowInstance("testExp", "testWorkflow2", "template1"); registry.setWorkflowInstanceTemplateName("testWorkflow2", "template2"); String testWorkflow = registry.getWorkflowExecutionTemplateName("testWorkflow2"); assertTrue("workflow execution template name retrieved successfully", testWorkflow.equals("template2")); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject"); } public void testGetExperimentWorkflowInstances() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); registry.addExperiment("testProject", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testexperiment"); registry.addWorkflowInstance("testExp", "testWorkflow3", "template1"); List<WorkflowExecution> workflowInstances = registry.getExperimentWorkflowInstances("testExp"); assertTrue("workflow instances retrieved successfully", workflowInstances.size() != 0); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject"); } public void testIsWorkflowInstanceExists() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); registry.addExperiment("testProject", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testexperiment"); registry.addWorkflowInstance("testExp", "testWorkflow4", "template1"); assertTrue("workflow instance exists", registry.isWorkflowInstanceExists("testWorkflow4")); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject"); } public void testUpdateWorkflowInstanceStatus() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject")) { workspaceProject = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); registry.addExperiment("testProject", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testexperiment"); registry.addWorkflowInstance("testExp", "testWorkflow5", "template1"); registry.updateWorkflowInstanceStatus("testWorkflow5", WorkflowExecutionStatus.State.STARTED); assertTrue("workflow instance status updated successfully", registry.getWorkflowInstanceStatus("testWorkflow5").getExecutionStatus().equals(WorkflowExecutionStatus.State.STARTED)); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject"); } public void testGetWorkflowInstanceStatus() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject1")) { workspaceProject = new WorkspaceProject("testProject1", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); registry.addExperiment("testProject1", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testexperiment"); registry.addWorkflowInstance("testExp", "testWorkflow6", "template1"); Calendar c = Calendar.getInstance(); java.util.Date date = c.getTime(); Date currentTime = new Date(date.getTime()); registry.updateWorkflowInstanceStatus(new WorkflowExecutionStatus(new WorkflowExecution("testExp", "testWorkflow6"), WorkflowExecutionStatus.State.STARTED,currentTime)); assertTrue("workflow instance status updated successfully", registry.getWorkflowInstanceStatus("testWorkflow6").getExecutionStatus().equals(WorkflowExecutionStatus.State.STARTED)); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject1"); } public void testUpdateWorkflowNodeInput() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject1")) { workspaceProject = new WorkspaceProject("testProject1", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); registry.addExperiment("testProject1", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testexperiment"); registry.addWorkflowInstance("testExp", "testWorkflow7", "template1"); WorkflowInstanceNode workflowInstanceNode = new WorkflowInstanceNode(new WorkflowExecution("testExp", "testWorkflow7"), "testNode"); WorkflowNodeType nodeType = new WorkflowNodeType(WorkflowNodeType.WorkflowNode.INPUTNODE); registry.updateWorkflowNodeType(workflowInstanceNode, nodeType); registry.updateWorkflowNodeInput(workflowInstanceNode, "testParameter=testData"); NodeExecutionData nodeData = registry.getWorkflowInstanceNodeData("testWorkflow7", "testNode"); assertTrue("workflow instance node input saved successfully", nodeData.getInput().equals("testParameter=testData")); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject1"); } public void testUpdateWorkflowNodeOutput() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject1")) { workspaceProject = new WorkspaceProject("testProject1", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); registry.addExperiment("testProject1", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testexperiment"); registry.addWorkflowInstance("testExp", "testWorkflow8", "template1"); WorkflowInstanceNode workflowInstanceNode = new WorkflowInstanceNode(new WorkflowExecution("testExp", "testWorkflow8"), "testNode"); registry.updateWorkflowNodeOutput(workflowInstanceNode, "testData"); NodeExecutionData nodeData = registry.getWorkflowInstanceNodeData("testWorkflow8", "testNode"); assertTrue("workflow instance node output saved successfully", nodeData.getOutput().equals("testData")); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject1"); } public void testGetExperiment() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject1")) { workspaceProject = new WorkspaceProject("testProject1", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); registry.addExperiment("testProject1", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testexperiment"); registry.addWorkflowInstance("testExp", "testWorkflow9", "template1"); ExperimentData testExp = registry.getExperiment("testExp"); assertNotNull("experiment data retrieved successfully", testExp); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject1"); } public void testGetExperimentMetaInformation() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject1")) { workspaceProject = new WorkspaceProject("testProject1", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); registry.addExperiment("testProject1", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testexperiment"); registry.addWorkflowInstance("testExp", "testWorkflow10", "template1"); ExperimentData testExp = registry.getExperimentMetaInformation("testExp"); assertNotNull("experiment data retrieved successfully", testExp); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject1"); } public void testGetAllExperimentMetaInformation() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject1")) { workspaceProject = new WorkspaceProject("testProject1", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); registry.addExperiment("testProject1", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testexperiment"); registry.addWorkflowInstance("testExp", "testWorkflow11", "template1"); ExperimentData testExp = registry.getExperimentMetaInformation("testExp"); assertNotNull("experiment data retrieved successfully", testExp); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject1"); } public void testGetExperimentIdByUser() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject1")) { workspaceProject = new WorkspaceProject("testProject1", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment1 = new AiravataExperiment(); experiment1.setExperimentId("testExp1"); registry.addExperiment("testProject1", experiment1); AiravataExperiment experiment2 = new AiravataExperiment(); experiment2.setExperimentId("testExp2"); registry.addExperiment("testProject1", experiment2); registry.updateExperimentExecutionUser("testExp1", "admin"); registry.updateExperimentExecutionUser("testExp2", "admin"); registry.updateExperimentName("testExp1", "testexperiment1"); registry.updateExperimentName("testExp2", "testexperiment2"); registry.addWorkflowInstance("testExp1", "testWorkflow12", "template1"); registry.addWorkflowInstance("testExp2", "testWorkflow13", "template2"); List<String> experimentIdByUser = registry.getExperimentIdByUser("admin"); assertNotNull("experiment ID s for user retrieved successfully", experimentIdByUser.size() != 0); registry.removeExperiment("testExp1"); registry.removeExperiment("testExp2"); registry.deleteWorkspaceProject("testProject1"); } public void testGetExperimentByUser() throws Exception { WorkspaceProject workspaceProject = null; if(!registry.isWorkspaceProjectExists("testProject1")) { workspaceProject = new WorkspaceProject("testProject1", registry); registry.addWorkspaceProject(workspaceProject); } AiravataExperiment experiment1 = new AiravataExperiment(); experiment1.setExperimentId("testExp1"); registry.addExperiment("testProject1", experiment1); AiravataExperiment experiment2 = new AiravataExperiment(); experiment2.setExperimentId("testExp2"); registry.addExperiment("testProject1", experiment2); registry.updateExperimentExecutionUser("testExp1", "admin"); registry.updateExperimentExecutionUser("testExp2", "admin"); registry.updateExperimentName("testExp1", "testexperiment1"); registry.updateExperimentName("testExp2", "testexperiment2"); registry.addWorkflowInstance("testExp1", "testWorkflow14", "template1"); registry.addWorkflowInstance("testExp2", "testWorkflow15", "template2"); List<ExperimentData> experimentDataList = registry.getExperimentByUser("admin"); assertNotNull("experiment ID s for user retrieved successfully", experimentDataList.size() != 0); registry.removeExperiment("testExp1"); registry.removeExperiment("testExp2"); registry.deleteWorkspaceProject("testProject1"); } // public void testUpdateWorkflowNodeStatus() throws Exception { // WorkspaceProject workspaceProject1 = new WorkspaceProject("testProject", registry); // registry.addWorkspaceProject(workspaceProject1); // AiravataExperiment experiment = new AiravataExperiment(); // experiment.setExperimentId("testExp"); // registry.addExperiment("testProject", experiment); // // registry.updateExperimentExecutionUser("testExp", "admin"); // registry.updateExperimentName("testExp", "testexperiment"); // // registry.addWorkflowInstance("testExp", "testWorkflow", "template1"); // // // // WorkflowNodeType workflowNodeType = new WorkflowNodeType(); // workflowNodeType.setNodeType(WorkflowNodeType.WorkflowNode.SERVICENODE); // // WorkflowInstanceNode node = new WorkflowInstanceNode(new WorkflowInstance("testExp", "testWorkflow"), "testNode"); // registry.addWorkflowInstanceNode("testWorkflow", "testNode"); // // WorkflowInstanceData workflowInstanceData = registry.getWorkflowInstanceData("testWorkflow"); // WorkflowInstanceNodeData workflowInstanceNodeData = registry.getWorkflowInstanceNodeData("testWorkflow", "testNode"); // // Calendar c = Calendar.getInstance(); // java.util.Date date = c.getTime(); // Date currentTime = new Date(date.getTime()); // // workflowInstanceNodeData.setStatus(WorkflowInstanceStatus.ExecutionStatus.FINISHED, currentTime); // workflowInstanceData.addNodeData(workflowInstanceNodeData); // // registry.updateWorkflowNodeOutput(node, "testData"); // registry.updateWorkflowNodeType(node,workflowNodeType); // // registry.updateWorkflowNodeStatus("testWorkflow", "testNode", WorkflowInstanceStatus.ExecutionStatus.FINISHED); // // WorkflowInstanceNodeStatus workflowNodeStatus = registry.getWorkflowNodeStatus(node); // // assertTrue("workflow instance node status updated successfully", workflowNodeStatus.getExecutionStatus().equals(WorkflowInstanceStatus.ExecutionStatus.FINISHED)); // // registry.removeExperiment("testExp"); // registry.deleteWorkspaceProject("testProject"); // // } /* public void testGetWorkflowNodeStatus() throws Exception { WorkspaceProject workspaceProject1 = new WorkspaceProject("testProject", registry); registry.addWorkspaceProject(workspaceProject1); AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId("testExp"); registry.addExperiment("testProject", experiment); registry.updateExperimentExecutionUser("testExp", "admin"); registry.updateExperimentName("testExp", "testexperiment"); registry.addWorkflowInstance("testExp", "testWorkflow", "template1"); WorkflowInstanceNode workflowInstanceNode = new WorkflowInstanceNode(new WorkflowInstance("testExp", "testWorkflow"), "testNode"); registry.updateWorkflowNodeOutput(workflowInstanceNode, "testData"); WorkflowInstanceNodeData nodeData = registry.getWorkflowInstanceNodeData("testWorkflow", "testNode"); assertTrue("workflow instance node output saved successfully", nodeData.getOutput().equals("testData")); registry.removeExperiment("testExp"); registry.deleteWorkspaceProject("testProject"); } public void testGetWorkflowNodeStartTime() throws Exception { // WorkspaceProject workspaceProject1 = new WorkspaceProject("testProject", registry); // registry.addWorkspaceProject(workspaceProject1); // AiravataExperiment experiment = new AiravataExperiment(); // experiment.setExperimentId("testExp"); // registry.addExperiment("testProject", experiment); // // registry.updateExperimentExecutionUser("testExp", "admin"); // registry.updateExperimentName("testExp", "testexperiment"); // // registry.addWorkflowInstance("testExp", "testWorkflow", "template1"); // // WorkflowNodeType workflowNodeType = new WorkflowNodeType(); // workflowNodeType.setNodeType(WorkflowNodeType.WorkflowNode.SERVICENODE); // // WorkflowInstanceNode node = new WorkflowInstanceNode(new WorkflowInstance("testExp", "testWorkflow"), "testNode"); // registry.addWorkflowInstanceNode("testWorkflow", "testNode"); // // WorkflowInstanceData workflowInstanceData = registry.getWorkflowInstanceData("testWorkflow"); // WorkflowInstanceNodeData workflowInstanceNodeData = registry.getWorkflowInstanceNodeData("testWorkflow", "testNode"); // // Calendar c = Calendar.getInstance(); // java.util.Date date = c.getTime(); // Date currentTime = new Date(date.getTime()); // // workflowInstanceNodeData.setStatus(WorkflowInstanceStatus.ExecutionStatus.FINISHED, currentTime); // workflowInstanceData.addNodeData(workflowInstanceNodeData); // // registry.updateWorkflowNodeOutput(node, "testData"); // registry.updateWorkflowNodeType(node,workflowNodeType); // // registry.updateWorkflowNodeStatus("testWorkflow", "testNode", WorkflowInstanceStatus.ExecutionStatus.FINISHED); // // WorkflowInstanceNodeStatus workflowNodeStatus = registry.getWorkflowNodeStatus(node); // // assertTrue("workflow instance node status updated successfully", workflowNodeStatus.getExecutionStatus().equals(WorkflowInstanceStatus.ExecutionStatus.FINISHED)); // // registry.removeExperiment("testExp"); // registry.deleteWorkspaceProject("testProject"); } public void testGetWorkflowStartTime() throws Exception { } public void testUpdateWorkflowNodeGramData() throws Exception { } public void testGetWorkflowInstanceData() throws Exception { } public void testIsWorkflowInstanceNodePresent() throws Exception { } public void testGetWorkflowInstanceNodeData() throws Exception { } public void testAddWorkflowInstance() throws Exception { } public void testUpdateWorkflowNodeType() throws Exception { } public void testAddWorkflowInstanceNode() throws Exception { } */ public void testIsPublishedWorkflowExists() throws Exception { registry.addWorkflow("workflow1", "testContent"); registry.publishWorkflow("workflow1"); assertTrue("published workflow exists", registry.isPublishedWorkflowExists("workflow1")); registry.removePublishedWorkflow("workflow1"); registry.removeWorkflow("workflow1"); } public void testPublishWorkflow() throws Exception { registry.addWorkflow("workflow1", "testContent"); registry.publishWorkflow("workflow1"); assertTrue("workflow is published", registry.isPublishedWorkflowExists("workflow1")); registry.removePublishedWorkflow("workflow1"); registry.removeWorkflow("workflow1"); } public void testPublishWorkflowWithGivenName() throws Exception { registry.addWorkflow("workflow1", "testContent"); registry.publishWorkflow("workflow1", "publishedWorkflow1"); assertTrue("workflow published with given name", registry.isPublishedWorkflowExists("publishedWorkflow1")); registry.removePublishedWorkflow("publishedWorkflow1"); registry.removeWorkflow("workflow1"); } public void testGetPublishedWorkflowGraphXML() throws Exception { registry.addWorkflow("workflow1", "testContent"); registry.publishWorkflow("workflow1"); String graphXML = registry.getPublishedWorkflowGraphXML("workflow1"); assertTrue("workflow content retrieved successfully", "testContent".equals(graphXML)); registry.removePublishedWorkflow("workflow1"); registry.removeWorkflow("workflow1"); } public void testGetPublishedWorkflowNames() throws Exception { registry.addWorkflow("workflow1", "testContent"); registry.publishWorkflow("workflow1", "publishWorkflow1"); registry.publishWorkflow("workflow1", "publishWorkflow2"); List<String> publishedWorkflowNames = registry.getPublishedWorkflowNames(); assertTrue("published workflow names retrieved successfully", publishedWorkflowNames.size() == 2); registry.removePublishedWorkflow("publishWorkflow1"); registry.removePublishedWorkflow("publishWorkflow2"); registry.removeWorkflow("workflow1"); } public void testGetPublishedWorkflows() throws Exception { registry.addWorkflow("workflow1", "testContent"); registry.publishWorkflow("workflow1", "publishWorkflow1"); registry.publishWorkflow("workflow1", "publishWorkflow2"); Map<String, String> publishedWorkflows = registry.getPublishedWorkflows(); assertTrue("published workflows retrieved successfully", publishedWorkflows.size() == 2); registry.removePublishedWorkflow("publishWorkflow1"); registry.removePublishedWorkflow("publishWorkflow2"); registry.removeWorkflow("workflow1"); } public void testRemovePublishedWorkflow() throws Exception { registry.addWorkflow("workflow1", "testContent"); registry.publishWorkflow("workflow1"); registry.removePublishedWorkflow("workflow1"); assertFalse("publish workflow removed successfully", registry.isPublishedWorkflowExists("workflow1")); registry.removeWorkflow("workflow1"); } public void testIsWorkflowExists() throws Exception { registry.addWorkflow("workflow1", "testContent"); assertTrue("user workflow exists", registry.isWorkflowExists("workflow1")); registry.removeWorkflow("workflow1"); } public void testAddWorkflow() throws Exception { registry.addWorkflow("workflow1", "testContent"); assertTrue("user workflow added successfully", registry.isWorkflowExists("workflow1")); registry.removeWorkflow("workflow1"); } public void testUpdateWorkflow() throws Exception { registry.addWorkflow("workflow1", "testContent1"); registry.updateWorkflow("workflow1", "testContent2"); assertTrue("user workflow updated successfully", registry.getWorkflowGraphXML("workflow1").equals("testContent2")); registry.removeWorkflow("workflow1"); } public void testGetWorkflowGraphXML() throws Exception { registry.addWorkflow("workflow1", "testContent1"); assertTrue("user workflow graph retrieved successfully", registry.getWorkflowGraphXML("workflow1").equals("testContent1")); registry.removeWorkflow("workflow1"); } public void testGetWorkflows() throws Exception { registry.addWorkflow("workflow1", "testContent1"); registry.addWorkflow("workflow2", "testContent2"); Map<String, String> workflows = registry.getWorkflows(); assertTrue("workflows retrieved successfully", workflows.size() ==2); registry.removeWorkflow("workflow1"); registry.removeWorkflow("workflow2"); } public void testRemoveWorkflow() throws Exception { registry.addWorkflow("workflow1", "testContent"); registry.removeWorkflow("workflow1"); assertFalse("user workflow removed successfully", registry.isWorkflowExists("workflow1")); } @Override protected void tearDown() throws Exception { initialize.stopDerbyServer(); } }
9,473
0
Create_ds/airavata-sandbox/registry/airavata-registry-test/src/test/java/org/apache/airavata/registry/api/test
Create_ds/airavata-sandbox/registry/airavata-registry-test/src/test/java/org/apache/airavata/registry/api/test/util/Initialize.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.registry.api.test.util; import org.apache.airavata.common.utils.DerbyUtil; import org.apache.airavata.persistance.registry.jpa.ResourceType; import org.apache.airavata.persistance.registry.jpa.resources.GatewayResource; import org.apache.airavata.persistance.registry.jpa.resources.UserResource; import org.apache.airavata.persistance.registry.jpa.resources.Utils; import org.apache.airavata.persistance.registry.jpa.resources.WorkerResource; import org.apache.airavata.registry.api.exception.RegistrySettingsException; import org.apache.airavata.registry.api.util.RegistrySettings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.sql.*; import java.util.StringTokenizer; public class Initialize { private static final Logger logger = LoggerFactory.getLogger(Initialize.class); private static final String delimiter = ";"; public static final String PERSISTANT_DATA = "Configuration"; public static boolean checkStringBufferEndsWith(StringBuffer buffer, String suffix) { if (suffix.length() > buffer.length()) { return false; } // this loop is done on purpose to avoid memory allocation performance // problems on various JDKs // StringBuffer.lastIndexOf() was introduced in jdk 1.4 and // implementation is ok though does allocation/copying // StringBuffer.toString().endsWith() does massive memory // allocation/copying on JDK 1.5 // See http://issues.apache.org/bugzilla/show_bug.cgi?id=37169 int endIndex = suffix.length() - 1; int bufferIndex = buffer.length() - 1; while (endIndex >= 0) { if (buffer.charAt(bufferIndex) != suffix.charAt(endIndex)) { return false; } bufferIndex--; endIndex--; } return true; } public void initializeDB() { String jdbcUrl = null; String jdbcDriver = null; String jdbcUser = null; String jdbcPassword = null; try{ jdbcDriver = RegistrySettings.getSetting("registry.jdbc.driver"); jdbcUrl = RegistrySettings.getSetting("registry.jdbc.url"); jdbcUser = RegistrySettings.getSetting("registry.jdbc.user"); jdbcPassword = RegistrySettings.getSetting("registry.jdbc.password"); jdbcUrl = jdbcUrl + "?" + "user=" + jdbcUser + "&" + "password=" + jdbcPassword; } catch (RegistrySettingsException e) { logger.error("Unable to read properties" , e); } startDerbyInServerMode(); // startDerbyInEmbeddedMode(); Connection conn = null; try { Class.forName(Utils.getJDBCDriver()).newInstance(); conn = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword); if (!isDatabaseStructureCreated(PERSISTANT_DATA, conn)) { executeSQLScript(conn); logger.info("New Database created for Registry"); } else { logger.debug("Database already created for Registry!"); } } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException("Database failure"); } finally { try { if (!conn.getAutoCommit()) { conn.commit(); } conn.close(); } catch (SQLException e) { logger.error(e.getMessage(), e); e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } try{ GatewayResource gatewayResource = new GatewayResource(); gatewayResource.setGatewayName(RegistrySettings.getSetting("default.registry.gateway")); gatewayResource.setOwner(RegistrySettings.getSetting("default.registry.gateway")); gatewayResource.save(); UserResource userResource = (UserResource) gatewayResource.create(ResourceType.USER); userResource.setUserName(RegistrySettings.getSetting("default.registry.user")); userResource.setPassword(RegistrySettings.getSetting("default.registry.password")); userResource.save(); WorkerResource workerResource = (WorkerResource) gatewayResource.create(ResourceType.GATEWAY_WORKER); workerResource.setUser(userResource.getUserName()); workerResource.save(); } catch (RegistrySettingsException e) { logger.error("Unable to read properties", e); } } public static boolean isDatabaseStructureCreated(String tableName, Connection conn) { try { System.out.println("Running a query to test the database tables existence."); // check whether the tables are already created with a query Statement statement = null; try { statement = conn.createStatement(); ResultSet rs = statement.executeQuery("select * from " + tableName); if (rs != null) { rs.close(); } } finally { try { if (statement != null) { statement.close(); } } catch (SQLException e) { return false; } } } catch (SQLException e) { return false; } return true; } private void executeSQLScript(Connection conn) throws Exception { StringBuffer sql = new StringBuffer(); BufferedReader reader = null; try{ InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("data-derby.sql"); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.startsWith("//")) { continue; } if (line.startsWith("--")) { continue; } StringTokenizer st = new StringTokenizer(line); if (st.hasMoreTokens()) { String token = st.nextToken(); if ("REM".equalsIgnoreCase(token)) { continue; } } sql.append(" ").append(line); // SQL defines "--" as a comment to EOL // and in Oracle it may contain a hint // so we cannot just remove it, instead we must end it if (line.indexOf("--") >= 0) { sql.append("\n"); } if ((checkStringBufferEndsWith(sql, delimiter))) { executeSQL(sql.substring(0, sql.length() - delimiter.length()), conn); sql.replace(0, sql.length(), ""); } } // Catch any statements not followed by ; if (sql.length() > 0) { executeSQL(sql.toString(), conn); } }catch (IOException e){ logger.error("Error occurred while executing SQL script for creating Airavata database", e); throw new Exception("Error occurred while executing SQL script for creating Airavata database", e); }finally { if (reader != null) { reader.close(); } } } private static void executeSQL(String sql, Connection conn) throws Exception { // Check and ignore empty statements if ("".equals(sql.trim())) { return; } Statement statement = null; try { logger.debug("SQL : " + sql); boolean ret; int updateCount = 0, updateCountTotal = 0; statement = conn.createStatement(); ret = statement.execute(sql); updateCount = statement.getUpdateCount(); do { if (!ret) { if (updateCount != -1) { updateCountTotal += updateCount; } } ret = statement.getMoreResults(); if (ret) { updateCount = statement.getUpdateCount(); } } while (ret); logger.debug(sql + " : " + updateCountTotal + " rows affected"); SQLWarning warning = conn.getWarnings(); while (warning != null) { logger.warn(warning + " sql warning"); warning = warning.getNextWarning(); } conn.clearWarnings(); } catch (SQLException e) { if (e.getSQLState().equals("X0Y32")) { // eliminating the table already exception for the derby // database logger.info("Table Already Exists", e); } else { throw new Exception("Error occurred while executing : " + sql, e); } } finally { if (statement != null) { try { statement.close(); } catch (SQLException e) { logger.error("Error occurred while closing result set.", e); } } } } private void startDerbyInServerMode() { try { DerbyUtil.startDerbyInServerMode(Utils.getHost(), 20000, Utils.getJDBCUser(), Utils.getJDBCUser()); } catch (Exception e) { logger.error("Unable to start Apache derby in the server mode! Check whether " + "specified port is available", e); } } private void startDerbyInEmbeddedMode(){ try { DerbyUtil.startDerbyInEmbeddedMode(); } catch (Exception e) { logger.error("Error occurred while starting Derby in embedded mode", e); } } public void stopDerbyServer() { try { DerbyUtil.stopDerbyServer(); } catch (Exception e) { logger.error("Error occurred while stopping Derby", e); } } }
9,474
0
Create_ds/airavata-sandbox/job-throttler/src/test/java/org/apache/airavata/scheduler
Create_ds/airavata-sandbox/job-throttler/src/test/java/org/apache/airavata/scheduler/jobthrottler/MetaSchedulerTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.scheduler.jobthrottler; import java.util.*; public class MetaSchedulerTest { public static void main(String[] args) { ArrayList<String> experimentData = new ArrayList<String>(); ArrayList<String> statusData = new ArrayList<String>(); Random rand = new Random(); String hostID = ""; String queueID = ""; String gatewayID = ""; int submitCtr = 0; int holdCtr = 0; int errorCtr = 0; String sarg0 = args[0]; if (sarg0.equals("clear")) { System.out.println("Clearing Active Jobs"); MetaScheduler.clearActiveJobs(); } if ((sarg0.equals("run")) || (sarg0.equals("end"))) { int runCount = Integer.parseInt(args[1]); int n = rand.nextInt(100); hostID = "quarry.uits.iu.edu"; if (n < 50) { hostID = "bigred2.uits.iu.edu"; } queueID = "debug"; n = rand.nextInt(100); if (n < 25) { queueID = "serial"; } n = rand.nextInt(100); if (n < 25) { queueID = "normal"; } n = rand.nextInt(100); if (n < 25) { queueID = "long"; } n = rand.nextInt(100); gatewayID = "Gateway1"; n = rand.nextInt(100); if (n < 50) { gatewayID = "Gateway2"; } long currentTime = ((long) System.currentTimeMillis()) / 99; for (int i=0;i<runCount;i++) { experimentData.add(hostID); experimentData.add(queueID); experimentData.add(gatewayID); experimentData.add(Long.toString(currentTime+i)); } if (sarg0.equals("run")) { System.out.println("Scheduling " + runCount + " jobs on " + hostID + " : " + queueID + " for " + gatewayID); statusData = MetaScheduler.submitThrottleJob(experimentData); // display results summarized int dataNDX = 0; while (dataNDX < statusData.size()) { if (statusData.get(dataNDX).equals("SUBMIT")) { submitCtr++; } if (statusData.get(dataNDX).equals("HOLD")) { holdCtr++; } if (statusData.get(dataNDX).equals("ERROR")) { errorCtr++; } dataNDX++; } System.out.println("Job States: submit=" + submitCtr + " hold=" + holdCtr + " error=" + errorCtr); } if (sarg0.equals("end")) { System.out.println("Changing Status of " + runCount + " jobs on " + hostID + " : " + queueID + " for " + gatewayID); MetaScheduler.changeJobStatus(experimentData); } } } }
9,475
0
Create_ds/airavata-sandbox/job-throttler/src/main/java/org/apache/airavata/scheduler
Create_ds/airavata-sandbox/job-throttler/src/main/java/org/apache/airavata/scheduler/jobthrottler/MetaScheduler.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.scheduler.jobthrottler; import java.sql.*; import java.util.ArrayList; public class MetaScheduler { public static Connection mySQLConnection() { String jdbcDriver = "com.mysql.jdbc.Driver"; String jdbcUser="******"; String jdbcPwd="********"; String jdbcUrl="jdbc:mysql://rdc04.uits.iu.edu:3059/scheduler"; Connection connect = null; try { Class.forName(jdbcDriver).newInstance(); connect = DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPwd); } catch (Exception e) { System.out.println("Connection to mysql Failed!"); e.printStackTrace(); return(null); } return(connect); } public static ArrayList<String> submitThrottleJob(ArrayList<String> experimentData) { ArrayList<String> statusData = new ArrayList<String>(); String hostID = ""; String queueID = ""; String experimentID = ""; String gatewayID = ""; String jobStatus = ""; int activeJobs = 0; int queueLimit = 0; Connection conn = mySQLConnection(); int dataNDX = 0; while (dataNDX < experimentData.size()) { hostID = experimentData.get(dataNDX); queueID = experimentData.get(dataNDX+1); gatewayID = experimentData.get(dataNDX+2); experimentID = experimentData.get(dataNDX+3); queueLimit = getQueueLimits(hostID,queueID,conn); activeJobs = getActiveJobs(gatewayID, hostID, queueID, conn); jobStatus = getJobStatus(activeJobs, queueLimit); if (!updateActiveJobs(gatewayID, hostID, queueID, experimentID, jobStatus, conn)) jobStatus = "ERROR"; statusData.add(jobStatus); dataNDX += 4; } return(statusData); } public static Boolean updateActiveJobs(String gatewayID, String hostID, String queueID, String jobID, String jobStatus, Connection conn ) { try { try { String sql = "insert into activejobs " + " (gatewayID, hostID, queueName, jobID, jobState) VALUES " + " (?,?,?,?,?) "; PreparedStatement insertSQL = conn.prepareStatement(sql); insertSQL.setString(1, gatewayID); insertSQL.setString(2, hostID); insertSQL.setString(3, queueID); insertSQL.setString(4, jobID); insertSQL.setString(5, jobStatus); insertSQL.executeUpdate(); } finally { } } catch (SQLException e) { return false; } return(true); } public static String getJobStatus(int activeJobs, int queueLimit) { String jobStatus = ""; if (queueLimit > activeJobs) jobStatus = "SUBMIT"; else jobStatus = "HOLD"; return(jobStatus); } public static int getActiveJobs(String gatewayID, String hostID, String queueID, Connection conn) { int activeJobs = 0; try { Statement statement = null; try { statement = conn.createStatement(); String sql = "select count(*) from activejobs where " + " gatewayID = ? and hostID = ? and queueName = ?"; PreparedStatement updateSQL = conn.prepareStatement(sql); updateSQL.setString(1, gatewayID); updateSQL.setString(2, hostID); updateSQL.setString(3, queueID); ResultSet rs = updateSQL.executeQuery(); if (rs != null) { rs.next(); activeJobs = rs.getInt(1); rs.close(); } } finally { try { if (statement != null) { statement.close(); } } catch (SQLException e) { return -1; } } } catch (SQLException e) { return -1; } return activeJobs; } public static int getQueueLimits(String hostID, String queueID, Connection conn) { int queueLimit = 0; try { Statement statement = null; try { statement = conn.createStatement(); String sql = "select * from queuelimits where hostID = ? and queueName = ?"; PreparedStatement updateSQL = conn.prepareStatement(sql); updateSQL.setString(1, hostID); updateSQL.setString(2, queueID); ResultSet rs = updateSQL.executeQuery(); if (rs != null) { while (rs.next()) { queueLimit = (Integer) rs.getObject("queueLimit"); } rs.close(); } } finally { try { if (statement != null) { statement.close(); } } catch (SQLException e) { return -1; } } } catch (SQLException e) { return -1; } return queueLimit; } public static Boolean clearActiveJobs() { try { Connection conn = mySQLConnection(); Statement statement = null; try { statement = conn.createStatement(); String sql = "delete from activejobs"; statement.executeUpdate(sql); } finally { try { if (statement != null) { statement.close(); } } catch (SQLException e) { return false; } } } catch (SQLException e) { return false; } return(true); } public static Boolean changeJobStatus(ArrayList<String> experimentData) { String hostID = ""; String queueID = ""; String gatewayID = ""; int deleteCtr = (experimentData.size() + 1) / 4; int dataNDX = 0; if (deleteCtr > 0) { hostID = experimentData.get(dataNDX); queueID = experimentData.get(dataNDX+1); gatewayID = experimentData.get(dataNDX+2); } try { Connection conn = mySQLConnection(); try { // not really meaningful, but useful for testing String sql = "delete top (?) from activejobs where " + "hostID = ? and queueID = ? and gatewayID = ? "; PreparedStatement updateSQL = conn.prepareStatement(sql); updateSQL.setInt(1, deleteCtr); updateSQL.setString(2, hostID); updateSQL.setString(3, queueID); updateSQL.setString(4, gatewayID); updateSQL.executeQuery(); } finally { } } catch (SQLException e) { return false; } return(true); } }
9,476
0
Create_ds/airavata-sandbox/gfac-sample/local-echo-sample-client/src/main/java/org/apache/airavata
Create_ds/airavata-sandbox/gfac-sample/local-echo-sample-client/src/main/java/org/apache/airavata/client/RunEchoLocalHost.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.client; import org.apache.airavata.model.error.ExperimentNotFoundException; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.airavata.common.utils.ClientSettings; import org.apache.airavata.model.util.ProjectModelUtil; import org.apache.airavata.model.workspace.Project; import org.apache.airavata.model.workspace.experiment.*; import org.apache.airavata.api.Airavata; import org.apache.airavata.api.client.AiravataClientFactory; import org.apache.airavata.model.error.AiravataClientException; import org.apache.airavata.model.error.AiravataSystemException; import org.apache.airavata.model.error.InvalidRequestException; import org.apache.airavata.client.AiravataAPIFactory; import org.apache.airavata.client.api.AiravataAPI; import org.apache.airavata.client.api.exception.AiravataAPIInvocationException; import org.apache.airavata.client.tools.DocumentCreator; import org.apache.airavata.common.utils.AiravataUtils; import org.apache.airavata.model.util.ExperimentModelUtil; import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public class RunEchoLocalHost { //FIXME: Read from a config file public static final String THRIFT_SERVER_HOST = "localhost"; public static final int THRIFT_SERVER_PORT = 8930; private final static Logger logger = LoggerFactory.getLogger(RunEchoLocalHost.class); private static final String DEFAULT_USER = "default.registry.user"; private static final String DEFAULT_GATEWAY = "default.registry.gateway"; public static void main(String[] args) { try { AiravataUtils.setExecutionAsClient(); final Airavata.Client airavata = AiravataClientFactory.createAiravataClient(THRIFT_SERVER_HOST, THRIFT_SERVER_PORT); addDescriptors(); final String expId = createExperimentForLocalHost(airavata); System.out.println("Experiment ID : " + expId); launchExperiment(airavata, expId); } catch (Exception e) { logger.error("Error while connecting with server", e.getMessage()); e.printStackTrace(); } } public static void addDescriptors() throws AiravataAPIInvocationException,ApplicationSettingsException { try { DocumentCreator documentCreator = new DocumentCreator(getAiravataAPI()); documentCreator.createLocalHostDocs(); } catch (AiravataAPIInvocationException e) { logger.error("Unable to create airavata API", e.getMessage()); throw new AiravataAPIInvocationException(e); } catch (ApplicationSettingsException e) { logger.error("Unable to create airavata API", e.getMessage()); throw new ApplicationSettingsException(e.getMessage()); } } private static AiravataAPI getAiravataAPI() throws AiravataAPIInvocationException, ApplicationSettingsException { AiravataAPI airavataAPI; try { String sysUser = ClientSettings.getSetting(DEFAULT_USER); String gateway = ClientSettings.getSetting(DEFAULT_GATEWAY); airavataAPI = AiravataAPIFactory.getAPI(gateway, sysUser); } catch (AiravataAPIInvocationException e) { logger.error("Unable to create airavata API", e.getMessage()); throw new AiravataAPIInvocationException(e); } catch (ApplicationSettingsException e) { logger.error("Unable to create airavata API", e.getMessage()); throw new ApplicationSettingsException(e.getMessage()); } return airavataAPI; } public static String createExperimentForTrestles(Airavata.Client client) throws TException { try{ List<DataObjectType> exInputs = new ArrayList<DataObjectType>(); DataObjectType input = new DataObjectType(); input.setKey("echo_input"); input.setType(DataType.STRING); input.setValue("echo_output=Hello World"); exInputs.add(input); List<DataObjectType> exOut = new ArrayList<DataObjectType>(); DataObjectType output = new DataObjectType(); output.setKey("echo_output"); output.setType(DataType.STRING); output.setValue(""); exOut.add(output); Experiment simpleExperiment = ExperimentModelUtil.createSimpleExperiment("default", "admin", "echoExperiment", "SimpleEcho2", "SimpleEcho2", exInputs); simpleExperiment.setExperimentOutputs(exOut); ComputationalResourceScheduling scheduling = ExperimentModelUtil.createComputationResourceScheduling("trestles.sdsc.edu", 1, 1, 1, "normal", 0, 0, 1, "sds128"); scheduling.setResourceHostId("gsissh-trestles"); UserConfigurationData userConfigurationData = new UserConfigurationData(); userConfigurationData.setAiravataAutoSchedule(false); userConfigurationData.setOverrideManualScheduledParams(false); userConfigurationData.setComputationalResourceScheduling(scheduling); simpleExperiment.setUserConfigurationData(userConfigurationData); return client.createExperiment(simpleExperiment); } catch (AiravataSystemException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new AiravataSystemException(e); } catch (InvalidRequestException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new InvalidRequestException(e); } catch (AiravataClientException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new AiravataClientException(e); }catch (TException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new TException(e); } } public static String cloneExperiment(Airavata.Client client, String expId) throws TException { try{ return client.cloneExperiment(expId, "cloneExperiment1"); }catch (TException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new TException(e); } } public static String createExperimentForLocalHost(Airavata.Client client) throws TException { try{ List<DataObjectType> exInputs = new ArrayList<DataObjectType>(); DataObjectType input = new DataObjectType(); input.setKey("echo_input"); input.setType(DataType.STRING); input.setValue("echo_output=Hello World"); exInputs.add(input); List<DataObjectType> exOut = new ArrayList<DataObjectType>(); DataObjectType output = new DataObjectType(); output.setKey("echo_output"); output.setType(DataType.STRING); output.setValue(""); exOut.add(output); Project project = ProjectModelUtil.createProject("project1", "admin", "test project"); String projectId = client.createProject(project); Experiment simpleExperiment = ExperimentModelUtil.createSimpleExperiment(projectId, "admin", "echoExperiment", "SimpleEcho0", "SimpleEcho0", exInputs); simpleExperiment.setExperimentOutputs(exOut); ComputationalResourceScheduling scheduling = ExperimentModelUtil.createComputationResourceScheduling("localhost", 1, 1, 1, "normal", 0, 0, 1, ""); scheduling.setResourceHostId("localhost"); UserConfigurationData userConfigurationData = new UserConfigurationData(); userConfigurationData.setAiravataAutoSchedule(false); userConfigurationData.setOverrideManualScheduledParams(false); userConfigurationData.setComputationalResourceScheduling(scheduling); simpleExperiment.setUserConfigurationData(userConfigurationData); return client.createExperiment(simpleExperiment); } catch (AiravataSystemException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new AiravataSystemException(e); } catch (InvalidRequestException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new InvalidRequestException(e); } catch (AiravataClientException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new AiravataClientException(e); }catch (TException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new TException(e); } } public static String createExperimentForSSHHost(Airavata.Client client) throws TException { try{ List<DataObjectType> exInputs = new ArrayList<DataObjectType>(); DataObjectType input = new DataObjectType(); input.setKey("echo_input"); input.setType(DataType.STRING); input.setValue("echo_output=Hello World"); exInputs.add(input); List<DataObjectType> exOut = new ArrayList<DataObjectType>(); DataObjectType output = new DataObjectType(); output.setKey("echo_output"); output.setType(DataType.STRING); output.setValue(""); exOut.add(output); Project project = ProjectModelUtil.createProject("default", "admin", "test project"); String projectId = client.createProject(project); Experiment simpleExperiment = ExperimentModelUtil.createSimpleExperiment(projectId, "admin", "sshEchoExperiment", "SSHEcho1", "SSHEcho1", exInputs); simpleExperiment.setExperimentOutputs(exOut); ComputationalResourceScheduling scheduling = ExperimentModelUtil.createComputationResourceScheduling("gw111.iu.xsede.org", 1, 1, 1, "normal", 0, 0, 1, "sds128"); scheduling.setResourceHostId("gw111.iu.xsede.org"); UserConfigurationData userConfigurationData = new UserConfigurationData(); userConfigurationData.setAiravataAutoSchedule(false); userConfigurationData.setOverrideManualScheduledParams(false); userConfigurationData.setComputationalResourceScheduling(scheduling); simpleExperiment.setUserConfigurationData(userConfigurationData); return client.createExperiment(simpleExperiment); } catch (AiravataSystemException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new AiravataSystemException(e); } catch (InvalidRequestException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new InvalidRequestException(e); } catch (AiravataClientException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new AiravataClientException(e); }catch (TException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new TException(e); } } public static String createExperimentForStampede(Airavata.Client client) throws TException { try{ List<DataObjectType> exInputs = new ArrayList<DataObjectType>(); DataObjectType input = new DataObjectType(); input.setKey("echo_input"); input.setType(DataType.STRING); input.setValue("echo_output=Hello World"); exInputs.add(input); List<DataObjectType> exOut = new ArrayList<DataObjectType>(); DataObjectType output = new DataObjectType(); output.setKey("echo_output"); output.setType(DataType.STRING); output.setValue(""); exOut.add(output); Project project = ProjectModelUtil.createProject("default", "admin", "test project"); String projectId = client.createProject(project); Experiment simpleExperiment = ExperimentModelUtil.createSimpleExperiment(projectId, "admin", "echoExperiment", "SimpleEcho3", "SimpleEcho3", exInputs); simpleExperiment.setExperimentOutputs(exOut); ComputationalResourceScheduling scheduling = ExperimentModelUtil.createComputationResourceScheduling("stampede.tacc.xsede.org", 1, 1, 1, "normal", 0, 0, 1, "TG-STA110014S"); scheduling.setResourceHostId("stampede-host"); UserConfigurationData userConfigurationData = new UserConfigurationData(); userConfigurationData.setAiravataAutoSchedule(false); userConfigurationData.setOverrideManualScheduledParams(false); userConfigurationData.setComputationalResourceScheduling(scheduling); simpleExperiment.setUserConfigurationData(userConfigurationData); return client.createExperiment(simpleExperiment); } catch (AiravataSystemException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new AiravataSystemException(e); } catch (InvalidRequestException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new InvalidRequestException(e); } catch (AiravataClientException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new AiravataClientException(e); }catch (TException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new TException(e); } } public static String createExperimentForLonestar(Airavata.Client client) throws TException { try{ List<DataObjectType> exInputs = new ArrayList<DataObjectType>(); DataObjectType input = new DataObjectType(); input.setKey("echo_input"); input.setType(DataType.STRING); input.setValue("echo_output=Hello World"); exInputs.add(input); List<DataObjectType> exOut = new ArrayList<DataObjectType>(); DataObjectType output = new DataObjectType(); output.setKey("echo_output"); output.setType(DataType.STRING); output.setValue(""); exOut.add(output); Project project = ProjectModelUtil.createProject("default", "admin", "test project"); String projectId = client.createProject(project); Experiment simpleExperiment = ExperimentModelUtil.createSimpleExperiment(projectId, "admin", "echoExperiment", "SimpleEcho4", "SimpleEcho4", exInputs); simpleExperiment.setExperimentOutputs(exOut); ComputationalResourceScheduling scheduling = ExperimentModelUtil.createComputationResourceScheduling("lonestar.tacc.utexas.edu", 1, 1, 1, "normal", 0, 0, 1, "TG-STA110014S"); scheduling.setResourceHostId("lonestar-host"); UserConfigurationData userConfigurationData = new UserConfigurationData(); userConfigurationData.setAiravataAutoSchedule(false); userConfigurationData.setOverrideManualScheduledParams(false); userConfigurationData.setComputationalResourceScheduling(scheduling); simpleExperiment.setUserConfigurationData(userConfigurationData); return client.createExperiment(simpleExperiment); } catch (AiravataSystemException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new AiravataSystemException(e); } catch (InvalidRequestException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new InvalidRequestException(e); } catch (AiravataClientException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new AiravataClientException(e); }catch (TException e) { logger.error("Error occured while creating the experiment...", e.getMessage()); throw new TException(e); } } public static void launchExperiment (Airavata.Client client, String expId) throws TException{ try { client.launchExperiment(expId, "testToken"); } catch (ExperimentNotFoundException e) { logger.error("Error occured while launching the experiment...", e.getMessage()); throw new ExperimentNotFoundException(e); } catch (AiravataSystemException e) { logger.error("Error occured while launching the experiment...", e.getMessage()); throw new AiravataSystemException(e); } catch (InvalidRequestException e) { logger.error("Error occured while launching the experiment...", e.getMessage()); throw new InvalidRequestException(e); } catch (AiravataClientException e) { logger.error("Error occured while launching the experiment...", e.getMessage()); throw new AiravataClientException(e); }catch (TException e) { logger.error("Error occured while launching the experiment...", e.getMessage()); throw new TException(e); } } public static List<Experiment> getExperimentsForUser (Airavata.Client client, String user){ try { return client.getAllUserExperiments(user); } catch (AiravataSystemException e) { e.printStackTrace(); } catch (InvalidRequestException e) { e.printStackTrace(); } catch (AiravataClientException e) { e.printStackTrace(); }catch (TException e){ e.printStackTrace(); } return null; } public static List<Project> getAllUserProject (Airavata.Client client, String user){ try { return client.getAllUserProjects(user); } catch (AiravataSystemException e) { e.printStackTrace(); } catch (InvalidRequestException e) { e.printStackTrace(); } catch (AiravataClientException e) { e.printStackTrace(); }catch (TException e){ e.printStackTrace(); } return null; } }
9,477
0
Create_ds/airavata-sandbox/gfac-sample/local-handler-sample/src/main/java/org/apache/airavata/gfac/local
Create_ds/airavata-sandbox/gfac-sample/local-handler-sample/src/main/java/org/apache/airavata/gfac/local/handler/OutputEmailHandler.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.gfac.local.handler; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.gfac.core.context.JobExecutionContext; import org.apache.airavata.gfac.core.handler.GFacHandler; import org.apache.airavata.gfac.core.handler.GFacHandlerException; import org.apache.airavata.schemas.gfac.StringParameterType; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Map; import java.util.Properties; public class OutputEmailHandler implements GFacHandler { private Properties props; public void initProperties(Properties properties) throws GFacHandlerException { System.out.println("Initializing " + OutputEmailHandler.class + " Handler..."); props = properties; } public void invoke(JobExecutionContext jobExecutionContext) throws GFacHandlerException { System.out.println("Start Emailing the output values ... "); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication((String) props.get("username"), (String) props.get("password")); } }); Message message = new MimeMessage(session); try { message.setFrom(new InternetAddress((String) props.get("username"))); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) props.get("username"))); message.setSubject("GFAC Output Email"); Map<String, Object> parameters = jobExecutionContext.getOutMessageContext().getParameters(); StringBuffer buffer = new StringBuffer(); for (String input : parameters.keySet()) { ActualParameter inParam = (ActualParameter) parameters.get(input); String paramDataType = inParam.getType().getType().toString(); if ("String".equals(paramDataType)) { String stringPrm = ((StringParameterType) inParam.getType()) .getValue(); buffer.append("Output Name: " + input + " Output Value: " + stringPrm + "\n"); } } message.setText(buffer.toString()); Transport.send(message); System.out.println("Sent email to : " + props.get("username")); } catch (MessagingException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }
9,478
0
Create_ds/airavata-sandbox/gfac-sample/local-handler-sample/src/main/java/org/apache/airavata/gfac/local
Create_ds/airavata-sandbox/gfac-sample/local-handler-sample/src/main/java/org/apache/airavata/gfac/local/handler/InputEmailHandler.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.gfac.local.handler; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.gfac.core.context.JobExecutionContext; import org.apache.airavata.gfac.core.handler.GFacHandler; import org.apache.airavata.gfac.core.handler.GFacHandlerException; import org.apache.airavata.schemas.gfac.StringParameterType; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import java.lang.String; import java.util.Map; import java.util.Properties; public class InputEmailHandler implements GFacHandler { private Properties props; public void initProperties(Properties properties) throws GFacHandlerException { System.out.println("Initializing " + InputEmailHandler.class + " Handler..."); props = properties; } public void invoke(JobExecutionContext jobExecutionContext) throws GFacHandlerException { // Session session = Session.getInstance(props, // new javax.mail.Authenticator() { // protected PasswordAuthentication getPasswordAuthentication() { // return new PasswordAuthentication((String) props.get("username"), (String) props.get("password")); // } // }); // // Message message = new MimeMessage(session); // try { // message.setFrom(new InternetAddress((String) props.get("username"))); // message.setRecipients(Message.RecipientType.TO, // InternetAddress.parse((String) props.get("username"))); // message.setSubject("GFAC Input Email"); // // Transport.send(message); // } catch (MessagingException e) { // e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. // } // System.out.println("Start Emailing the input values ... "); // try { // Session mailSession = Session.getDefaultInstance(props, null); // Transport transport = mailSession.getTransport(); // // MimeMessage message = new MimeMessage(mailSession); // message.setSubject("GFAC Inputs"); // Map<String, Object> parameters = jobExecutionContext.getOutMessageContext().getParameters(); // StringBuffer buffer = new StringBuffer(); // for (String input : parameters.keySet()) { // ActualParameter inParam = (ActualParameter) parameters.get(input); // String paramDataType = inParam.getType().getType().toString(); // if ("String".equals(paramDataType)) { // String stringPrm = ((StringParameterType) inParam.getType()) // .getValue(); // buffer.append("Input Name: input: Input Value: " + stringPrm + "\n"); // } // } // message.setContent(buffer.toString(), "text/plain"); // message.addRecipient(Message.RecipientType.TO, // new InternetAddress((String) props.get("username"))); // // transport.connect(); // transport.sendMessage(message, // message.getRecipients(Message.RecipientType.TO)); // transport.close(); // System.out.println("Sent email to : " + props.get("username")); // } catch (Exception e) { // // } System.out.println("Start Emailing the input values ... "); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication((String) props.get("username"), (String) props.get("password")); } }); Message message = new MimeMessage(session); try { message.setFrom(new InternetAddress((String) props.get("username"))); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) props.get("username"))); message.setSubject("GFAC Input Email"); Map<String, Object> parameters = jobExecutionContext.getInMessageContext().getParameters(); StringBuffer buffer = new StringBuffer(); for (String input : parameters.keySet()) { ActualParameter inParam = (ActualParameter) parameters.get(input); String paramDataType = inParam.getType().getType().toString(); if ("String".equals(paramDataType)) { String stringPrm = ((StringParameterType) inParam.getType()) .getValue(); buffer.append("Input Name:" + input + " Input Value: " + stringPrm + "\n"); } } message.setText(buffer.toString()); Transport.send(message); System.out.println("Sent email to : " + props.get("username")); } catch (MessagingException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }
9,479
0
Create_ds/airavata-sandbox/grid-tools/bes-client/src/test/java/org/apache/airavata/sample
Create_ds/airavata-sandbox/grid-tools/bes-client/src/test/java/org/apache/airavata/sample/bes/TestJSDLGeneration.java
package org.apache.airavata.sample.bes; import static org.junit.Assert.assertTrue; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.ggf.schemas.jsdl.x2005.x11.jsdl.ApplicationDocument; import org.ggf.schemas.jsdl.x2005.x11.jsdl.ApplicationType; import org.ggf.schemas.jsdl.x2005.x11.jsdl.CreationFlagEnumeration; import org.ggf.schemas.jsdl.x2005.x11.jsdl.DataStagingDocument; import org.ggf.schemas.jsdl.x2005.x11.jsdl.DataStagingType; import org.ggf.schemas.jsdl.x2005.x11.jsdl.JobDefinitionDocument; import org.ggf.schemas.jsdl.x2005.x11.jsdl.JobDescriptionType; import org.ggf.schemas.jsdl.x2005.x11.jsdl.ResourcesType; import org.ggf.schemas.jsdl.x2005.x11.jsdl.SourceTargetType; import org.ggf.schemas.jsdl.x2005.x11.jsdlPosix.POSIXApplicationDocument; import org.ggf.schemas.jsdl.x2005.x11.jsdlPosix.POSIXApplicationType; import org.junit.Test; import de.fzj.unicore.wsrflite.xmlbeans.WSUtilities; /** * This test case creates a sample jsdl instance * containing Application, Arguments, Source, and Target Elements * * */ public class TestJSDLGeneration { @Test public void testSimpleJSDLInstance(){ JobDefinitionDocument jdd = JobDefinitionDocument.Factory.newInstance(); JobDescriptionType jobDescType = jdd.addNewJobDefinition().addNewJobDescription(); // setting application details ApplicationDocument appDoc = ApplicationDocument.Factory.newInstance(); ApplicationType app = appDoc.addNewApplication(); app.setApplicationName("gnuplot"); WSUtilities.append(posixElement(), appDoc); jobDescType.setApplication(appDoc.getApplication()); // setting resource details ResourcesType resType = jobDescType.addNewResources(); resType.addNewIndividualPhysicalMemory().addNewLowerBoundedRange().setDoubleValue(20197152.0); resType.addNewTotalCPUCount().addNewExact().setDoubleValue(1.0); // setting simple data staging details newDataStagingElement(jobDescType.addNewDataStaging(), true, "control.txt"); newDataStagingElement(jobDescType.addNewDataStaging(), true, "input.dat"); newDataStagingElement(jobDescType.addNewDataStaging(), false, "output1.png"); // setting hpcp-file staging profile data staging details and credentials newHPCPFSPDataStagingElement(jobDescType.addNewDataStaging(), true, "control.txt", "u1", "p1"); newHPCPFSPDataStagingElement(jobDescType.addNewDataStaging(), true, "input.dat", "u1", "p1"); newHPCPFSPDataStagingElement(jobDescType.addNewDataStaging(), false, "output1.png", "u1", "p1"); newHPCPFSPDataStagingElement(jobDescType.addNewDataStaging(), false, "extendedoutput.png", "u1", "p1"); assertTrue(HPCPUtils.extractUsernamePassword(jdd)!=null); System.out.println(jdd); } private POSIXApplicationDocument posixElement(){ POSIXApplicationDocument posixDoc = POSIXApplicationDocument.Factory.newInstance(); POSIXApplicationType posixType = posixDoc.addNewPOSIXApplication(); posixType.addNewExecutable().setStringValue("/usr/bin/gnuplot"); posixType.addNewArgument().setStringValue("control.lst"); posixType.addNewArgument().setStringValue("input.dat"); //if they both are not set, then the target unicore server will name them stdout and stderr without i.e. '.txt' posixType.addNewOutput().setStringValue("stdout.txt"); posixType.addNewError().setStringValue("stderr.txt"); return posixDoc; } private void newDataStagingElement(DataStagingType dsType, boolean isSource, String fileName){ dsType.setFileName(fileName); dsType.setCreationFlag(CreationFlagEnumeration.OVERWRITE); dsType.setDeleteOnTermination(true); if(isSource) dsType.addNewSource().setURI("http://foo.bar.com/~me/"+fileName); else dsType.addNewTarget().setURI("http://foo.bar.com/~me/"+fileName); } private void newHPCPFSPDataStagingElement(final DataStagingType dsType, boolean isSource, String fileName, String userName, String password){ dsType.setFileName(fileName); dsType.setCreationFlag(CreationFlagEnumeration.OVERWRITE); dsType.setDeleteOnTermination(true); SourceTargetType sourceTarget = null; if(isSource) sourceTarget = dsType.addNewSource(); else sourceTarget = dsType.addNewTarget(); sourceTarget.setURI("http://foo.bar.com/~me/"+fileName); DataStagingDocument dsDoc = DataStagingDocument.Factory.newInstance(); dsDoc.setDataStaging(dsType); WSUtilities.append(HPCPUtils.createCredentialsElement(userName, password), dsDoc); dsType.set(dsDoc.getDataStaging()); } public int count(String word, String line){ Pattern pattern = Pattern.compile(word); Matcher matcher = pattern.matcher(line); int counter = 0; while (matcher.find()) counter++; return counter; } }
9,480
0
Create_ds/airavata-sandbox/grid-tools/bes-client/src/test/java/org/apache/airavata/sample
Create_ds/airavata-sandbox/grid-tools/bes-client/src/test/java/org/apache/airavata/sample/bes/TestInterop.java
package org.apache.airavata.sample.bes; import org.apache.airavata.sample.bes.RunBESJob; import org.junit.Test; public class TestInterop { @Test public void testRunJob(){ RunBESJob besJob = new RunBESJob(); besJob.runJob(); } @Test public void testRunAndTerminateJob(){ RunAndTerminateJob besJob = new RunAndTerminateJob(); besJob.runAndTerminate(); } }
9,481
0
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample/bes/CreateActivityTask.java
package org.apache.airavata.sample.bes; import java.util.Calendar; import org.ggf.schemas.bes.x2006.x08.besFactory.ActivityStateEnumeration; import org.ggf.schemas.bes.x2006.x08.besFactory.CreateActivityDocument; import org.ggf.schemas.bes.x2006.x08.besFactory.CreateActivityResponseDocument; import org.w3.x2005.x08.addressing.EndpointReferenceType; import de.fzj.unicore.bes.client.FactoryClient; import de.fzj.unicore.wsrflite.xmlbeans.WSUtilities; import eu.unicore.security.util.client.IClientProperties; public class CreateActivityTask { private BESJob job; private IClientProperties sec; private String jobId; public CreateActivityTask(BESJob job, IClientProperties sec) { this.job = job; this.sec = sec; } public void startJob() throws Exception { String factoryUrl = job.getFactoryUrl(); EndpointReferenceType eprt = EndpointReferenceType.Factory .newInstance(); eprt.addNewAddress().setStringValue(factoryUrl); System.out.println("========================================"); System.out.println(String.format("Job Submitted to %s.\n", factoryUrl)); FactoryClient factory = new FactoryClient(eprt, sec); CreateActivityDocument cad = CreateActivityDocument.Factory .newInstance(); cad.addNewCreateActivity().addNewActivityDocument() .setJobDefinition(job.getJobDoc().getJobDefinition()); CreateActivityResponseDocument response = factory.createActivity(cad); EndpointReferenceType activityEpr = response .getCreateActivityResponse().getActivityIdentifier(); // factory.waitWhileActivityIsDone(activityEpr, 1000); jobId = WSUtilities.extractResourceID(activityEpr); if (jobId == null) { jobId = new Long(Calendar.getInstance().getTimeInMillis()) .toString(); } ActivityStateEnumeration.Enum state = factory.getActivityStatus(activityEpr); String status; status = String.format("Job %s is %s.\n", activityEpr.getAddress() .getStringValue(), factory.getActivityStatus(activityEpr) .toString()).toString(); while ((factory.getActivityStatus(activityEpr) != ActivityStateEnumeration.FINISHED) && (factory.getActivityStatus(activityEpr) != ActivityStateEnumeration.FAILED)){ status = String.format("Job %s is %s.\n", activityEpr.getAddress() .getStringValue(), factory.getActivityStatus(activityEpr) .toString()).toString(); Thread.sleep(1500); continue; } status = String.format("Job %s is %s.\n", activityEpr.getAddress() .getStringValue(), factory.getActivityStatus(activityEpr) .toString()).toString(); System.out.println(status); if (!(factory.getActivityStatus(activityEpr) == ActivityStateEnumeration.FINISHED)) { throw new Exception("Job "+activityEpr.getAddress().getStringValue()+" "+state.toString()); } } }
9,482
0
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample/bes/UsernamePassword.java
package org.apache.airavata.sample.bes; import java.io.Serializable; /** * holds username and password for some types of data staging, * as found in the job description * * @author schuller */ public class UsernamePassword implements Serializable { private static final long serialVersionUID=1L; private final String user; private final String password; public UsernamePassword(String user, String password){ this.user=user; this.password=password; } public String getUser() { return user; } public String getPassword() { return password; } public String toString(){ return "UsernamePassword["+user+" "+password+"]"; } }
9,483
0
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample/bes/XmlBeansUtils.java
package org.apache.airavata.sample.bes; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlCursor.TokenType; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class XmlBeansUtils { /** * appends a XmlObject into another, immediately before the end tag<br> * @param what * @param toWhere */ public static void append(XmlObject what, XmlObject toWhere){ XmlCursor sourceCurs=what.newCursor(); sourceCurs.toNextToken(); XmlCursor targetCurs = toWhere.newCursor(); targetCurs.toEndDoc(); targetCurs.toPrevToken(); sourceCurs.copyXml(targetCurs); sourceCurs.dispose(); targetCurs.dispose(); } /** * returns the QName for the "root element" of the Argument * @param o * @return */ public static QName getQNameFor(XmlObject o){ XmlCursor c=o.newCursor(); try{ c.toFirstChild(); return c.getName(); }finally{ c.dispose(); } } /** * extract xsd:any elements using DOM * * @param source - the xml fragment * @param q - QName of elements to extract. If null, all children will be returned * @return XmlObject[] * @throws XmlException */ public static XmlObject[] extractAnyElements(XmlObject source, QName q)throws XmlException{ NodeList nodes=source.getDomNode().getChildNodes(); List<XmlObject>results=new ArrayList<XmlObject>(); for(int i=0;i<nodes.getLength();i++){ Node n=nodes.item(i); if(q!=null){ if(q.getNamespaceURI().equals(n.getNamespaceURI()) && q.getLocalPart().equals(n.getLocalName())){ XmlObject o=XmlObject.Factory.parse(n); results.add(o); } }else{ XmlObject o=XmlObject.Factory.parse(n); results.add(o); } } return results.toArray(new XmlObject[results.size()]); } public static XmlObject extractFirstAnyElement(XmlObject source, QName q)throws XmlException,IOException{ XmlCursor c=source.newCursor(); if(skipToElement(c, q)){ XmlObject res=XmlObject.Factory.parse(c.newInputStream()); c.dispose(); return res; }else{ return null; } } public static XmlObject extractFirstAnyElement(XmlObject source, QName[] q)throws XmlException,IOException{ XmlCursor c=source.newCursor(); if(skipToElement(c, q)){ XmlObject res=XmlObject.Factory.parse(c.newInputStream()); c.dispose(); return res; }else{ return null; } } public static Map<String,String>extractAttributes(XmlObject source){ Map<String,String>result=new HashMap<String,String>(); XmlCursor curs=source.newCursor(); while(curs.hasNextToken()){ TokenType type=curs.toNextToken(); if(TokenType.END.equals(type))break; if(TokenType.ATTR.equals(type)){ QName q=curs.getName(); String val=curs.getTextValue(); result.put(q.getLocalPart(),val); } } return result; } /** * extract the text content of an XML element * * @param source the xml element * * @return the text content, or "" if element has no content */ public static String extractElementTextAsString(XmlObject source){ XmlCursor c=null; try{ c=source.newCursor(); while(c.hasNextToken()){ if(c.toNextToken().equals(TokenType.TEXT)){ return c.getChars(); } } return ""; }finally{ try{ c.dispose(); }catch(Exception e){} } } /** * fast-forward the cursor up to the element with the given QName * * @param cursor * @param name * @return false if element does not exist */ public static boolean skipToElement(XmlCursor cursor, QName name){ // walk through element tree in prefix order (root first, then children from left to right) if(name.equals(cursor.getName())) return true; boolean hasMoreChildren=true; int i=0; while(hasMoreChildren){ hasMoreChildren = cursor.toChild(i++); if(hasMoreChildren){ boolean foundInChild = skipToElement(cursor, name); if(foundInChild) return true; cursor.toParent(); } } return false; } /** * fast-forward the cursor up to the element with one of the given QNames * * @param cursor * @param names - list of acceptable qnames * @return false if element does not exist */ public static boolean skipToElement(XmlCursor cursor, QName[] names){ // walk through element tree in prefix order (root first, then children from left to right) for(QName name: names){ if(name.equals(cursor.getName())) return true; } boolean hasMoreChildren=true; int i=0; while(hasMoreChildren){ hasMoreChildren = cursor.toChild(i++); if(hasMoreChildren){ boolean foundInChild = skipToElement(cursor, names); if(foundInChild) return true; cursor.toParent(); } } return false; } /** * extract the text of a certain element from an xml document * @param source * @param names * @return text or null if undefined */ public static String getElementText(XmlObject source, QName[] names){ try{ XmlObject o=extractFirstAnyElement(source, names); return extractElementTextAsString(o); } catch(Exception ex){ return null; } } /** * extract the text of the specified element * @param source - the source XML document * @param name - the qname of the desired element * @return */ public static String getElementText(XmlObject source, QName name){ try{ XmlObject o=extractFirstAnyElement(source, name); if(o==null)return null; return extractElementTextAsString(o); } catch(Exception ex){ return null; } } public static String getAttributeText(XmlObject source, QName elementName, QName attributeName){ try{ XmlObject o=extractFirstAnyElement(source, elementName); if(o==null)return null; return getAttributeText(o, attributeName); } catch(Exception ex){ } return null; } public static String getAttributeText(XmlObject source, QName attributeName){ XmlCursor c=source.newCursor(); try{ TokenType t=null; do{ t=c.toNextToken(); if(t.isAttr()){ if(attributeName.equals(c.getName())){ return c.getTextValue(); } } }while(!TokenType.END.equals(t)); return null; }finally{ c.dispose(); } } /** * extract an array of XML elements identified by their qname from an XML source * document. * * @param source - the xml fragment * @param q - QName of elements to extract * @param asClass - the XMLbeans class of the elements to extract * @return List<T> - a list of XMLBeans objects with the correct runtime type */ @SuppressWarnings("unchecked") public static <T> List<T>extractAnyElements(XmlObject source, QName q, Class<? extends XmlObject>asClass){ List<T>results=new ArrayList<T>(); XmlCursor cursor=null; try{ if(source != null){ cursor = source.newCursor(); skipToElement(cursor, q); String ns=q.getNamespaceURI(); boolean hasMore =true; while(hasMore){ XmlObject next = XmlObject.Factory.parse(cursor.newXMLStreamReader()); QName name = cursor.getName(); if( (name!=null && (ns.equals(name.getNamespaceURI()) || "*".equals(ns))) && q.getLocalPart().equals(name.getLocalPart())){ results.add((T)next); } hasMore = cursor.toNextSibling(); } } } catch(XmlException xe){ //what? } finally{ if(cursor!=null)cursor.dispose(); } return results; } }
9,484
0
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample/bes/BESJob.java
package org.apache.airavata.sample.bes; import org.ggf.schemas.jsdl.x2005.x11.jsdl.JobDefinitionDocument; public class BESJob { private String factoryUrl; private JobDefinitionDocument jobDoc; public BESJob() { } public String getFactoryUrl() { return factoryUrl; } public void setFactory(String factoryUrl) { this.factoryUrl = factoryUrl; } public JobDefinitionDocument getJobDoc() { return jobDoc; } public void setJobDoc(JobDefinitionDocument jobDoc) { this.jobDoc = jobDoc; } }
9,485
0
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample/bes/RunBESJob.java
package org.apache.airavata.sample.bes; import java.io.File; import org.ggf.schemas.jsdl.x2005.x11.jsdl.JobDefinitionDocument; public class RunBESJob extends AbstractJobCommand{ public RunBESJob() { super(); } public void runJob() { JobDefinitionDocument jobDoc = null; try { jobDoc = JobDefinitionDocument.Factory.parse(new File(dateJsdlPath)); } catch (Exception e) { System.err.println("Error parsing JSDL instance. " + e); } BESJob job = new BESJob(); job.setFactory(factoryUrl); job.setJobDoc(jobDoc); CreateActivityTask th = new CreateActivityTask(job, securityProperties); try { th.startJob(); } catch (Exception e) { System.err.println("Couldn't run job: " + e); } } }
9,486
0
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample/bes/AbstractJobCommand.java
package org.apache.airavata.sample.bes; import de.fzj.unicore.uas.security.ClientProperties; import eu.unicore.security.util.client.IClientProperties; public abstract class AbstractJobCommand { public static final String factoryUrl = "https://zam1161v01.zam.kfa-juelich.de:8002/INTEROP1/services/BESFactory?res=default_bes_factory"; public static final String dateJsdlPath = "src/test/resources/date.xml"; protected IClientProperties securityProperties; public AbstractJobCommand() { securityProperties = initSecurityProperties(); } protected ClientProperties initSecurityProperties() { ClientProperties sp = new ClientProperties(); sp.setSslEnabled(true); sp.setSignMessage(true); sp.setKeystore("src/test/resources/demo-keystore.jks"); sp.setKeystorePassword("654321"); sp.setKeystoreAlias("demouser-new"); sp.setKeystoreType("JKS"); return sp; } }
9,487
0
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample/bes/RunAndTerminateJob.java
package org.apache.airavata.sample.bes; import java.io.File; import org.ggf.schemas.jsdl.x2005.x11.jsdl.JobDefinitionDocument; public class RunAndTerminateJob extends AbstractJobCommand { public RunAndTerminateJob() { super(); } public void runAndTerminate(){ JobDefinitionDocument jobDoc = null; try { jobDoc = JobDefinitionDocument.Factory.parse(new File(dateJsdlPath)); } catch (Exception e) { System.err.println("Error parsing JSDL instance. " + e); } BESJob job = new BESJob(); job.setFactory(factoryUrl); job.setJobDoc(jobDoc); CreateAndTerminateActivityTask th = new CreateAndTerminateActivityTask(job, securityProperties); try { th.startJob(); } catch (Exception e) { System.err.println("Couldn't run job: " + e); } } }
9,488
0
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample/bes/CreateAndTerminateActivityTask.java
package org.apache.airavata.sample.bes; import java.util.Calendar; import org.ggf.schemas.bes.x2006.x08.besFactory.ActivityStateEnumeration; import org.ggf.schemas.bes.x2006.x08.besFactory.CreateActivityDocument; import org.ggf.schemas.bes.x2006.x08.besFactory.CreateActivityResponseDocument; import org.ggf.schemas.bes.x2006.x08.besFactory.TerminateActivitiesResponseType; import org.w3.x2005.x08.addressing.EndpointReferenceType; import de.fzj.unicore.bes.client.FactoryClient; import de.fzj.unicore.wsrflite.xmlbeans.WSUtilities; import eu.unicore.security.util.client.IClientProperties; public class CreateAndTerminateActivityTask { private BESJob job; private IClientProperties sec; private String jobId; public CreateAndTerminateActivityTask(BESJob job, IClientProperties sec) { this.job = job; this.sec = sec; } public void startJob() throws Exception { String factoryUrl = job.getFactoryUrl(); EndpointReferenceType eprt = EndpointReferenceType.Factory .newInstance(); eprt.addNewAddress().setStringValue(factoryUrl); System.out.println("========================================"); System.out.println(String.format("Job Submitted to %s.\n", factoryUrl)); FactoryClient factory = new FactoryClient(eprt, sec); CreateActivityDocument cad = CreateActivityDocument.Factory .newInstance(); cad.addNewCreateActivity().addNewActivityDocument() .setJobDefinition(job.getJobDoc().getJobDefinition()); CreateActivityResponseDocument response = factory.createActivity(cad); EndpointReferenceType activityEpr = response .getCreateActivityResponse().getActivityIdentifier(); jobId = WSUtilities.extractResourceID(activityEpr); if (jobId == null) { jobId = new Long(Calendar.getInstance().getTimeInMillis()) .toString(); } String status; status = String.format("Job %s is %s.\n", activityEpr.getAddress() .getStringValue(), factory.getActivityStatus(activityEpr) .toString()).toString(); System.out.println(status); TerminateActivitiesResponseType terminateResType = factory.terminateActivity(activityEpr); Thread.sleep(500); System.out.println(terminateResType); if (!(factory.getActivityStatus(activityEpr) == ActivityStateEnumeration.CANCELLED)) { throw new Exception("Job "+activityEpr.getAddress().getStringValue()+" not CANCELLED"); } status = String.format("Job %s is %s.\n", activityEpr.getAddress() .getStringValue(), factory.getActivityStatus(activityEpr) .toString()).toString(); System.out.println(status); } }
9,489
0
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample/bes/MonitorJobStatusTask.java
package org.apache.airavata.sample.bes; import org.w3.x2005.x08.addressing.EndpointReferenceType; import de.fzj.unicore.wsrflite.xmlbeans.WSUtilities; import eu.unicore.security.util.client.IClientProperties; public class MonitorJobStatusTask { private String factoryUrl; private EndpointReferenceType jobEPR; private IClientProperties sec; public MonitorJobStatusTask(String factoryUrl, IClientProperties sec, EndpointReferenceType jobEPR) { this.factoryUrl = factoryUrl; this.jobEPR = jobEPR; this.sec = sec; } }
9,490
0
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample
Create_ds/airavata-sandbox/grid-tools/bes-client/src/main/java/org/apache/airavata/sample/bes/HPCPUtils.java
package org.apache.airavata.sample.bes; import javax.xml.namespace.QName; import org.apache.xmlbeans.XmlCursor; import org.apache.xmlbeans.XmlCursor.TokenType; import org.apache.xmlbeans.XmlObject; import org.ggf.schemas.jsdl.x2005.x11.jsdl.DataStagingType; import org.ggf.schemas.jsdl.x2005.x11.jsdl.SourceTargetType; import de.fzj.unicore.wsrflite.xmlbeans.WSUtilities; import eu.unicore.security.util.Log; /** * Helper for dealing with the HPC file staging profile (see GFD.135) * (activity credentials) * * @author schuller */ public class HPCPUtils { private HPCPUtils(){} public final static QName AC_QNAME=new QName("http://schemas.ogf.org/hpcp/2007/11/ac","Credential"); public final static QName AC_USERNAME=new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd","Username"); public final static QName AC_PASSWD=new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd","Password"); public final static QName AC_QNAME_2=new QName("http://schemas.ogf.org/hpcp/2007/01/fs","Credential"); /** * Extracts username and password from the security credentials as defined in the HPC file staging profile (GFD.135) * <br/><br/> &lt;Credential xmlns="http://schemas.ogf.org/hpcp/2007/01/ac"&gt;<br/> &lt;UsernameToken xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">&gt;<br/> &lt;Username>sc07demo &lt;/Username&gt;<br/> &lt;Password>hpcpsc07 &lt;/Password&gt;<br/> &lt;/UsernameToken&gt;<br/> &lt;/Credential&gt;<br/> * <br/> * The first HPCP Activity Credential found in the given source document is used * * @param source - an XML document * @return {@link UsernamePassword} containing the username and password found in the XML */ public static UsernamePassword extractUsernamePassword(XmlObject source){ String user=null; String passwd=null; try{ XmlObject copy=source.copy(); XmlObject credential=XmlBeansUtils.extractFirstAnyElement(copy, AC_QNAME); if(credential==null){ //try namespace defined by GFD.135 (but not used in the example) credential=XmlBeansUtils.extractFirstAnyElement(copy, AC_QNAME_2); } if(credential!=null){ user=getUserName(credential); passwd=getPassword(credential); } }catch(Exception ex){ Log.logException("Problem extracting data staging credentials.", ex); } return new UsernamePassword(user, passwd); } /** * extract the username token * @param credentials * @return username or null if not found */ private static String getUserName(XmlObject credentials){ XmlCursor c=credentials.newCursor(); try{ int t; while(true){ t=c.toNextToken().intValue(); if(t==TokenType.INT_ENDDOC)return null; if(t==TokenType.INT_START){ if(AC_USERNAME.equals(c.getName())){ while(c.toNextToken().intValue()!=TokenType.INT_TEXT); String res=c.getChars().trim(); c.dispose(); return res; } } } }catch(Exception e){ } finally{ if(c!=null)c.dispose(); } return null; } /** * extract the password token * @param credentials * @return password or null if not found */ private static String getPassword(XmlObject credentials){ XmlCursor c=credentials.newCursor(); try{ int t; while(true){ t=c.toNextToken().intValue(); if(t==TokenType.INT_ENDDOC)return null; if(t==TokenType.INT_START){ if(AC_PASSWD.equals(c.getName())){ while(c.toNextToken().intValue()!=TokenType.INT_TEXT); String res=c.getChars().trim(); c.dispose(); return res; } } } }catch(Exception e){ } finally{ if(c!=null)c.dispose(); } return null; } public static XmlObject createCredentialsElement(String userName, String password){ XmlObject newXml = XmlObject.Factory.newInstance(); XmlCursor cursor = newXml.newCursor(); cursor.toNextToken(); cursor.beginElement(AC_QNAME); cursor.insertElementWithText(AC_USERNAME, userName); cursor.insertElementWithText(AC_PASSWD, password); cursor.dispose(); return newXml; } public static void appendDataStagingWithCredentials(DataStagingType dsType, String userName, String password){ WSUtilities.append(createCredentialsElement(userName, password), dsType); } }
9,491
0
Create_ds/airavata-sandbox/grid-tools/gsi-myproxy-client/src/test/java/org/apache/airavata/security
Create_ds/airavata-sandbox/grid-tools/gsi-myproxy-client/src/test/java/org/apache/airavata/security/myproxy/SecurityContextTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.security.myproxy; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.log4j.Logger; import org.globus.gsi.provider.GlobusProvider; import java.io.BufferedReader; import java.io.InputStreamReader; import java.security.Security; /** * User: AmilaJ (amilaj@apache.org) * Date: 5/23/13 * Time: 2:44 PM * NOTE : BEFORE RUNNING THESE TESTS UPDATE gsi-myproxy-client/src/test/resources/airavata-myproxy-client.properties * FILE WITH APPROPRIATE MY PROXY SERVER CONFIGURATIONS. */ public class SecurityContextTest extends TestCase { private String userName; private String password; private static final Logger log = Logger.getLogger(SecurityContext.class); static { Security.addProvider(new GlobusProvider()); } public void setUp() { this.userName = System.getProperty("myproxy.user"); this.password = System.getProperty("myproxy.password"); if (userName == null || password == null || userName.trim().equals("") || password.trim().equals("")) { log.error("===== Please set myproxy.user and myproxy.password system properties. ======="); Assert.fail("Please set myproxy.user and myproxy.password system properties."); } log.info("Using my proxy user name - " + userName); } public void testLogin() throws Exception { SecurityContext myProxy = new SecurityContext(userName, password); myProxy.login(); Assert.assertNotNull(myProxy.getGssCredential()); } public void testProxyCredentials() throws Exception { SecurityContext myProxy = new SecurityContext(userName, password); myProxy.login(); Assert.assertNotNull(myProxy.getProxyCredentials(myProxy.getGssCredential())); } /** * Before executing you need to add your host as a trusted renewer. * Execute following command * > myproxy-logon -t <LIFETIME></LIFETIME> -s <MY PROXY SERVER> -l <USER NAME> * E.g :- > myproxy-logon -t 264 -s myproxy.teragrid.org -l us3 * Enter MyProxy pass phrase: * A credential has been received for user us3 in /tmp/x509up_u501. * > myproxy-init -A --cert /tmp/x509up_u501 --key /tmp/x509up_u501 -l us3 -s myproxy.teragrid.org * @throws Exception */ public void testRenewCredentials() throws Exception { SecurityContext myProxy = new SecurityContext(userName, password); myProxy.login(); Assert.assertNotNull(myProxy.renewCredentials(myProxy.getGssCredential())); } }
9,492
0
Create_ds/airavata-sandbox/grid-tools/gsi-myproxy-client/src/main/java/org/apache/airavata/security
Create_ds/airavata-sandbox/grid-tools/gsi-myproxy-client/src/main/java/org/apache/airavata/security/myproxy/MyProxyCredentials.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.security.myproxy; import java.io.*; import java.security.PrivateKey; import java.security.cert.X509Certificate; import org.apache.log4j.Logger; import org.globus.gsi.GlobusCredential; import org.globus.gsi.X509Credential; import org.globus.gsi.gssapi.GlobusGSSCredentialImpl; import org.globus.myproxy.GetParams; import org.globus.myproxy.MyProxy; import org.ietf.jgss.GSSCredential; /** * Class to manipulate my proxy credentials. Responsible for retrieving, creating * my proxy credentials. */ public class MyProxyCredentials implements Serializable { private static final long serialVersionUID = -2471014486509046212L; protected String myProxyHostname; protected String myProxyUserName; protected String myProxyPassword; protected int myProxyPortNumber; protected int myProxyLifeTime = 14400; protected String trustedCertificatePath; private static final Logger log = Logger.getLogger(MyProxyCredentials.class); /** * Default constructor. */ public MyProxyCredentials() { } /** * Constructor. * @param myProxyServer Ip address of the my proxy server. * @param myProxyPort Port which my proxy server is running. * @param myProxyUsername User name to connect to my proxy server. * @param myProxyPassPhrase Password for my proxy authentication. * @param myProxyLifetime Lifetime of the retrieving credentials. * @param trustedCerts Trusted certificate location for SSL communication. */ public MyProxyCredentials(String myProxyServer, int myProxyPort, String myProxyUsername, String myProxyPassPhrase, int myProxyLifetime, String trustedCerts) { this.myProxyHostname = myProxyServer; this.myProxyPortNumber = myProxyPort; this.myProxyUserName = myProxyUsername; this.myProxyPassword = myProxyPassPhrase; this.myProxyLifeTime = myProxyLifetime; this.trustedCertificatePath = trustedCerts; init(); } /** * Gets the default proxy certificate. * @return Default my proxy credentials. * @throws Exception If an error occurred while retrieving credentials. */ public GSSCredential getDefaultCredentials() throws Exception { MyProxy myproxy = new MyProxy(this.myProxyHostname, this.myProxyPortNumber); return myproxy.get(this.myProxyUserName, this.myProxyPassword, this.myProxyLifeTime); } /** * Gets a new proxy certificate given current credentials. * @param credential The new proxy credentials. * @return The short lived GSSCredentials * @throws Exception If an error is occurred while retrieving credentials. */ public GSSCredential getProxyCredentials(GSSCredential credential) throws Exception { MyProxy myproxy = new MyProxy(this.myProxyHostname, this.myProxyPortNumber); return myproxy.get(credential, this.myProxyUserName, this.myProxyPassword, this.myProxyLifeTime); } /** * Renew GSSCredentials. * @param credential Credentials to be renewed. * @return Renewed credentials. * @throws Exception If an error occurred while renewing credentials. */ public GSSCredential renewCredentials(GSSCredential credential) throws Exception { MyProxy myproxy = new MyProxy(this.myProxyHostname, this.myProxyPortNumber); GetParams getParams = new GetParams(); getParams.setAuthzCreds(credential); getParams.setUserName(this.myProxyUserName); getParams.setLifetime(this.getMyProxyLifeTime()); return myproxy.get(credential, getParams); } public GSSCredential createCredentials(X509Certificate[] x509Certificates, PrivateKey privateKey) throws Exception { X509Credential newCredential = new X509Credential(privateKey, x509Certificates); return new GlobusGSSCredentialImpl(newCredential, GSSCredential.INITIATE_AND_ACCEPT); } public GSSCredential createCredentials(X509Certificate x509Certificate, PrivateKey privateKey) throws Exception { X509Certificate[] x509Certificates = new X509Certificate[1]; x509Certificates[0] = x509Certificate; return createCredentials(x509Certificates, privateKey); } public void init() { validateTrustedCertificatePath(); } private void validateTrustedCertificatePath() { File file = new File(this.trustedCertificatePath); if (!file.exists() || !file.canRead()) { File f = new File("."); System.out.println("Current directory " + f.getAbsolutePath()); throw new RuntimeException("Cannot read trusted certificate path " + this.trustedCertificatePath); } else { System.setProperty("X509_CERT_DIR", file.getAbsolutePath()); } } /** * @return the myProxyHostname */ public String getMyProxyHostname() { return myProxyHostname; } /** * @param myProxyHostname the myProxyHostname to set */ public void setMyProxyHostname(String myProxyHostname) { this.myProxyHostname = myProxyHostname; } /** * @return the myProxyUserName */ public String getMyProxyUserName() { return myProxyUserName; } /** * @param myProxyUserName the myProxyUserName to set */ public void setMyProxyUserName(String myProxyUserName) { this.myProxyUserName = myProxyUserName; } /** * @return the myProxyPassword */ public String getMyProxyPassword() { return myProxyPassword; } /** * @param myProxyPassword the myProxyPassword to set */ public void setMyProxyPassword(String myProxyPassword) { this.myProxyPassword = myProxyPassword; } /** * @return the myProxyLifeTime */ public int getMyProxyLifeTime() { return myProxyLifeTime; } /** * @param myProxyLifeTime the myProxyLifeTime to set */ public void setMyProxyLifeTime(int myProxyLifeTime) { this.myProxyLifeTime = myProxyLifeTime; } /** * @return the myProxyPortNumber */ public int getMyProxyPortNumber() { return myProxyPortNumber; } /** * @param myProxyPortNumber the myProxyPortNumber to set */ public void setMyProxyPortNumber(int myProxyPortNumber) { this.myProxyPortNumber = myProxyPortNumber; } public String getTrustedCertificatePath() { return trustedCertificatePath; } public void setTrustedCertificatePath(String trustedCertificatePath) { this.trustedCertificatePath = trustedCertificatePath; } /** * @return the portalUserName */ /*public String getPortalUserName() { return portalUserName; }*/ /** * @param portalUserName * the portalUserName to set */ /*public void setPortalUserName(String portalUserName) { this.portalUserName = portalUserName; }*/ /** * Returns the initialized. * * @return The initialized */ /*public boolean isInitialized() { return this.initialized; }*/ /** * Sets initialized. * * @param initialized * The initialized to set. */ /* public void setInitialized(boolean initialized) { this.initialized = initialized; }*/ /** * @param hostcertsKeyFile * the hostcertsKeyFile to set */ /*public void setHostcertsKeyFile(String hostcertsKeyFile) { this.hostcertsKeyFile = hostcertsKeyFile; }*/ /** * @return the hostcertsKeyFile */ /*public String getHostcertsKeyFile() { return hostcertsKeyFile; }*/ /** * @param trustedCertsFile * the trustedCertsFile to set */ /*public void setTrustedCertsFile(String trustedCertsFile) { this.trustedCertsFile = trustedCertsFile; }*/ /** * @return the trustedCertsFile */ /*public String getTrustedCertsFile() { return trustedCertsFile; }*/ }
9,493
0
Create_ds/airavata-sandbox/grid-tools/gsi-myproxy-client/src/main/java/org/apache/airavata/security
Create_ds/airavata-sandbox/grid-tools/gsi-myproxy-client/src/main/java/org/apache/airavata/security/myproxy/CertificateManager.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.security.myproxy; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import org.globus.gsi.util.CertificateLoadUtil; import org.globus.util.ClassLoaderUtils; public class CertificateManager { private static X509Certificate[] trustedCertificates; /** * Load CA certificates from a file included in the XBaya jar. * * @return The trusted certificates. */ public static X509Certificate[] getTrustedCertificate(String certificate) { if (trustedCertificates != null) { return trustedCertificates; } List<X509Certificate> extremeTrustedCertificates = getTrustedCertificates(certificate); List<X509Certificate> allTrustedCertificates = new ArrayList<X509Certificate>(); allTrustedCertificates.addAll(extremeTrustedCertificates); trustedCertificates = allTrustedCertificates.toArray(new X509Certificate[allTrustedCertificates.size()]); return trustedCertificates; } private static List<X509Certificate> getTrustedCertificates(String pass) { // ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); //** // InputStream stream = classLoader.getResourceAsStream(pass); //** InputStream stream = ClassLoaderUtils.getResourceAsStream(pass); // ** if (stream == null) { throw new RuntimeException("Failed to get InputStream to " + pass); } return readTrustedCertificates(stream); } /** * @param stream * @return List of X509Certificate */ public static List<X509Certificate> readTrustedCertificates(InputStream stream) { ArrayList<X509Certificate> certificates = new ArrayList<X509Certificate>(); while (true) { X509Certificate certificate; try { certificate = CertificateLoadUtil.loadCertificate(stream); } catch (GeneralSecurityException e) { String message = "Certificates are invalid"; throw new RuntimeException(message, e); } if (certificate == null) { break; } certificates.add(certificate); } return certificates; } }
9,494
0
Create_ds/airavata-sandbox/grid-tools/gsi-myproxy-client/src/main/java/org/apache/airavata/security
Create_ds/airavata-sandbox/grid-tools/gsi-myproxy-client/src/main/java/org/apache/airavata/security/myproxy/SecurityContext.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.security.myproxy; import java.io.File; import java.io.InputStream; import java.util.Properties; import org.apache.log4j.Logger; import org.globus.myproxy.MyProxy; import org.ietf.jgss.GSSCredential; public class SecurityContext { /** * */ public static final String MY_PROXY_CLIENT_PROPERTY = "airavata-myproxy-client.properties"; private Properties properties; protected GSSCredential gssCredential; private MyProxyCredentials myProxyCredentials; private static final Logger log = Logger.getLogger(SecurityContext.class); private String userName = null; private String password = null; /** * * Constructs a ApplicationGlobalContext. * * @throws Exception */ public SecurityContext() throws Exception { log.setLevel(org.apache.log4j.Level.INFO); loadConfiguration(); } public SecurityContext(String user, String pwd) throws Exception { this.userName = user; this.password = pwd; log.setLevel(org.apache.log4j.Level.INFO); loadConfiguration(); } /** * * @throws Exception */ public void login() throws Exception { gssCredential = myProxyCredentials.getDefaultCredentials(); } public GSSCredential getProxyCredentials(GSSCredential credential) throws Exception { return myProxyCredentials.getProxyCredentials(credential); } public GSSCredential renewCredentials(GSSCredential credential) throws Exception { return myProxyCredentials.renewCredentials(credential); } public static String getProperty(String name) { try { SecurityContext context = new SecurityContext(); return context.getProperties().getProperty(name); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Load the configration file * * @throws Exception */ private void loadConfiguration() throws Exception { try { System.out.println("In the load configurations method ....."); if (properties == null) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream propertyStream = classLoader.getResourceAsStream(MY_PROXY_CLIENT_PROPERTY); properties = new Properties(); if (myProxyCredentials == null) { this.myProxyCredentials = new MyProxyCredentials(); } if (propertyStream != null) { properties.load(propertyStream); String myproxyServerTmp = properties.getProperty(ServiceConstants.MYPROXY_SERVER); if (myproxyServerTmp != null) { this.myProxyCredentials.setMyProxyHostname(myproxyServerTmp.trim()); } String myproxyPortTemp = properties.getProperty(ServiceConstants.MYPROXY_PORT); if (myproxyPortTemp != null && myproxyPortTemp.trim().length() > 0) { this.myProxyCredentials.setMyProxyPortNumber(Integer.parseInt(myproxyPortTemp.trim())); } else { this.myProxyCredentials.setMyProxyPortNumber(MyProxy.DEFAULT_PORT); } this.myProxyCredentials.setMyProxyUserName(userName); this.myProxyCredentials.setMyProxyPassword(password); String myproxytime = properties.getProperty(ServiceConstants.MYPROXY_LIFETIME); if (myproxytime != null) { this.myProxyCredentials.setMyProxyLifeTime(Integer.parseInt(myproxytime)); } String currentDirectory = System.getProperty("projectDirectory"); String certificatePath = currentDirectory + File.separatorChar + properties.getProperty(ServiceConstants.TRUSTED_CERTS_FILE); this.myProxyCredentials.setTrustedCertificatePath(certificatePath); System.out.println("Certificate path - " + certificatePath); this.myProxyCredentials.init(); } } } catch (Exception e) { e.printStackTrace(); log.error(e.getLocalizedMessage()); throw new Exception(e); } } /** * @return the properties */ public Properties getProperties() { return properties; } /** * @param properties * the properties to set */ public void setProperties(Properties properties) { this.properties = properties; } /** * Returns the raw gssCredential, without creating a proxy. * * @return The gssCredential */ public GSSCredential getRawCredential() throws Exception{ return gssCredential; } /** * Returns the gssCredential. * * @return The gssCredential */ public GSSCredential getGssCredential() throws Exception{ if (this.gssCredential == null) return null; return renewCredentials(gssCredential); } /** * Sets gssCredential. * * @param gssCredential * The gssCredential to set. */ public void setGssCredential(GSSCredential gssCredential) { this.gssCredential = gssCredential; } public MyProxyCredentials getMyProxyCredentials() { return myProxyCredentials; } public void setMyProxyCredentials(MyProxyCredentials myProxyCredentials) { this.myProxyCredentials = myProxyCredentials; } }
9,495
0
Create_ds/airavata-sandbox/grid-tools/gsi-myproxy-client/src/main/java/org/apache/airavata/security
Create_ds/airavata-sandbox/grid-tools/gsi-myproxy-client/src/main/java/org/apache/airavata/security/myproxy/ServiceConstants.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.security.myproxy; public class ServiceConstants { public static final String MYPROXY_SERVER = "myproxyServer"; public static final String MYPROXY_PORT = "myproxyPort"; public static final String MYPROXY_LIFETIME = "myproxy_lifetime"; public static final String MYPROXY_USERNAME = "myproxyUserName"; public static final String MYPROXY_PASSWD = "myproxyPasswd"; public static final String TRUSTED_CERTS_FILE = "trustedCertsFile"; }
9,496
0
Create_ds/airavata-sandbox/grid-tools/gridftp-client/src/test/java/org/apache/airavata
Create_ds/airavata-sandbox/grid-tools/gridftp-client/src/test/java/org/apache/airavata/filetransfer/CertFileReadTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.filetransfer; import junit.framework.Assert; import org.bouncycastle.asn1.DEROutputStream; import org.bouncycastle.asn1.x500.*; import junit.framework.TestCase; import org.bouncycastle.asn1.ASN1Encodable; import org.bouncycastle.asn1.DEREncodable; import org.bouncycastle.asn1.DERObject; import org.bouncycastle.asn1.x509.X509Name; import org.bouncycastle.jce.X509Principal; import org.globus.gsi.SigningPolicy; import org.globus.gsi.SigningPolicyParser; import org.globus.gsi.util.CertificateIOUtil; import org.globus.util.GlobusResource; import org.junit.Ignore; import javax.security.auth.x500.X500Principal; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.Reader; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Map; /** * User: AmilaJ (amilaj@apache.org) * Date: 6/7/13 * Time: 9:57 AM */ @Ignore("This test case used to debug JGlobus-102. No need to run this test with other gridftp tests.") public class CertFileReadTest extends TestCase { private static MessageDigest md5; private static String CERT_FILE_LOCATION = "/Users/thejaka/development/apache/airavata/sandbox/grid-tools/gridftp-client/certificates/"; public void testCertFileRead() throws Exception { String path1 = CERT_FILE_LOCATION + "ffc3d59b"; String path2 = CERT_FILE_LOCATION + "e5cc84c2"; GlobusResource globusResource1 = new GlobusResource(path1 + ".signing_policy"); GlobusResource globusResource2 = new GlobusResource(path2 + ".signing_policy"); //GlobusResource globusResource3 = new GlobusResource("/Users/thejaka/development/apache/airavata/sandbox/grid-tools/gridftp-client/certificates/ef300431.signing_policy"); //GlobusResource globusResource4 = new GlobusResource("/Users/thejaka/development/apache/airavata/sandbox/grid-tools/gridftp-client/certificates/01b5d333.signing_policy"); //GlobusResource globusResource5 = new GlobusResource("/Users/thejaka/development/apache/airavata/sandbox/grid-tools/gridftp-client/certificates/081fefd0.signing_policy"); //ResourceSigningPolicy resourceSigningPolicy = new ResourceSigningPolicy(globusResource); // ===== Testing globusResource1 - This should pass (cos no DC components) ================ // X509Certificate crt1 = readCertificate(path1 + ".0"); X500Principal policySubjectCert1 = getPrincipal(globusResource1); String certHash1 = CertificateIOUtil.nameHash(crt1.getSubjectX500Principal()); String principalHash1 = CertificateIOUtil.nameHash(policySubjectCert1); System.out.println("======== Printing hashes for 1 ================"); System.out.println(certHash1); System.out.println(principalHash1); Assert.assertEquals("Certificate hash value does not match with the hash value generated using principal name.", certHash1, principalHash1); // ===== Testing globusResource1 - This should fail (cos we have DC components) ================ // X509Certificate crt2 = readCertificate(path2 + ".0"); X500Principal policySubjectCert2 = getPrincipal(globusResource2); String certHash2 = CertificateIOUtil.nameHash(crt2.getSubjectX500Principal()); String principalHash2 = CertificateIOUtil.nameHash(policySubjectCert2); System.out.println("======== Printing hashes for 2 ================"); System.out.println(certHash2); System.out.println(principalHash2); Assert.assertEquals("Certificate hash value does not match with the hash value generated using principal name.", certHash2, principalHash2); //X509Certificate crt = readCertificate(path1 + ".0"); //X509Certificate crt2 = readCertificate(path2 + ".0"); //System.out.println("======================================="); //System.out.println(crt.getIssuerX500Principal().getName()); //X500Principal certPrincipal = crt.getSubjectX500Principal(); //X500Principal policySubjectCert = getPrincipal(globusResource1); //"CN=TACC Classic CA,O=UT-AUSTIN,DC=TACC,DC=UTEXAS,DC=EDU" //X500Principal policySubjectCert = new X500Principal(certPrincipal.getName()); //System.out.println(CertificateIOUtil.nameHash(certPrincipal)); //System.out.println(CertificateIOUtil.nameHash((policySubjectCert))); //ByteArrayOutputStream bout = new ByteArrayOutputStream(); //DEROutputStream der = new DEROutputStream(bout); //der.writeObject(name.getDERObject()); //==================== //X500Principal certPrincipal2 = crt2.getSubjectX500Principal(); // X500Principal policySubjectCert = getPrincipal(globusResource1); //"CN=TACC Classic CA,O=UT-AUSTIN,DC=TACC,DC=UTEXAS,DC=EDU" //X500Principal policySubjectCert2 = new X500Principal(certPrincipal2.getName()); //System.out.println(CertificateIOUtil.nameHash(certPrincipal2)); //System.out.println(CertificateIOUtil.nameHash((policySubjectCert2))); //Assert.assertEquals(getHash(globusResource1), "e5cc84c2"); //Assert.assertEquals(getHash(globusResource2), "ffc3d59b"); //Assert.assertEquals(getHash(globusResource3), "ef300431"); //Assert.assertEquals(getHash(globusResource4), "01b5d333"); //Assert.assertEquals(getHash(globusResource5), "081fefd0"); } private String getHash(GlobusResource globusResource) throws Exception { X500Principal principal = getPrincipal(globusResource); System.out.println(principal.getName()); return CertificateIOUtil.nameHash(principal); } private X500Principal getPrincipal(GlobusResource globusResource) throws Exception{ SigningPolicyParser parser = new SigningPolicyParser(); Reader reader = new InputStreamReader(globusResource.getInputStream()); Map<X500Principal, SigningPolicy> policies = parser.parse(reader); return policies.keySet().iterator().next(); } private X509Certificate readCertificate(String certPath) { try { FileInputStream fr = new FileInputStream(certPath); CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate crt = (X509Certificate) cf.generateCertificate(fr); System.out.println("Read certificate:"); System.out.println("\tCertificate for: " + crt.getSubjectDN()); System.out.println("\tCertificate issued by: " + crt.getIssuerDN()); System.out.println("\tCertificate is valid from " + crt.getNotBefore() + " to " + crt.getNotAfter()); System.out.println("\tCertificate SN# " + crt.getSerialNumber()); System.out.println("\tGenerated with " + crt.getSigAlgName()); return crt; } catch (Exception e) { e.printStackTrace(); } return null; } private static synchronized String hash(byte[] data) { init(); if (md5 == null) { return null; } md5.reset(); md5.update(data); byte[] md = md5.digest(); long ret = (fixByte(md[0]) | (fixByte(md[1]) << 8L)); ret = ret | fixByte(md[2]) << 16L; ret = ret | fixByte(md[3]) << 24L; ret = ret & 0xffffffffL; return Long.toHexString(ret); } private static long fixByte(byte b) { return (b < 0) ? (long) (b + 256) : (long) b; } private static void init() { if (md5 == null) { try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } } }
9,497
0
Create_ds/airavata-sandbox/grid-tools/gridftp-client/src/test/java/org/apache/airavata
Create_ds/airavata-sandbox/grid-tools/gridftp-client/src/test/java/org/apache/airavata/filetransfer/FileTransferTest.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.filetransfer; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.airavata.filetransfer.utils.GridFtp; import org.apache.airavata.security.myproxy.SecurityContext; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.ietf.jgss.GSSCredential; import java.io.*; import java.net.URI; /** * User: AmilaJ (amilaj@apache.org) * Date: 5/31/13 * Time: 12:39 PM */ public class FileTransferTest extends TestCase { private GSSCredential gssCredential; private ExecutionContext executionContext; private static final Logger log = Logger.getLogger(FileTransferTest.class); public void setUp() throws Exception { String userName = System.getProperty("myproxy.user"); String password = System.getProperty("myproxy.password"); SecurityContext context = null; if (userName == null || password == null || userName.trim().equals("") || password.trim().equals("")) { log.error("myproxy.user and myproxy.password system properties are not set. Example :- " + "> mvn clean install -Dmyproxy.user=u1 -Dmyproxy.password=xxx"); Assert.fail("Please set myproxy.user and myproxy.password system properties."); } else { context = new SecurityContext(userName, password); } log.info("Using my proxy user name - " + userName); BasicConfigurator.configure(); Logger logger = Logger.getLogger("GridFTPClient"); Level lev = Level.toLevel("DEBUG"); logger.setLevel(lev); context.login(); executionContext = new ExecutionContext(); String targeterp = executionContext.getGridFTPServerDestination(); String remoteDestFile = executionContext.getDestinationDataLocation(); URI dirLocation = GridFtp.createGsiftpURI(targeterp, remoteDestFile.substring(0, remoteDestFile.lastIndexOf("/"))); gssCredential = context.getGssCredential(); System.out.println(dirLocation); } public void testMakeDir() throws Exception { String targetErp = executionContext.getGridFTPServerDestination(); String remoteDestinationFile = executionContext.getDestinationDataLocation(); URI dirLocation = GridFtp.createGsiftpURI(targetErp, remoteDestinationFile.substring(0, remoteDestinationFile.lastIndexOf("/"))); GridFtp ftp = new GridFtp(); ftp.makeDir(dirLocation, gssCredential); Assert.assertTrue(ftp.exists(dirLocation, gssCredential)); } public void testTransferData() throws Exception { String sourceERP = executionContext.getGridFTPServerSource(); String remoteSrcFile = executionContext.getSourceDataLocation(); String targetErp = executionContext.getGridFTPServerDestination(); String remoteDestinationFile = executionContext.getDestinationDataLocation(); URI srcURI = GridFtp.createGsiftpURI(sourceERP, remoteSrcFile); URI destURI = GridFtp.createGsiftpURI(targetErp, remoteDestinationFile); GridFtp ftp = new GridFtp(); ftp.transfer(srcURI, destURI, gssCredential, true); Assert.assertTrue(ftp.exists(destURI, gssCredential)); } public void testDownloadFile() throws Exception { String fileName = "./downloaded"; File deleteFile = new File(fileName); if (deleteFile.exists()) { if (!deleteFile.delete()) throw new RuntimeException("Unable to delete file " + fileName); } File f = new File(fileName); GridFtp ftp = new GridFtp(); ftp.downloadFile(executionContext.getSourceDataFileUri(), gssCredential, f); Assert.assertTrue(f.exists()); } public void testFileExists() throws Exception { GridFtp ftp = new GridFtp(); Assert.assertTrue(ftp.exists(executionContext.getSourceDataFileUri(), gssCredential)); } public void testUpdateFile() throws Exception { String currentDir = System.getProperty("projectDirectory"); if (currentDir == null) currentDir = "src/test/resources"; else currentDir = currentDir + "/src/test/resources"; String file = currentDir + "/dummy"; System.out.println("File to upload is " + file); File fileToUpload = new File(file); Assert.assertTrue(fileToUpload.canRead()); GridFtp ftp = new GridFtp(); ftp.updateFile(executionContext.getUploadingFilePathUri(), gssCredential, fileToUpload); Assert.assertTrue(ftp.exists(executionContext.getUploadingFilePathUri(), gssCredential)); } }
9,498
0
Create_ds/airavata-sandbox/grid-tools/gridftp-client/src/main/java/org/apache/airavata
Create_ds/airavata-sandbox/grid-tools/gridftp-client/src/main/java/org/apache/airavata/filetransfer/ExecutionContext.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.filetransfer; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Properties; import org.apache.airavata.filetransfer.utils.ServiceConstants; @SuppressWarnings("UnusedDeclaration") public class ExecutionContext { private String testingHost; private String loneStarGridFTP; private String rangerGridFTP; private String trestlesGridFTP; private String gridFTPServerSource; private String sourceDataLocation; private String gridFTPServerDestination; private String destinationDataLocation; private String uploadingFilePath; public static final String PROPERTY_FILE = "airavata-myproxy-client.properties"; public ExecutionContext() throws IOException { loadConfigurations(); } private void loadConfigurations() throws IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream propertyStream = classLoader.getResourceAsStream(PROPERTY_FILE); Properties properties = new Properties(); if (propertyStream != null) { properties.load(propertyStream); String testingHost = properties.getProperty(ServiceConstants.TESTINGHOST); String loneStarGridFtp = properties.getProperty(ServiceConstants.LONESTARGRIDFTPEPR); String rangerGridFtp = properties.getProperty(ServiceConstants.RANGERGRIDFTPEPR); String trestlesGridFtp = properties.getProperty(ServiceConstants.TRESTLESGRIDFTPEPR); String gridFTPServerSource = properties.getProperty(ServiceConstants.GRIDFTPSERVERSOURCE); String gridFTPSourcePath = properties.getProperty(ServiceConstants.GRIDFTPSOURCEPATH); String gridFTPServerDestination = properties.getProperty(ServiceConstants.GRIDFTPSERVERDEST); String gridFTPDestinationPath = properties.getProperty(ServiceConstants.GRIDFTPDESTPATH); String gridFTPUploadingPath = properties.getProperty(ServiceConstants.UPLOADING_FILE_PATH); if (testingHost != null) { this.testingHost = testingHost; } if (loneStarGridFtp != null) { this.loneStarGridFTP = loneStarGridFtp; } if (rangerGridFtp != null) { this.rangerGridFTP= rangerGridFtp; } if (trestlesGridFtp != null) { this.trestlesGridFTP = trestlesGridFtp; } if (gridFTPServerSource != null && !gridFTPServerSource.isEmpty()) { this.gridFTPServerSource = gridFTPServerSource; } if (gridFTPSourcePath != null && !gridFTPSourcePath.isEmpty()) { this.sourceDataLocation = gridFTPSourcePath; } if (gridFTPServerDestination != null && !gridFTPServerDestination.isEmpty()) { this.gridFTPServerDestination = gridFTPServerDestination; } if (gridFTPDestinationPath != null && !gridFTPDestinationPath.isEmpty()) { this.destinationDataLocation = gridFTPDestinationPath; } if (gridFTPUploadingPath != null && !gridFTPUploadingPath.isEmpty()) { this.uploadingFilePath = gridFTPUploadingPath; } } } public String getTestingHost() { return testingHost; } public void setTestingHost(String testingHost) { this.testingHost = testingHost; } public String getLoneStarGridFTP() { return loneStarGridFTP; } public void setLoneStarGridFTP(String loneStarGridFTP) { this.loneStarGridFTP = loneStarGridFTP; } public String getRangerGridFTP() { return rangerGridFTP; } public void setRangerGridFTP(String rangerGridFTP) { this.rangerGridFTP = rangerGridFTP; } public String getTrestlesGridFTP() { return trestlesGridFTP; } public void setTrestlesGridFTP(String trestlesGridFTP) { this.trestlesGridFTP = trestlesGridFTP; } public String getGridFTPServerSource() { return gridFTPServerSource; } public void setGridFTPServerSource(String gridFTPServerSource) { this.gridFTPServerSource = gridFTPServerSource; } public URI getSourceDataFileUri() throws URISyntaxException { String file = gridFTPServerSource + getSourceDataLocation(); return new URI(file); } public URI getUploadingFilePathUri() throws URISyntaxException { String file = gridFTPServerSource + getUploadingFilePath(); return new URI(file); } public String getUploadingFilePath() { return uploadingFilePath; } public void setUploadingFilePath(String uploadingFilePath) { this.uploadingFilePath = uploadingFilePath; } public String getSourceDataLocation() { return sourceDataLocation; } public void setSourceDataLocation(String sourceDataLocation) { this.sourceDataLocation = sourceDataLocation; } public String getGridFTPServerDestination() { return gridFTPServerDestination; } public void setGridFTPServerDestination(String gridFTPServerDestination) { this.gridFTPServerDestination = gridFTPServerDestination; } public String getDestinationDataLocation() { return destinationDataLocation; } public void setDestinationDataLocation(String destinationDataLocation) { this.destinationDataLocation = destinationDataLocation; } }
9,499