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/airavata-layered-architecture/src/test/java/org/apache/airavata/applications
Create_ds/airavata-sandbox/airavata-layered-architecture/src/test/java/org/apache/airavata/applications/hpc/HPCApplicationTest.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.applications.hpc; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.UUID; public class HPCApplicationTest { private final static Logger logger = LoggerFactory.getLogger(HPCApplicationTest.class); @Test public void testTensorFlow() throws Exception { Map<String, String> inputs = new HashMap<>(); inputs.put("code_tf.py", HPCApplicationTest.class.getClassLoader().getResource("code_tf.py").getPath()); TensorFlow tensorflow = new TensorFlow("tensorflow", inputs); String routingKey = UUID.randomUUID().toString(); HPCApplicationExecutor hpcApplicationExecutor = new HPCApplicationExecutor(); String computerResource = "bigred2.uits.iu.edu"; hpcApplicationExecutor.executeApplication(routingKey, tensorflow, computerResource, tensorflow.getJobSpecification(computerResource)); } }
8,900
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/test/java/org/apache/airavata/runners
Create_ds/airavata-sandbox/airavata-layered-architecture/src/test/java/org/apache/airavata/runners/ssh/SSHRunnerTest.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.runners.ssh; import org.apache.airavata.models.Constants; import org.apache.airavata.models.runners.ssh.SSHKeyAuthentication; import org.apache.airavata.models.runners.ssh.SSHServerInfo; import org.apache.commons.io.IOUtils; import org.junit.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.UUID; public class SSHRunnerTest { private final static Logger logger = LoggerFactory.getLogger(SSHRunnerTest.class); @Test public void test() { try{ SSHKeyAuthentication br2SshAuthentication = new SSHKeyAuthentication( Constants.loginUserName, IOUtils.toByteArray(SSHRunnerTest.class.getClassLoader().getResourceAsStream("ssh/id_rsa")), IOUtils.toByteArray(SSHRunnerTest.class.getClassLoader().getResourceAsStream("ssh/id_rsa.pub")), "dummy", SSHRunnerTest.class.getClassLoader().getResource("ssh/known_hosts").getPath(), false ); SSHServerInfo br2 = new SSHServerInfo(Constants.loginUserName, "bigred2.uits.iu.edu", br2SshAuthentication,22); String routingKey = UUID.randomUUID().toString(); SSHRunner sshExecutor = new SSHRunner(); sshExecutor.executeCommand(routingKey, "mkdir -p airavata", br2, br2SshAuthentication); sshExecutor.scpTo(routingKey, SSHRunnerTest.class.getClassLoader().getResource("job_tf.pbs").getPath(), "~/airavata/", br2, br2SshAuthentication); sshExecutor.scpTo(routingKey, SSHRunnerTest.class.getClassLoader().getResource("code_tf.py").getPath(), "~/airavata/", br2, br2SshAuthentication); sshExecutor.executeCommand(routingKey, new String[]{"cd ~/airavata", "qsub ~/airavata/job_tf.pbs"}, br2, br2SshAuthentication); }catch (Exception ex){ ex.printStackTrace(); Assert.fail(); } } }
8,901
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/resources
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/resources/batch/BigRed2.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.resources.batch; import org.apache.airavata.models.*; import org.apache.airavata.models.resources.Authentication; import org.apache.airavata.models.resources.ServerInfo; import org.apache.airavata.models.resources.hpc.JobManagerConfiguration; import org.apache.airavata.models.resources.hpc.PBSJobConfiguration; import org.apache.airavata.models.runners.ssh.SSHKeyAuthentication; import org.apache.airavata.models.runners.ssh.SSHServerInfo; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; public class BigRed2 extends HPCBatchResource { private final static Logger logger = LoggerFactory.getLogger(BigRed2.class); public BigRed2(ServerInfo serverInfo, JobManagerConfiguration jobManagerConfiguration, Authentication authentication) throws Exception { super(serverInfo, jobManagerConfiguration, authentication); } public BigRed2() throws Exception { //These should be read from a database. For simplicity I have hardcoded them SSHKeyAuthentication br2SshAuthentication = new SSHKeyAuthentication( Constants.loginUserName, IOUtils.toByteArray(BigRed2.class.getClassLoader().getResourceAsStream("ssh/id_rsa")), IOUtils.toByteArray(BigRed2.class.getClassLoader().getResourceAsStream("ssh/id_rsa.pub")), "dummy", BigRed2.class.getClassLoader().getResource("ssh/known_hosts").getPath(), false ); SSHServerInfo br2 = new SSHServerInfo(Constants.loginUserName, "bigred2.uits.iu.edu", br2SshAuthentication,22); Map<JobManagerConfiguration.JobManagerCommand, String> jobManagerCommands = new HashMap<>(); jobManagerCommands.put(JobManagerConfiguration.JobManagerCommand.SUBMISSION, "qsub"); jobManagerCommands.put(JobManagerConfiguration.JobManagerCommand.JOB_MONITORING, "qstat"); jobManagerCommands.put(JobManagerConfiguration.JobManagerCommand.DELETION, "qdel"); JobManagerConfiguration pbsJobConfiguration = new PBSJobConfiguration(PBSJobConfiguration.class.getClassLoader(). getResource("resources/batch/PBS_Groovy.template").getPath(), ".pbs", "/opt/torque/torque-5.0.1/bin", jobManagerCommands, new BatchJobOutputParser()); this.serverInfo = (SSHServerInfo) br2; this.authentication = (SSHKeyAuthentication) br2SshAuthentication; this.jobManagerConfiguration = pbsJobConfiguration; this.outputParser = jobManagerConfiguration.getParser(); } }
8,902
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/resources
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/resources/batch/HPCBatchResource.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.resources.batch; import com.jcraft.jsch.JSchException; import groovy.lang.*; import groovy.text.GStringTemplateEngine; import groovy.text.TemplateEngine; import org.apache.airavata.models.resources.Authentication; import org.apache.airavata.models.resources.JobSubmissionOutput; import org.apache.airavata.models.resources.ServerInfo; import org.apache.airavata.models.resources.hpc.*; import org.apache.airavata.models.resources.hpc.Script; import org.apache.airavata.models.runners.ssh.SSHKeyAuthentication; import org.apache.airavata.models.runners.ssh.SSHServerInfo; import org.apache.airavata.runners.ssh.SSHCommandOutputReader; import org.apache.airavata.runners.ssh.SSHRunner; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.net.URL; public class HPCBatchResource { private final static Logger logger = LoggerFactory.getLogger(HPCBatchResource.class); private static final int MAX_RETRY_COUNT = 3; protected ServerInfo serverInfo; protected Authentication authentication; protected JobManagerConfiguration jobManagerConfiguration; protected OutputParser outputParser; public HPCBatchResource(ServerInfo serverInfo, JobManagerConfiguration jobManagerConfiguration, Authentication authentication) throws Exception { if(!(serverInfo instanceof SSHServerInfo) || !(authentication instanceof SSHKeyAuthentication)){ throw new Exception("Currently only SSH based communication is enabled for HPCRemote clusters"); } if(!(jobManagerConfiguration instanceof PBSJobConfiguration)){ throw new Exception("Currently only PBS job configuration is enabled"); } this.serverInfo = (SSHServerInfo) serverInfo; this.authentication = (SSHKeyAuthentication) authentication; this.jobManagerConfiguration = jobManagerConfiguration; this.outputParser = jobManagerConfiguration.getParser(); } public HPCBatchResource() {} public JobSubmissionOutput submitBatchJob(String routingKey, GroovyMap groovyMap) throws Exception { File tempJobFile = File.createTempFile("temp_job", jobManagerConfiguration.getScriptExtension()); FileUtils.writeStringToFile(tempJobFile, generateScript(groovyMap)); String workingDirectory = groovyMap.get(Script.WORKING_DIR).toString(); String jobScriptFilePath = tempJobFile.getPath(); JobSubmissionOutput jsoutput = new JobSubmissionOutput(); copyTo(routingKey, jobScriptFilePath, workingDirectory+"/demo_job" + jobManagerConfiguration.getScriptExtension()); // scp script file to working directory RawCommandInfo submitCommand = jobManagerConfiguration.getSubmitCommand(workingDirectory, workingDirectory+"/demo_job" + jobManagerConfiguration.getScriptExtension()); submitCommand.setRawCommand("cd " + workingDirectory + " && " + submitCommand.getRawCommand()); SSHCommandOutputReader reader = executeCommand(routingKey, submitCommand); jsoutput.setJobId(outputParser.parseJobSubmission(reader.getStdOutputString())); if (jsoutput.getJobId() == null) { if (outputParser.isJobSubmissionFailed(reader.getStdOutputString())) { jsoutput.setJobSubmissionFailed(true); jsoutput.setFailureReason("stdout : " + reader.getStdOutputString() + "\n stderr : " + reader.getStdErrorString()); } } jsoutput.setExitCode(reader.getExitCode()); if (jsoutput.getExitCode() != 0) { jsoutput.setJobSubmissionFailed(true); jsoutput.setFailureReason("stdout : " + reader.getStdOutputString() + "\n stderr : " + reader.getStdErrorString()); } jsoutput.setStdOut(reader.getStdOutputString()); jsoutput.setStdErr(reader.getStdErrorString()); return jsoutput; } public void copyTo(String routingKey, String localFile, String remoteFile) throws Exception { int retry = 3; while (retry > 0) { try { SSHRunner sshRunner = new SSHRunner(); logger.info("Transferring localhost:" + localFile + " to " + serverInfo.getHost() + ":" + remoteFile); sshRunner.scpTo("", localFile, remoteFile, (SSHServerInfo) serverInfo, (SSHKeyAuthentication) authentication); retry = 0; } catch (Exception e) { retry--; if (retry == 0) { throw new Exception("Failed to scp localhost:" + localFile + " to " + serverInfo.getHost() + ":" + remoteFile, e); } else { logger.info("Retry transfer localhost:" + localFile + " to " + serverInfo.getHost() + ":" + remoteFile); } } } } public void copyFrom(String routingKey, String remoteFile, String localFile) throws Exception { int retry = 0; while(retry < MAX_RETRY_COUNT) { try { logger.info("Transferring " + serverInfo.getHost() + ":" + remoteFile + " To localhost:" + localFile); SSHRunner sshRunner = new SSHRunner(); sshRunner.scpFrom(routingKey, remoteFile, localFile, (SSHServerInfo) serverInfo, (SSHKeyAuthentication)authentication); retry=0; } catch (Exception e) { retry++; if (retry == 0) { throw new Exception("Failed to scp " + serverInfo.getHost() + ":" + remoteFile + " to " + "localhost:" + localFile, e); } else { logger.info("Retry transfer " + serverInfo.getHost() + ":" + remoteFile + " to localhost:" + localFile); } } } } public void makeDirectory(String routingKey, String directoryPath) throws Exception { int retryCount = 0; try { while (retryCount < MAX_RETRY_COUNT) { retryCount++; logger.info("Creating directory: " + serverInfo.getHost() + ":" + directoryPath); try { SSHRunner sshRunner = new SSHRunner(); sshRunner.makeDirectory(routingKey, directoryPath, (SSHServerInfo) serverInfo, (SSHKeyAuthentication)authentication); break; // Exit while loop } catch (JSchException e) { if (retryCount == MAX_RETRY_COUNT) { logger.error("Retry count " + MAX_RETRY_COUNT + " exceeded for creating directory: " + serverInfo.getHost() + ":" + directoryPath, e); throw e; } logger.error("Issue with jsch, Retry creating directory: " + serverInfo.getHost() + ":" + directoryPath); } } } catch (JSchException | IOException e) { throw new Exception("Failed to create directory " + serverInfo.getHost() + ":" + directoryPath, e); } } private SSHCommandOutputReader executeCommand(String routingKey, RawCommandInfo commandInfo) throws Exception { String command = commandInfo.getCommand(); int retryCount = 0; try { while (retryCount < MAX_RETRY_COUNT) { retryCount++; SSHRunner sshRunner = new SSHRunner(); SSHCommandOutputReader commandOutput = sshRunner.executeCommand(routingKey, command, (SSHServerInfo)serverInfo, (SSHKeyAuthentication)authentication); logger.info("Executing command {}", commandInfo.getCommand()); return commandOutput; } throw new Exception("Unable to execute command after "+retryCount+" retry attempts - " + command); } catch (JSchException e) { throw new Exception("Unable to execute command - " + command, e); } } private String generateScript(GroovyMap groovyMap) throws Exception { URL templateUrl = new URL("file://"+jobManagerConfiguration.getJobDescriptionTemplateName()); if (templateUrl == null) { String error = "Template file '" + jobManagerConfiguration.getJobDescriptionTemplateName() + "' not found"; throw new Exception(error); } File template = new File(templateUrl.getPath()); TemplateEngine engine = new GStringTemplateEngine(); Writable make; try { make = engine.createTemplate(template).make(groovyMap); } catch (Exception e) { throw new Exception("Error while generating script using groovy map"); } return make.toString(); } }
8,903
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/resources
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/resources/batch/BatchJobOutputParser.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.resources.batch; import org.apache.airavata.models.resources.JobStatus; import org.apache.airavata.models.resources.hpc.OutputParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; public class BatchJobOutputParser implements OutputParser { private final static Logger logger = LoggerFactory.getLogger(BatchJobOutputParser.class); /** * This can be used to parseSingleJob the result of a job submission to get the JobID * * @param rawOutput * @return the job id as a String, or null if no job id found */ @Override public String parseJobSubmission(String rawOutput) throws Exception { return null; } /** * Parse output return by job submission task and identify jobSubmission failures. * * @param rawOutput * @return true if job submission has been failed, false otherwise. */ @Override public boolean isJobSubmissionFailed(String rawOutput) { return false; } /** * This can be used to get the job status from the output * * @param jobID * @param rawOutput */ @Override public JobStatus parseJobStatus(String jobID, String rawOutput) throws Exception { return null; } /** * This can be used to parseSingleJob a big output and get multipleJob statuses * * @param userName * @param statusMap list of status map will return and key will be the job ID * @param rawOutput */ @Override public void parseJobStatuses(String userName, Map<String, JobStatus> statusMap, String rawOutput) throws Exception { } /** * filter the jobId value of given JobName from rawOutput * * @param jobName * @param rawOutput * @return * @throws Exception */ @Override public String parseJobId(String jobName, String rawOutput) throws Exception { return null; } }
8,904
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/Constants.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.models; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Constants { private final static Logger logger = LoggerFactory.getLogger(Constants.class); public static final String loginUserName = "snakanda"; }
8,905
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources/JobSubmissionOutput.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.models.resources; public class JobSubmissionOutput { private int exitCode = Integer.MIN_VALUE; private String stdOut; private String stdErr; private String command; private String jobId; private boolean isJobSubmissionFailed; private String failureReason; public int getExitCode() { return exitCode; } public void setExitCode(int exitCode) { this.exitCode = exitCode; } public String getStdOut() { return stdOut; } public void setStdOut(String stdOut) { this.stdOut = stdOut; } public String getStdErr() { return stdErr; } public void setStdErr(String stdErr) { this.stdErr = stdErr; } public String getCommand() { return command; } public void setCommand(String command) { this.command = command; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public boolean isJobSubmissionFailed() { return isJobSubmissionFailed; } public void setJobSubmissionFailed(boolean jobSubmissionFailed) { isJobSubmissionFailed = jobSubmissionFailed; } public String getFailureReason() { return failureReason; } public void setFailureReason(String failureReason) { this.failureReason = failureReason; } }
8,906
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources/ServerInfo.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.models.resources; public class ServerInfo { public static enum ComProtocol {SSH, LOCAL} protected String host; protected String userName; protected int port; protected ComProtocol comProtocol; public ServerInfo(){} public ServerInfo(String userName, String host, ComProtocol comProtocol, int port) { this.userName = userName; this.host = host; this.comProtocol = comProtocol; this.port = port; } public String getHost() { return host; } public String getUserName() { return userName; } }
8,907
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources/Authentication.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.models.resources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Authentication { private final static Logger logger = LoggerFactory.getLogger(Authentication.class); protected String userName; }
8,908
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources/JobStatus.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.models.resources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class JobStatus { private final static Logger logger = LoggerFactory.getLogger(JobStatus.class); }
8,909
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources/CommandOutput.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.models.resources; import com.jcraft.jsch.Channel; import java.io.OutputStream; /** * Output of a certain command. */ public interface CommandOutput { /** * Gets the output of the command as a stream. * @param channel Command output as a stream. */ void onOutput(Channel channel); /** * Gets standard error as a output stream. * @return Command error as a stream. */ OutputStream getStandardError(); /** * The command exit code. * @param code The program exit code */ void exitCode(int code); /** * Return the exit code of the command execution. * @return exit code */ int getExitCode(); }
8,910
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources/hpc/GroovyMap.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.models.resources.hpc; import java.util.HashMap; import java.util.Optional; public class GroovyMap extends HashMap<String, Object> { public GroovyMap() { super(); // to mitigate groovy exception groovy.lang.MissingPropertyException: No such property: <name> for class: groovy.lang.Binding addDefaultValues(); } public GroovyMap add(Script name, Object value){ put(name.name, value); return this; } @Override public Object get(Object key) { return super.getOrDefault(key, null); } public Object get(Script script) { return get(script.name); } public Optional<String> getStringValue(Script script) { Object obj = get(script); if (obj instanceof String) { return Optional.of((String) obj); } else if (obj == null) { return Optional.empty(); } else { throw new IllegalArgumentException("Value is not String type"); } } private void addDefaultValues() { this.add(Script.SHELL_NAME, null) .add(Script.QUEUE_NAME, null) .add(Script.NODES, null) .add(Script.CPU_COUNT, null) .add(Script.MAIL_ADDRESS, null) .add(Script.ACCOUNT_STRING, null) .add(Script.MAX_WALL_TIME, null) .add(Script.JOB_NAME, null) .add(Script.STANDARD_OUT_FILE, null) .add(Script.STANDARD_ERROR_FILE, null) .add(Script.QUALITY_OF_SERVICE, null) .add(Script.RESERVATION, null) .add(Script.EXPORTS, null) .add(Script.MODULE_COMMANDS, null) .add(Script.SCRATCH_LOCATION, null) .add(Script.WORKING_DIR, null) .add(Script.PRE_JOB_COMMANDS, null) .add(Script.JOB_SUBMITTER_COMMAND, null) .add(Script.EXECUTABLE_PATH, null) .add(Script.INPUTS, null) .add(Script.POST_JOB_COMMANDS, null) .add(Script.USED_MEM, null) .add(Script.PROCESS_PER_NODE, null) .add(Script.CHASSIS_NAME, null) .add(Script.INPUT_DIR, null) .add(Script.OUTPUT_DIR, null) .add(Script.USER_NAME, null) .add(Script.GATEWAY_ID, null) .add(Script.GATEWAY_USER_NAME, null) .add(Script.APPLICATION_NAME, null); } }
8,911
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources/hpc/PBSJobConfiguration.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.models.resources.hpc; import org.apache.commons.io.FilenameUtils; import java.io.File; import java.util.Map; public class PBSJobConfiguration implements JobManagerConfiguration { private final Map<JobManagerCommand, String> jobManagerCommands; private String jobDescriptionTemplateName; private String scriptExtension; private String installedPath; private OutputParser parser; public PBSJobConfiguration(String jobDescriptionTemplateName, String scriptExtension, String installedPath, Map<JobManagerCommand, String> jobManagerCommands, OutputParser parser) { this.jobDescriptionTemplateName = jobDescriptionTemplateName; this.scriptExtension = scriptExtension; this.parser = parser; installedPath = installedPath.trim(); if (installedPath.endsWith("/")) { this.installedPath = installedPath; } else { this.installedPath = installedPath + "/"; } this.jobManagerCommands = jobManagerCommands; } public RawCommandInfo getCancelCommand(String jobID) { return new RawCommandInfo(this.installedPath + jobManagerCommands.get(JobManagerCommand.DELETION).trim() + " " + jobID); } public String getJobDescriptionTemplateName() { return jobDescriptionTemplateName; } public void setJobDescriptionTemplateName(String jobDescriptionTemplateName) { this.jobDescriptionTemplateName = jobDescriptionTemplateName; } public RawCommandInfo getMonitorCommand(String jobID) { return new RawCommandInfo(this.installedPath + jobManagerCommands.get(JobManagerCommand.JOB_MONITORING).trim() + " -f " + jobID); } public String getScriptExtension() { return scriptExtension; } public RawCommandInfo getSubmitCommand(String workingDirectory, String pbsFilePath) { return new RawCommandInfo(this.installedPath + jobManagerCommands.get(JobManagerCommand.SUBMISSION).trim() + " " + workingDirectory + File.separator + FilenameUtils.getName(pbsFilePath)); } public String getInstalledPath() { return installedPath; } public void setInstalledPath(String installedPath) { this.installedPath = installedPath; } public OutputParser getParser() { return parser; } public void setParser(OutputParser parser) { this.parser = parser; } public RawCommandInfo getUserBasedMonitorCommand(String userName) { return new RawCommandInfo(this.installedPath + jobManagerCommands.get(JobManagerCommand.JOB_MONITORING).trim() + " -u " + userName); } @Override public RawCommandInfo getJobIdMonitorCommand(String jobName, String userName) { // For PBS there is no option to get jobDetails by JobName, so we search with userName return new RawCommandInfo(this.installedPath + jobManagerCommands.get(JobManagerCommand.JOB_MONITORING).trim() + " -u " + userName + " -f | grep \"Job_Name = " + jobName + "\" -B1"); } @Override public String getBaseCancelCommand() { return jobManagerCommands.get(JobManagerCommand.DELETION).trim(); } @Override public String getBaseMonitorCommand() { return jobManagerCommands.get(JobManagerCommand.JOB_MONITORING).trim(); } @Override public String getBaseSubmitCommand() { return jobManagerCommands.get(JobManagerCommand.SUBMISSION).trim(); } }
8,912
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources/hpc/Script.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.models.resources.hpc; public enum Script { SHELL_NAME("shellName"), QUEUE_NAME("queueName"), NODES("nodes"), CPU_COUNT("cpuCount"), MAIL_ADDRESS("mailAddress"), ACCOUNT_STRING("accountString"), MAX_WALL_TIME("maxWallTime"), JOB_NAME("jobName"), STANDARD_OUT_FILE("standardOutFile"), STANDARD_ERROR_FILE("standardErrorFile"), QUALITY_OF_SERVICE("qualityOfService"), RESERVATION("reservation"), EXPORTS("exports"), MODULE_COMMANDS("moduleCommands"), SCRATCH_LOCATION("scratchLocation"), WORKING_DIR("workingDirectory"), PRE_JOB_COMMANDS("preJobCommands"), JOB_SUBMITTER_COMMAND("jobSubmitterCommand"), EXECUTABLE_PATH("executablePath"), INPUTS("inputs"), POST_JOB_COMMANDS("postJobCommands"), USED_MEM("usedMem"), PROCESS_PER_NODE("processPerNode"), CHASSIS_NAME("chassisName"), INPUT_DIR("inputDir"), OUTPUT_DIR("outputDir"), USER_NAME("userName"), GATEWAY_ID("gatewayId"), GATEWAY_USER_NAME("gatewayUserName"), APPLICATION_NAME("applicationName"), ; String name; Script(String name) { this.name = name; } }
8,913
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources/hpc/OutputParser.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.models.resources.hpc; import org.apache.airavata.models.resources.JobStatus; import java.util.Map; public interface OutputParser { /** * This can be used to parseSingleJob the result of a job submission to get the JobID * @param rawOutput * @return the job id as a String, or null if no job id found */ public String parseJobSubmission(String rawOutput)throws Exception; /** * Parse output return by job submission task and identify jobSubmission failures. * @param rawOutput * @return true if job submission has been failed, false otherwise. */ public boolean isJobSubmissionFailed(String rawOutput); /** * This can be used to get the job status from the output * @param jobID * @param rawOutput */ public JobStatus parseJobStatus(String jobID, String rawOutput)throws Exception; /** * This can be used to parseSingleJob a big output and get multipleJob statuses * @param statusMap list of status map will return and key will be the job ID * @param rawOutput */ public void parseJobStatuses(String userName, Map<String, JobStatus> statusMap, String rawOutput)throws Exception; /** * filter the jobId value of given JobName from rawOutput * @param jobName * @param rawOutput * @return * @throws Exception */ public String parseJobId(String jobName, String rawOutput) throws Exception; }
8,914
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources/hpc/RawCommandInfo.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.models.resources.hpc; public class RawCommandInfo { private String rawCommand; public RawCommandInfo(String cmd) { this.rawCommand = cmd; } public String getCommand() { return this.rawCommand; } public String getRawCommand() { return rawCommand; } public void setRawCommand(String rawCommand) { this.rawCommand = rawCommand; } }
8,915
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/resources/hpc/JobManagerConfiguration.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.models.resources.hpc; public interface JobManagerConfiguration { public static enum JobManagerCommand{JOB_MONITORING, SUBMISSION, DELETION}; public RawCommandInfo getCancelCommand(String jobID); public String getJobDescriptionTemplateName(); public RawCommandInfo getMonitorCommand(String jobID); public RawCommandInfo getUserBasedMonitorCommand(String userName); public RawCommandInfo getJobIdMonitorCommand(String jobName , String userName); public String getScriptExtension(); public RawCommandInfo getSubmitCommand(String workingDirectory, String pbsFilePath); public OutputParser getParser(); public String getInstalledPath(); public String getBaseCancelCommand(); public String getBaseMonitorCommand(); public String getBaseSubmitCommand(); }
8,916
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/runners
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/runners/ssh/SSHApiException.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.models.runners.ssh; /** * An exception class to wrap SSH command execution related errors. */ public class SSHApiException extends Exception { public SSHApiException(String message) { super(message); } public SSHApiException(String message, Exception e) { super(message, e); } }
8,917
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/runners
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/runners/ssh/SSHUserInfo.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.models.runners.ssh; import com.jcraft.jsch.UserInfo; public class SSHUserInfo implements UserInfo { private String userName; private String password; private String passphrase; public SSHUserInfo(String userName, String password, String passphrase) { this.userName = userName; this.password = password; this.passphrase = passphrase; } @Override public String getPassphrase() { return null; } @Override public String getPassword() { return null; } @Override public boolean promptPassword(String s) { return false; } @Override public boolean promptPassphrase(String s) { return false; } @Override public boolean promptYesNo(String s) { return false; } @Override public void showMessage(String s) { } }
8,918
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/runners
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/runners/ssh/SSHServerInfo.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.models.runners.ssh; import org.apache.airavata.models.resources.ServerInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SSHServerInfo extends ServerInfo { private final static Logger logger = LoggerFactory.getLogger(SSHServerInfo.class); SSHKeyAuthentication authentication; int sshPort; public SSHServerInfo(String userName, String host, SSHKeyAuthentication authentication, int port){ super(userName, host, ComProtocol.SSH, port); this.authentication = authentication; this.sshPort = port; } public SSHServerInfo(String userName, String host, SSHKeyAuthentication authentication){ super(userName, host, ComProtocol.SSH, 22); this.authentication = authentication; this.sshPort = 22; } public SSHKeyAuthentication getAuthentication() { return authentication; } public int getSshPort() { return sshPort; } }
8,919
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/runners
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/models/runners/ssh/SSHKeyAuthentication.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.models.runners.ssh; import org.apache.airavata.models.resources.Authentication; public class SSHKeyAuthentication extends Authentication { private byte[] privateKey; private byte[] publicKey; private String passphrase; private String knownHostsFilePath; private String strictHostKeyChecking; // yes or no public SSHKeyAuthentication(String userName, byte[] privateKey, byte[] publicKey, String passphrase, String knownHostsFilePath, boolean strictHostKeyChecking) { this.userName = userName; this.privateKey = privateKey; this.publicKey = publicKey; this.passphrase = passphrase; this.knownHostsFilePath = knownHostsFilePath; if(strictHostKeyChecking){ this.strictHostKeyChecking = "yes"; }else{ this.strictHostKeyChecking = "no"; } } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public byte[] getPrivateKey() { return privateKey; } public void setPrivateKey(byte[] privateKey) { this.privateKey = privateKey; } public byte[] getPublicKey() { return publicKey; } public void setPublicKey(byte[] publicKey) { this.publicKey = publicKey; } public String getPassphrase() { return passphrase; } public void setPassphrase(String passphrase) { this.passphrase = passphrase; } public String getKnownHostsFilePath() { return knownHostsFilePath; } public void setKnownHostsFilePath(String knownHostsFilePath) { this.knownHostsFilePath = knownHostsFilePath; } public String getStrictHostKeyChecking() { return strictHostKeyChecking; } public void setStrictHostKeyChecking(String strictHostKeyChecking) { this.strictHostKeyChecking = strictHostKeyChecking; } }
8,920
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/applications
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/applications/hpc/TensorFlow.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.applications.hpc; import org.apache.airavata.models.resources.hpc.GroovyMap; import org.apache.airavata.models.resources.hpc.Script; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; public class TensorFlow extends HPCApplication { private final static Logger logger = LoggerFactory.getLogger(TensorFlow.class); public TensorFlow(String applicationName, Map<String, String> applicationInputs) { super(applicationName, applicationInputs); } public GroovyMap getJobSpecification(String computeResource){ GroovyMap jobSpecification = new GroovyMap(); jobSpecification.add(Script.NODES, 1); jobSpecification.add(Script.PROCESS_PER_NODE, 16); jobSpecification.add(Script.MAX_WALL_TIME, "00:30:00"); jobSpecification.add(Script.QUEUE_NAME, "debug_gpu"); jobSpecification.add(Script.MAIL_ADDRESS, "supun.nakandala@gmail.com"); List<String> moduleLoads = new ArrayList<>(); moduleLoads.add("module load ccm"); moduleLoads.add("module load singularity"); jobSpecification.add(Script.MODULE_COMMANDS, moduleLoads); jobSpecification.add(Script.WORKING_DIR, "/N/dc2/scratch/snakanda/work-dirs"); List<java.lang.String> inputs = new ArrayList<>(); inputs.add("~/airavata/code_tf.py"); jobSpecification.add(Script.INPUTS, inputs); jobSpecification.add(Script.EXECUTABLE_PATH, "singularity exec /N/soft/cle5/singularity/images/tensorflow1.1-ubuntu-py2.7.11-test.img python"); jobSpecification.add(Script.JOB_SUBMITTER_COMMAND,"ccmrun"); jobSpecification.add(Script.STANDARD_OUT_FILE, "STDOUT.txt"); jobSpecification.add(Script.STANDARD_ERROR_FILE, "STDERR.txt"); return jobSpecification; } }
8,921
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/applications
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/applications/hpc/HPCApplication.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.applications.hpc; import org.apache.airavata.models.resources.hpc.GroovyMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; public class HPCApplication { private final static Logger logger = LoggerFactory.getLogger(HPCApplication.class); private String applicationName; private Map<String, String> applicationInputs; public HPCApplication(String applicationName, Map<String, String> applicationInputs) { this.applicationName = applicationName; this.applicationInputs = applicationInputs; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } public Map<String, String> getApplicationInputs() { return applicationInputs; } public void setApplicationInputs(Map<String, String> applicationInputs) { this.applicationInputs = applicationInputs; } public GroovyMap getJobMap(String computeResource){return null;} }
8,922
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/applications
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/applications/hpc/HPCApplicationExecutor.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.applications.hpc; import org.apache.airavata.models.resources.hpc.GroovyMap; import org.apache.airavata.models.resources.hpc.Script; import org.apache.airavata.resources.batch.BigRed2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; public class HPCApplicationExecutor { private final static Logger logger = LoggerFactory.getLogger(HPCApplicationExecutor.class); public void executeApplication(String routingKey, HPCApplication application, String computeResource, GroovyMap jobSpecification) throws Exception { if(computeResource.equals("bigred2.uits.iu.edu")){ //Even though here I use different class specific for BigRed2 there should be a generic class (HPCBatchResource) //which will be configured with BigRed2 specific config values read from a database BigRed2 bigRed2 = new BigRed2(); String workingDirectory = jobSpecification.get(Script.WORKING_DIR).toString(); bigRed2.makeDirectory(routingKey, workingDirectory); for(Map.Entry<String, String> entry: application.getApplicationInputs().entrySet()){ bigRed2.copyTo(routingKey, entry.getValue(), workingDirectory + "/" + entry.getKey()); } bigRed2.submitBatchJob(routingKey, jobSpecification); }else{ throw new Exception("Unsupported compute resource..."); } } }
8,923
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/runners
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/runners/ssh/SSHCommandOutputReader.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.runners.ssh; import com.jcraft.jsch.Channel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class SSHCommandOutputReader{ private static final Logger logger = LoggerFactory.getLogger(SSHCommandOutputReader.class); String stdOutputString = null; String stdErrorString = null; ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); private int exitCode; public void onOutput(Channel channel) { try { this.setStdOutputString(getOutputStream(channel, channel.getInputStream())); this.setStdErrorString(new String(errorStream.toByteArray(), "UTF-8")); this.exitCode = channel.getExitStatus(); } catch (IOException e) { logger.error(e.getMessage(), e); } } private String getOutputStream(Channel channel, InputStream inputStream) throws IOException { StringBuilder output = new StringBuilder(""); byte[] tmp = new byte[1024]; do { while (inputStream.available() > 0) { int i = inputStream.read(tmp, 0, 1024); if (i < 0) break; output.append(new String(tmp, 0, i)); } } while (!channel.isClosed()) ; return output.toString(); } public void setExitCode(int exitCode) { this.exitCode = exitCode; } public int getExitCode() { return exitCode; } public String getStdOutputString() { return stdOutputString; } public void setStdOutputString(String stdOutputString) { this.stdOutputString = stdOutputString; } public String getStdErrorString() { return stdErrorString; } public void setStdErrorString(String stdErrorString) { this.stdErrorString = stdErrorString; } public ByteArrayOutputStream getErrorStream() { return errorStream; } }
8,924
0
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/runners
Create_ds/airavata-sandbox/airavata-layered-architecture/src/main/java/org/apache/airavata/runners/ssh/SSHRunner.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.runners.ssh; import com.jcraft.jsch.*; import org.apache.airavata.models.runners.ssh.SSHApiException; import org.apache.airavata.models.runners.ssh.SSHKeyAuthentication; import org.apache.airavata.models.runners.ssh.SSHServerInfo; import org.apache.airavata.models.runners.ssh.SSHUserInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*; public class SSHRunner { private final static Logger log = LoggerFactory.getLogger(SSHRunner.class); public Session createSSHSession(SSHServerInfo serverInfo, SSHKeyAuthentication authentication) throws JSchException { JSch jSch = new JSch(); jSch.addIdentity(UUID.randomUUID().toString(), authentication.getPrivateKey(), authentication.getPublicKey(), authentication.getPassphrase().getBytes()); Session session = jSch.getSession(serverInfo.getUserName(), serverInfo.getHost(), serverInfo.getSshPort()); session.setUserInfo(new SSHUserInfo(serverInfo.getUserName(), null, authentication.getPassphrase())); if (authentication.getStrictHostKeyChecking().equals("yes")) { jSch.setKnownHosts(authentication.getKnownHostsFilePath()); } else { session.setConfig("StrictHostKeyChecking", "no"); } session.connect(); return session; } public String scpTo(String routingKey, String localFile, String remoteFile, SSHServerInfo serverInfo, SSHKeyAuthentication authentication) throws IOException, JSchException, SSHApiException { Session session = createSSHSession(serverInfo, authentication); FileInputStream fis = null; String prefix = null; if (new File(localFile).isDirectory()) { prefix = localFile + File.separator; } boolean ptimestamp = true; // exec 'scp -t rfile' remotely String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + remoteFile; Channel channel = session.openChannel("exec"); SSHCommandOutputReader stdOutReader = new SSHCommandOutputReader(); ((ChannelExec) channel).setCommand(command); ((ChannelExec) channel).setErrStream(stdOutReader.getErrorStream()); // get I/O streams for remote scp OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); channel.connect(); if (checkAck(in) != 0) { String error = "Error Reading input Stream"; log.error(error); throw new SSHApiException(error); } File _lfile = new File(localFile); if (ptimestamp) { command = "T" + (_lfile.lastModified() / 1000) + " 0"; // The access time should be sent here, // but it is not accessible with JavaAPI ;-< command += (" " + (_lfile.lastModified() / 1000) + " 0\n"); out.write(command.getBytes()); out.flush(); if (checkAck(in) != 0) { String error = "Error Reading input Stream"; log.error(error); throw new SSHApiException(error); } } // send "C0644 filesize filename", where filename should not include '/' long filesize = _lfile.length(); command = "C0644 " + filesize + " "; if (localFile.lastIndexOf('/') > 0) { command += localFile.substring(localFile.lastIndexOf('/') + 1); } else { command += localFile; } command += "\n"; out.write(command.getBytes()); out.flush(); if (checkAck(in) != 0) { String error = "Error Reading input Stream"; log.error(error); throw new SSHApiException(error); } // send a content of localFile fis = new FileInputStream(localFile); byte[] buf = new byte[1024]; while (true) { int len = fis.read(buf, 0, buf.length); if (len <= 0) break; out.write(buf, 0, len); //out.flush(); } fis.close(); fis = null; // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); if (checkAck(in) != 0) { String error = "Error Reading input Stream"; log.error(error); throw new SSHApiException(error); } out.close(); stdOutReader.onOutput(channel); channel.disconnect(); if (stdOutReader.getStdErrorString().contains("scp:")) { throw new SSHApiException(stdOutReader.getStdErrorString()); } session.disconnect(); //since remote file is always a file we just return the file return remoteFile; } /** * This method will copy a remote file to a local directory * * @param remoteFile remote file path, this has to be a full qualified path * @param localFile This is the local file to copy, this can be a directory too * @return returns the final local file path of the new file came from the remote resource */ public void scpFrom(String routingKey, String remoteFile, String localFile, SSHServerInfo serverInfo, SSHKeyAuthentication authentication) throws IOException, JSchException, SSHApiException { Session session = createSSHSession(serverInfo, authentication); FileOutputStream fos = null; try { String prefix = null; if (new File(localFile).isDirectory()) { prefix = localFile + File.separator; } SSHCommandOutputReader stdOutReader = new SSHCommandOutputReader(); // exec 'scp -f remotefile' remotely String command = "scp -f " + remoteFile; Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); ((ChannelExec) channel).setErrStream(stdOutReader.getErrorStream()); // get I/O streams for remote scp OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); if (!channel.isClosed()){ channel.connect(); } byte[] buf = new byte[1024]; // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); while (true) { int c = checkAck(in); if (c != 'C') { break; } // read '0644 ' in.read(buf, 0, 5); long filesize = 0L; while (true) { if (in.read(buf, 0, 1) < 0) { // error break; } if (buf[0] == ' ') break; filesize = filesize * 10L + (long) (buf[0] - '0'); } String file = null; for (int i = 0; ; i++) { in.read(buf, i, 1); if (buf[i] == (byte) 0x0a) { file = new String(buf, 0, i); break; } } //System.out.println("filesize="+filesize+", file="+file); // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); // read a content of lfile fos = new FileOutputStream(prefix == null ? localFile : prefix + file); int foo; while (true) { if (buf.length < filesize) foo = buf.length; else foo = (int) filesize; foo = in.read(buf, 0, foo); if (foo < 0) { // error break; } fos.write(buf, 0, foo); filesize -= foo; if (filesize == 0L) break; } fos.close(); fos = null; if (checkAck(in) != 0) { String error = "Error transfering the file content"; log.error(error); throw new SSHApiException(error); } // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); } stdOutReader.onOutput(channel); if (stdOutReader.getStdErrorString().contains("scp:")) { throw new SSHApiException(stdOutReader.getStdErrorString()); } } catch (Exception e) { log.error(e.getMessage(), e); } finally { try { if (fos != null) fos.close(); session.disconnect(); } catch (Exception ee) { } } } public void makeDirectory(String routingKey, String path, SSHServerInfo serverInfo, SSHKeyAuthentication authentication) throws IOException, JSchException, Exception { Session session = createSSHSession(serverInfo, authentication); // exec 'scp -t rfile' remotely String command = "mkdir -p " + path; Channel channel = session.openChannel("exec"); SSHCommandOutputReader stdOutReader = new SSHCommandOutputReader(); ((ChannelExec) channel).setCommand(command); ((ChannelExec) channel).setErrStream(stdOutReader.getErrorStream()); try { channel.connect(); } catch (JSchException e) { channel.disconnect(); log.error("Unable to retrieve command output. Command - " + command + " on server - " + session.getHost() + ":" + session.getPort() + " connecting user name - " + session.getUserName()); throw e; } stdOutReader.onOutput(channel); if (stdOutReader.getStdErrorString().contains("mkdir:")) { throw new Exception(stdOutReader.getStdErrorString()); } channel.disconnect(); session.disconnect(); } public List<String> listDirectory(String routingKey, String path, SSHServerInfo serverInfo, SSHKeyAuthentication authentication) throws IOException, JSchException, Exception { Session session = createSSHSession(serverInfo, authentication); // exec 'scp -t rfile' remotely String command = "ls " + path; Channel channel = session.openChannel("exec"); SSHCommandOutputReader stdOutReader = new SSHCommandOutputReader(); ((ChannelExec) channel).setCommand(command); ((ChannelExec) channel).setErrStream(stdOutReader.getErrorStream()); try { channel.connect(); } catch (JSchException e) { channel.disconnect(); throw new Exception("Unable to retrieve command output. Command - " + command + " on server - " + session.getHost() + ":" + session.getPort() + " connecting user name - " + session.getUserName(), e); } if (stdOutReader.getStdErrorString().contains("ls:")) { throw new Exception(stdOutReader.getStdErrorString()); } channel.disconnect(); session.disconnect(); return Arrays.asList(stdOutReader.getStdOutputString().split("\n")); } public SSHCommandOutputReader executeCommand(String routingKey, String command, SSHServerInfo serverInfo, SSHKeyAuthentication authentication) throws Exception { Session session = createSSHSession(serverInfo, authentication); Map<String, String> results = new HashMap<>(); Channel channel = session.openChannel("exec"); SSHCommandOutputReader stdOutReader = new SSHCommandOutputReader(); ((ChannelExec) channel).setCommand(command); ((ChannelExec) channel).setErrStream(stdOutReader.getErrorStream()); try { channel.connect(); } catch (JSchException e) { channel.disconnect(); throw new Exception("Unable to retrieve command output. Command - " + command + " on server - " + session.getHost() + ":" + session.getPort() + " connecting user name - " + session.getUserName(), e); } stdOutReader.onOutput(channel); session.disconnect(); return stdOutReader; } public SSHCommandOutputReader executeCommand(String routingKey, String[] commands, SSHServerInfo serverInfo, SSHKeyAuthentication authentication) throws Exception { return executeCommand(routingKey, String.join(" && ", commands), serverInfo, authentication); } private int checkAck(InputStream in) throws IOException { int b = in.read(); if (b == 0) return b; if (b == -1) return b; if (b == 1 || b == 2) { StringBuffer sb = new StringBuffer(); int c; do { c = in.read(); sb.append((char) c); } while (c != '\n'); if (b == 1) { // error System.out.print(sb.toString()); } if (b == 2) { // fatal error System.out.print(sb.toString()); } log.warn(sb.toString()); } return b; } }
8,925
0
Create_ds/airavata-sandbox/utils/src/test/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/test/java/org/apache/airavata/common/utils/ApplicationSettingsTest.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.common.utils; import junit.framework.Assert; import junit.framework.TestCase; import org.apache.airavata.common.exception.ApplicationSettingsException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * User: AmilaJ (amilaj@apache.org) * Date: 7/5/13 * Time: 4:39 PM */ public class ApplicationSettingsTest extends TestCase { public void testGetAbsoluteSetting() throws Exception { System.setProperty(AiravataUtils.EXECUTION_MODE, "SERVER"); String url = ApplicationSettings.getAbsoluteSetting("registry.service.wsdl"); Assert.assertEquals("http://192.2.33.12:8080/airavata-server/services/RegistryService?wsdl", url); } public void testGetAbsoluteSettingWithSpecialCharacters() throws Exception { System.setProperty(AiravataUtils.EXECUTION_MODE, "SERVER"); String url = ApplicationSettings.getAbsoluteSetting("registry.service.wsdl2"); Assert.assertEquals("http://localhost:8080/airavata-server/services/RegistryService?wsdl", url); } }
8,926
0
Create_ds/airavata-sandbox/utils/src/test/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/test/java/org/apache/airavata/common/utils/SecurityUtilTest.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.common.utils; import junit.framework.Assert; import org.junit.Test; import java.io.InputStream; import java.net.URL; import java.security.KeyStore; /** * User: AmilaJ (amilaj@apache.org) * Date: 10/11/13 * Time: 10:42 AM */ public class SecurityUtilTest { @Test public void testEncryptString() throws Exception { URL url = this.getClass().getClassLoader().getResource("mykeystore.jks"); assert url != null; String stringToEncrypt = "Test string to encrypt"; byte[] encrypted = SecurityUtil.encryptString(url.getPath(), "mykey", new TestKeyStoreCallback(), stringToEncrypt); String decrypted = SecurityUtil.decryptString(url.getPath(), "mykey", new TestKeyStoreCallback(), encrypted); Assert.assertTrue(stringToEncrypt.equals(decrypted)); } @Test public void testEncryptBytes() throws Exception { URL url = this.getClass().getClassLoader().getResource("mykeystore.jks"); assert url != null; String stringToEncrypt = "Test string to encrypt"; byte[] encrypted = SecurityUtil.encrypt(url.getPath(), "mykey", new TestKeyStoreCallback(), stringToEncrypt.getBytes("UTF-8")); byte[] decrypted = SecurityUtil.decrypt(url.getPath(), "mykey", new TestKeyStoreCallback(), encrypted); Assert.assertTrue(stringToEncrypt.equals(new String(decrypted, "UTF-8"))); } @Test public void testLoadKeyStore() throws Exception{ InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("mykeystore.jks"); KeyStore ks = SecurityUtil.loadKeyStore(inputStream, "jceks", new TestKeyStoreCallback()); Assert.assertNotNull(ks); } @Test public void testLoadKeyStoreFromFile() throws Exception{ URL url = this.getClass().getClassLoader().getResource("mykeystore.jks"); assert url != null; KeyStore ks = SecurityUtil.loadKeyStore(url.getPath(), "jceks", new TestKeyStoreCallback()); Assert.assertNotNull(ks); } private class TestKeyStoreCallback implements KeyStorePasswordCallback { @Override public char[] getStorePassword() { return "airavata".toCharArray(); } @Override public char[] getSecretKeyPassPhrase(String keyAlias) { if (keyAlias.equals("mykey")) { return "airavatasecretkey".toCharArray(); } return null; } } }
8,927
0
Create_ds/airavata-sandbox/utils/src/test/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/test/java/org/apache/airavata/common/utils/XMLUtilTest.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.common.utils; import org.apache.airavata.common.utils.XMLUtil; import org.junit.Test; public class XMLUtilTest { @Test public void isXMLTest(){ String xml = "<test>testing</test>"; org.junit.Assert.assertTrue(XMLUtil.isXML(xml)); org.junit.Assert.assertFalse(XMLUtil.isXML("NonXMLString")); } @Test public void isEqualTest(){ String xml1 = "<test><inner>innerValue</inner></test>"; String xml2 = "<test><inner>innerValue</inner></test>"; String xml3 = "<test1><inner>innerValue</inner></test1>"; try { org.junit.Assert.assertTrue(XMLUtil.isEqual(XMLUtil.stringToXmlElement(xml1), XMLUtil.stringToXmlElement(xml2))); org.junit.Assert.assertFalse(XMLUtil.isEqual(XMLUtil.stringToXmlElement(xml1), XMLUtil.stringToXmlElement(xml3))); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } @Test public void getQNameTest(){ String qname = "ns1:a"; org.junit.Assert.assertEquals("a",XMLUtil.getLocalPartOfQName(qname)); org.junit.Assert.assertEquals("ns1",XMLUtil.getPrefixOfQName(qname)); } }
8,928
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/context/RequestContext.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.common.context; /** * The request context class. This will be local to a thread. User data that needs to propagate relevant to a request * will be stored here. We use thread local globals to store request data. Currently we only store user identity. */ public class RequestContext { public String getUserIdentity() { return userIdentity; } public void setUserIdentity(String userIdentity) { this.userIdentity = userIdentity; } /** * User associated with current request. */ private String userIdentity; public String getGatewayId() { return gatewayId; } public void setGatewayId(String gatewayId) { this.gatewayId = gatewayId; } /** * The gateway id. */ private String gatewayId; }
8,929
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/context/WorkflowContext.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.common.context; /** * The workflow context class. This will be local to a thread. Workflow data that needs to propagate relevant to a * request will be stored here. We use thread local globals to store request data. Currently we only store user * identity. */ public class WorkflowContext { private static final ThreadLocal userThreadLocal = new InheritableThreadLocal(); /** * Sets the context. * * @param context * The context to be set. - Careful when calling this. Make sure other data relevant to context is * preserved. */ public static void set(RequestContext context) { userThreadLocal.set(context); } /** * Clears the context */ public static void unset() { userThreadLocal.remove(); } /** * Gets the context associated with current context. * * @return The context associated with current thread. */ public static RequestContext get() { return (RequestContext) userThreadLocal.get(); } /** * Gets the user associated with current user. * * @return User id associated with current request. */ public static synchronized String getRequestUser() { RequestContext requestContext = (RequestContext) userThreadLocal.get(); if (requestContext != null) { return requestContext.getUserIdentity(); } return null; } public static synchronized String getGatewayId() { RequestContext requestContext = (RequestContext) userThreadLocal.get(); if (requestContext != null) { return requestContext.getGatewayId(); } return null; } }
8,930
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/DBUtil.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.common.utils; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.commons.dbcp.BasicDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.sql.*; import java.util.Properties; /** * Database lookup. Abstracts out JDBC operations. */ public class DBUtil { private String jdbcUrl; private String databaseUserName; private String databasePassword; private String driverName; protected static Logger log = LoggerFactory.getLogger(DBUtil.class); private Properties properties; public DBUtil(String jdbcUrl, String userName, String password, String driver) throws InstantiationException, IllegalAccessException, ClassNotFoundException { this.jdbcUrl = jdbcUrl; this.databaseUserName = userName; this.databasePassword = password; this.driverName = driver; init(); } /** * Initializes and load driver. Must be called this before calling anyother method. * * @throws ClassNotFoundException * If DB driver is not found. * @throws InstantiationException * If unable to create driver class. * @throws IllegalAccessException * If security does not allow users to instantiate driver object. */ private void init() throws ClassNotFoundException, InstantiationException, IllegalAccessException { properties = new Properties(); properties.put("user", databaseUserName); properties.put("password", databasePassword); properties.put("characterEncoding", "ISO-8859-1"); properties.put("useUnicode", "true"); loadDriver(); } /** * Generic method to query values in the database. * * @param tableName * Table name to query * @param selectColumn * The column selecting * @param whereValue * The condition query * @return The value appropriate to the query. * @throws SQLException * If an error occurred while querying */ public String getMatchingColumnValue(String tableName, String selectColumn, String whereValue) throws SQLException { return getMatchingColumnValue(tableName, selectColumn, selectColumn, whereValue); } /** * Generic method to query values in the database. * * @param tableName * Table name to query * @param selectColumn * The column selecting * @param whereColumn * The column which condition should apply * @param whereValue * The condition query * @return The value appropriate to the query. * @throws SQLException * If an error occurred while querying */ public String getMatchingColumnValue(String tableName, String selectColumn, String whereColumn, String whereValue) throws SQLException { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("SELECT ").append(selectColumn).append(" FROM ").append(tableName).append(" WHERE ") .append(whereColumn).append(" = ?"); String sql = stringBuilder.toString(); Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = null; try { ps.setString(1, whereValue); rs = ps.executeQuery(); if (rs.next()) { return rs.getString(1); } } finally { try { if (rs != null) { rs.close(); } ps.close(); connection.close(); } catch (Exception ignore) { log.error("An error occurred while closing database connections ", ignore); } } return null; } /** * Create table utility method. * * @param sql * SQL to be executed. * @throws SQLException * If an error occurred while creating the table. */ public void executeSQL(String sql) throws SQLException { Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(sql); try { ps.executeUpdate(); connection.commit(); } finally { try { if (ps != null) { ps.close(); } connection.close(); } catch (Exception ignore) { log.error("An error occurred while closing database connections ", ignore); } } } private void loadDriver() throws ClassNotFoundException, IllegalAccessException, InstantiationException { Class.forName(driverName).newInstance(); } /** * Gets a new DBCP data source. * * @return A new data source. */ public DataSource getDataSource() { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(this.driverName); ds.setUsername(this.databaseUserName); ds.setPassword(this.databasePassword); ds.setUrl(this.jdbcUrl); return ds; } /** * Creates a new JDBC connections based on provided DBCP properties. * * @return A new DB connection. * @throws SQLException * If an error occurred while creating the connection. */ public Connection getConnection() throws SQLException { Connection connection = DriverManager.getConnection(jdbcUrl, properties); connection.setAutoCommit(false); return connection; } /** * Utility method to close statements and connections. * * @param preparedStatement * The prepared statement to close. * @param connection * The connection to close. */ public static void cleanup(PreparedStatement preparedStatement, Connection connection) { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { log.error("Error closing prepared statement.", e); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { log.error("Error closing database connection.", e); } } } /** * Utility method to close statements and connections. * * @param preparedStatement * The prepared statement to close. */ public static void cleanup(PreparedStatement preparedStatement) { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { log.error("Error closing prepared statement.", e); } } } /** * Utility method to close statements and connections. * * @param preparedStatement * The prepared statement to close. */ public static void cleanup(PreparedStatement preparedStatement, ResultSet resultSet) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { log.error("Error closing prepared statement.", e); } } cleanup(preparedStatement); } /** * Cleanup the connection. * @param connection The connection to close. */ public static void cleanup(Connection connection) { if (connection != null) { try { connection.close(); } catch (SQLException e) { log.debug("Error closing connection.", e); log.warn("Error closing connection."); } } } /** * Mainly useful for tests. * * @param tableName * The table name. * @param connection * The connection to be used. */ public static void truncate(String tableName, Connection connection) throws SQLException { String sql = "delete from " + tableName; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); connection.commit(); } /** * Creates a DBUtil object based on servlet context configurations. * * @return DBUtil object. * @throws Exception * If an error occurred while reading configurations or while creating database object. */ public static DBUtil getCredentialStoreDBUtil() throws ApplicationSettingsException, IllegalAccessException, ClassNotFoundException, InstantiationException { String jdbcUrl = ServerSettings.getCredentialStoreDBURL(); String userName = ServerSettings.getCredentialStoreDBUser(); String password = ServerSettings.getCredentialStoreDBPassword(); String driverName = ServerSettings.getCredentialStoreDBDriver(); StringBuilder stringBuilder = new StringBuilder("Starting credential store, connecting to database - "); stringBuilder.append(jdbcUrl).append(" DB user - ").append(userName).append(" driver name - ") .append(driverName); log.debug(stringBuilder.toString()); DBUtil dbUtil = new DBUtil(jdbcUrl, userName, password, driverName); dbUtil.init(); return dbUtil; } }
8,931
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/ServerSettings.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.common.utils; import java.util.ArrayList; import javax.management.InstanceNotFoundException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.catalina.Server; import org.apache.catalina.Service; import org.apache.catalina.connector.Connector; import org.apache.coyote.ProtocolHandler; import org.apache.coyote.http11.Http11AprProtocol; import org.apache.coyote.http11.Http11NioProtocol; import org.apache.coyote.http11.Http11Protocol; public class ServerSettings extends ApplicationSettings{ private static final String SYSTEM_USER="system.user"; private static final String SYSTEM_USER_PASSWORD="system.password"; private static final String SYSTEM_USER_GATEWAY="system.gateway"; private static final String TOMCAT_PORT = "port"; private static final String SERVER_CONTEXT_ROOT="server.context-root"; private static String tomcatPort=null; private static final String CREDENTIAL_STORE_DB_URL ="credential.store.jdbc.url"; private static final String CREDENTIAL_STORE_DB_USER ="credential.store.jdbc.user"; private static final String CREDENTIAL_STORE_DB_PASSWORD ="credential.store.jdbc.password"; private static final String CREDENTIAL_STORE_DB_DRIVER ="credential.store.jdbc.driver"; private static final String REGISTRY_DB_URL ="registry.jdbc.url"; private static final String REGISTRY_DB_USER ="registry.jdbc.user"; private static final String REGISTRY_DB_PASSWORD ="registry.jdbc.password"; private static final String REGISTRY_DB_DRIVER ="registry.jdbc.driver"; private static final String ENABLE_HTTPS = "enable.https"; private static final String HOST_SCHEDULER = "host.scheduler"; public static String getSystemUser() throws ApplicationSettingsException{ return getSetting(SYSTEM_USER); } public static String getSystemUserPassword() throws ApplicationSettingsException{ return getSetting(SYSTEM_USER_PASSWORD); } public static String getSystemUserGateway() throws ApplicationSettingsException{ return getSetting(SYSTEM_USER_GATEWAY); } public static String getServerContextRoot(){ return getSetting(SERVER_CONTEXT_ROOT,"axis2"); } public static String getCredentialStoreDBUser() throws ApplicationSettingsException { try { return getSetting(CREDENTIAL_STORE_DB_USER); } catch (ApplicationSettingsException e) { return getSetting(REGISTRY_DB_USER); } } public static String getCredentialStoreDBPassword() throws ApplicationSettingsException { try { return getSetting(CREDENTIAL_STORE_DB_PASSWORD); } catch (ApplicationSettingsException e) { return getSetting(REGISTRY_DB_PASSWORD); } } public static String getCredentialStoreDBDriver() throws ApplicationSettingsException { try { return getSetting(CREDENTIAL_STORE_DB_DRIVER); } catch (ApplicationSettingsException e) { return getSetting(REGISTRY_DB_DRIVER); } } public static String getCredentialStoreDBURL() throws ApplicationSettingsException { try { return getSetting(CREDENTIAL_STORE_DB_URL); } catch (ApplicationSettingsException e) { return getSetting(REGISTRY_DB_URL); } } public static boolean isEnableHttps() { try { return Boolean.parseBoolean(getSetting(ENABLE_HTTPS)); } catch (ApplicationSettingsException e) { return false; } } public static String getTomcatPort(String protocol) throws ApplicationSettingsException { if (tomcatPort==null) { try { //First try to get the port from a tomcat if it is already running ArrayList<MBeanServer> mBeanServers = MBeanServerFactory .findMBeanServer(null); if (mBeanServers.size() > 0) { MBeanServer mBeanServer = mBeanServers.get(0); Server server = null; String[] domains = mBeanServer.getDomains(); for (String domain : domains) { try { server = (Server) mBeanServer.getAttribute( new ObjectName(domain, "type", "Server"), "managedResource"); break; } catch (InstanceNotFoundException e) { //ignore } } if (server != null) { Service[] findServices = server.findServices(); for (Service service : findServices) { for (Connector connector : service.findConnectors()) { ProtocolHandler protocolHandler = connector.getProtocolHandler(); if(protocol != null && protocol.equals(connector.getScheme())){ if (protocolHandler instanceof Http11Protocol || protocolHandler instanceof Http11AprProtocol || protocolHandler instanceof Http11NioProtocol) { Http11Protocol p = (Http11Protocol) protocolHandler; if (p.getSslImplementationName() == null || p.getSslImplementationName() .equals("")) { tomcatPort = String.valueOf(connector .getPort()); } } } } } } } } catch (Exception e) { e.printStackTrace(); } //if unable to determine the server port from a running tomcat server, get it from //the server settings file if (tomcatPort == null) { tomcatPort = getSetting(TOMCAT_PORT); } } return tomcatPort; } public static String getHostScheduler() throws ApplicationSettingsException { return getSetting(HOST_SCHEDULER); } }
8,932
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/DatabaseTestCases.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.common.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.SQLException; /** * An abstraction for database specific test classes. This will create a database and provides methods to execute SQLs. */ public class DatabaseTestCases { private static final Logger logger = LoggerFactory.getLogger(DatabaseTestCases.class); protected static String hostAddress = "localhost"; protected static int port = 20000; protected static String userName = "admin"; protected static String password = "admin"; protected static String driver = "org.apache.derby.jdbc.ClientDriver"; public static String getHostAddress() { return hostAddress; } public static int getPort() { return port; } public static String getUserName() { return userName; } public static String getPassword() { return password; } public static String getDriver() { return driver; } public static String getJDBCUrl() { return new StringBuilder().append("jdbc:derby://").append(getHostAddress()).append(":").append(getPort()) .append("/persistent_data;create=true;user=").append(getUserName()).append(";password=") .append(getPassword()).toString(); } public static void waitTillServerStarts() { DBUtil dbUtil = null; try { dbUtil = new DBUtil(getJDBCUrl(), getUserName(), getPassword(), getDriver()); } catch (Exception e) { // ignore } Connection connection = null; try { if (dbUtil != null) { connection = dbUtil.getConnection(); } } catch (Throwable e) { // ignore } while (connection == null) { try { Thread.sleep(1000); try { if (dbUtil != null) { connection = dbUtil.getConnection(); } } catch (SQLException e) { // ignore } } catch (InterruptedException e) { // ignore } } } public static void executeSQL(String sql) throws Exception { DBUtil dbUtil = new DBUtil(getJDBCUrl(), getUserName(), getPassword(), getDriver()); dbUtil.executeSQL(sql); } public DBUtil getDbUtil () throws Exception { return new DBUtil(getJDBCUrl(), getUserName(), getPassword(), getDriver()); } public Connection getConnection() throws Exception { DBUtil dbUtil = getDbUtil (); Connection connection = dbUtil.getConnection(); connection.setAutoCommit(true); return connection; } }
8,933
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/ClientSettings.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.common.utils; import org.apache.airavata.common.exception.ApplicationSettingsException; public class ClientSettings extends ApplicationSettings { }
8,934
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/ServiceUtils.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.common.utils; import java.io.IOException; import java.net.SocketException; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.description.TransportInDescription; import org.apache.axis2.util.Utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ServiceUtils { private static final Logger log = LoggerFactory.getLogger(ServiceUtils.class); // private static final String REPOSITORY_PROPERTIES = "airavata-server.properties"; public static final String IP = "ip"; public static final String PORT = "port"; public static String generateServiceURLFromConfigurationContext( ConfigurationContext context, String serviceName) throws IOException { // URL url = ServiceUtils.class.getClassLoader() // .getResource(REPOSITORY_PROPERTIES); String localAddress = null; String port = null; // Properties properties = new Properties(); try { localAddress = ServerSettings.getSetting(IP); } catch (ApplicationSettingsException e) { //we will ignore this exception since the properties file will not contain the values //when it is ok to retrieve them from the axis2 context } if(localAddress == null){ try { localAddress = Utils.getIpAddress(context .getAxisConfiguration()); } catch (SocketException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } String protocol="http"; if(ServerSettings.isEnableHttps()){ protocol="https"; } try { port = ServerSettings.getTomcatPort(protocol); } catch (ApplicationSettingsException e) { //we will ignore this exception since the properties file will not contain the values //when it is ok to retrieve them from the axis2 context } if (port == null) { TransportInDescription transportInDescription = context .getAxisConfiguration().getTransportsIn() .get(protocol); if (transportInDescription != null && transportInDescription.getParameter(PORT) != null) { port = (String) transportInDescription .getParameter(PORT).getValue(); } } localAddress = protocol+"://" + localAddress + ":" + port; localAddress = localAddress + "/" //We are not using axis2 config context to get the context root because it is invalid //+ context.getContextRoot() + "/" //FIXME: the context root will be correct after updating the web.xml + ServerSettings.getServerContextRoot() + "/" + context.getServicePath() + "/" + serviceName; log.debug("Service Address Configured:" + localAddress); return localAddress; } }
8,935
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/SwingUtil.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.common.utils; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.net.URL; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.Spring; import javax.swing.SpringLayout; public class SwingUtil { /** * Minimum size, zero. */ public static final Dimension MINIMUM_SIZE = new Dimension(0, 0); /** * The default distance between components. */ public static final int PAD = 6; /** * Default cursor. */ public static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR); /** * Hand cursor. */ public static final Cursor HAND_CURSOR = new Cursor(Cursor.HAND_CURSOR); /** * Cross hair cursor. */ public static final Cursor CROSSHAIR_CURSOR = new Cursor(Cursor.CROSSHAIR_CURSOR); /** * Move cursor. */ public static final Cursor MOVE_CURSOR = new Cursor(Cursor.MOVE_CURSOR); /** * Wait cursor. */ public static final Cursor WAIT_CURSOR = new Cursor(Cursor.WAIT_CURSOR); /** * Creates an icon from an image contained in the "images" directory. * * @param filename * @return the ImageIcon created */ public static ImageIcon createImageIcon(String filename) { ImageIcon icon = null; URL imgURL = getImageURL(filename); if (imgURL != null) { icon = new ImageIcon(imgURL); } return icon; } /** * Creates an image from an image contained in the "images" directory. * * @param filename * @return the Image created */ public static Image createImage(String filename) { Image icon = null; URL imgURL = getImageURL(filename); if (imgURL != null) { icon = Toolkit.getDefaultToolkit().getImage(imgURL); } return icon; } public static URL getImageURL(String filename) { String path = "/images/" + filename; URL imgURL = SwingUtil.class.getResource(path); return imgURL; } /** * Return the Frame of a specified component if any. * * @param component * the specified component * * @return the Frame of a specified component if any; otherwise null */ public static Frame getFrame(Component component) { Frame frame; Component parent; while ((parent = component.getParent()) != null) { component = parent; } if (component instanceof Frame) { frame = (Frame) component; } else { frame = null; } return frame; } /** * Wight none of rows or eolumns. Used by layoutToGrid(). */ public final static int WEIGHT_NONE = -1; /** * Weight all rows or columns equally. Used by layoutToGrid(). */ public final static int WEIGHT_EQUALLY = -2; /** * Layouts the child components of a specified parent component using GridBagLayout. * * @param parent * The specified parent component * @param numRow * The number of rows * @param numColumn * The number of columns * @param weightedRow * The row to weight * @param weightedColumn * The column to weight */ public static void layoutToGrid(Container parent, int numRow, int numColumn, int weightedRow, int weightedColumn) { GridBagLayout layout = new GridBagLayout(); parent.setLayout(layout); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(SwingUtil.PAD, SwingUtil.PAD, SwingUtil.PAD, SwingUtil.PAD); for (int row = 0; row < numRow; row++) { constraints.gridy = row; if (weightedRow == WEIGHT_EQUALLY) { constraints.weighty = 1; } else if (row == weightedRow) { constraints.weighty = 1; } else { constraints.weighty = 0; } for (int column = 0; column < numColumn; column++) { constraints.gridx = column; if (weightedColumn == WEIGHT_EQUALLY) { constraints.weightx = 1; } else if (column == weightedColumn) { constraints.weightx = 1; } else { constraints.weightx = 0; } Component component = parent.getComponent(row * numColumn + column); layout.setConstraints(component, constraints); } } } /** * @param parent * @param rowWeights * @param columnWeights */ public static void layoutToGrid(Container parent, double[] rowWeights, double[] columnWeights) { GridBagLayout layout = new GridBagLayout(); parent.setLayout(layout); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(SwingUtil.PAD, SwingUtil.PAD, SwingUtil.PAD, SwingUtil.PAD); for (int row = 0; row < rowWeights.length; row++) { constraints.gridy = row; constraints.weighty = rowWeights[row]; for (int column = 0; column < columnWeights.length; column++) { constraints.gridx = column; constraints.weightx = columnWeights[column]; Component component = parent.getComponent(row * columnWeights.length + column); layout.setConstraints(component, constraints); } } } /** * @param parent * @param rowWeights * @param columnWeights */ @SuppressWarnings("boxing") public static void layoutToGrid(Container parent, List<Double> rowWeights, List<Double> columnWeights) { GridBagLayout layout = new GridBagLayout(); parent.setLayout(layout); GridBagConstraints constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(SwingUtil.PAD, SwingUtil.PAD, SwingUtil.PAD, SwingUtil.PAD); for (int row = 0; row < rowWeights.size(); row++) { constraints.gridy = row; constraints.weighty = rowWeights.get(row); for (int column = 0; column < columnWeights.size(); column++) { constraints.gridx = column; constraints.weightx = columnWeights.get(column); Component component = parent.getComponent(row * columnWeights.size() + column); layout.setConstraints(component, constraints); } } } /** * Aligns the first <code>rows</code> * <code>cols</code> components of <code>parent</code> in a grid. Each * component in a column is as wide as the maximum preferred width of the components in that column; height is * similarly determined for each row. The parent is made just big enough to fit them all. * * @param parent * * @param rows * number of rows * @param cols * number of columns */ public static void makeSpringCompactGrid(Container parent, int rows, int cols) { makeSpringCompactGrid(parent, rows, cols, PAD, PAD, PAD, PAD); } /** * Aligns the first <code>rows</code> * <code>cols</code> components of <code>parent</code> in a grid. Each * component in a column is as wide as the maximum preferred width of the components in that column; height is * similarly determined for each row. The parent is made just big enough to fit them all. * * @param parent * * @param rows * number of rows * @param cols * number of columns * @param initialX * x location to start the grid at * @param initialY * y location to start the grid at * @param xPad * x padding between cells * @param yPad * y padding between cells */ private static void makeSpringCompactGrid(Container parent, int rows, int cols, int initialX, int initialY, int xPad, int yPad) { SpringLayout layout = new SpringLayout(); parent.setLayout(layout); // Align all cells in each column and make them the same width. Spring x = Spring.constant(initialX); for (int c = 0; c < cols; c++) { Spring width = Spring.constant(0); for (int r = 0; r < rows; r++) { width = Spring.max(width, getConstraintsForCell(r, c, parent, cols).getWidth()); } for (int r = 0; r < rows; r++) { SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); constraints.setX(x); constraints.setWidth(width); } x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad))); } // Align all cells in each row and make them the same height. Spring y = Spring.constant(initialY); for (int r = 0; r < rows; r++) { Spring height = Spring.constant(0); for (int c = 0; c < cols; c++) { height = Spring.max(height, getConstraintsForCell(r, c, parent, cols).getHeight()); } for (int c = 0; c < cols; c++) { SpringLayout.Constraints constraints = getConstraintsForCell(r, c, parent, cols); constraints.setY(y); constraints.setHeight(height); } y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad))); } // Set the parent's size. SpringLayout.Constraints pCons = layout.getConstraints(parent); pCons.setConstraint(SpringLayout.SOUTH, y); pCons.setConstraint(SpringLayout.EAST, x); } /* Used by makeCompactGrid. */ private static SpringLayout.Constraints getConstraintsForCell(int row, int col, Container parent, int cols) { SpringLayout layout = (SpringLayout) parent.getLayout(); Component c = parent.getComponent(row * cols + col); return layout.getConstraints(c); } public static void addPlaceHolder(final JTextField field,final String placeHolderText){ field.addFocusListener(new FocusListener(){ private Color fontColor=field.getForeground(); // private String previousText=field.getText(); public void focusGained(FocusEvent arg0) { if (field.getText().equals(placeHolderText)){ field.setText(""); } field.setForeground(fontColor); } public void focusLost(FocusEvent arg0) { if (field.getText().trim().equals("")){ fontColor=field.getForeground(); field.setForeground(Color.GRAY); field.setText(placeHolderText); } } }); if (field.getText().trim().equals("")){ field.setText(placeHolderText); field.setForeground(Color.GRAY); } } }
8,936
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/SecurityUtil.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.common.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.security.*; import java.security.cert.CertificateException; /** * Class which includes security utilities. */ public class SecurityUtil { public static final String PASSWORD_HASH_METHOD_PLAINTEXT = "PLAINTEXT"; public static final String CHARSET_ENCODING = "UTF-8"; public static final String ENCRYPTION_ALGORITHM = "AES"; public static final String PADDING_MECHANISM = "AES/CBC/PKCS5Padding"; private static final Logger logger = LoggerFactory.getLogger(SecurityUtil.class); /** * Creates a hash of given string with the given hash algorithm. * * @param stringToDigest * The string to digest. * @param digestingAlgorithm * Hash algorithm. * @return The digested string. * @throws NoSuchAlgorithmException * If given hash algorithm doesnt exists. */ public static String digestString(String stringToDigest, String digestingAlgorithm) throws NoSuchAlgorithmException { if (digestingAlgorithm == null || digestingAlgorithm.equals(PASSWORD_HASH_METHOD_PLAINTEXT)) { return stringToDigest; } MessageDigest messageDigest = MessageDigest.getInstance(digestingAlgorithm); try { return new String(messageDigest.digest(stringToDigest.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { logger.error("Error encoding password string when creating digest", e); throw new RuntimeException("Error encoding password string when creating digest", e); } } /** * Sets the truststore for application. Useful when communicating over HTTPS. * * @param trustStoreFilePath * Where trust store is located. * @param trustStorePassword * The trust store password. */ public static void setTrustStoreParameters(String trustStoreFilePath, String trustStorePassword) { if (System.getProperty("javax.net.ssl.trustStrore") == null) { logger.info("Setting Java trust store to " + trustStoreFilePath); System.setProperty("javax.net.ssl.trustStrore", trustStoreFilePath); } if (System.getProperty("javax.net.ssl.trustStorePassword") == null) { System.setProperty("javax.net.ssl.trustStorePassword", trustStoreFilePath); } } public static byte[] encryptString(String keyStorePath, String keyAlias, KeyStorePasswordCallback passwordCallback, String value) throws GeneralSecurityException, IOException { return encrypt(keyStorePath, keyAlias, passwordCallback, value.getBytes(CHARSET_ENCODING)); } public static byte[] encrypt(String keyStorePath, String keyAlias, KeyStorePasswordCallback passwordCallback, byte[] value) throws GeneralSecurityException, IOException { Key secretKey = getSymmetricKey(keyStorePath, keyAlias, passwordCallback); Cipher cipher = Cipher.getInstance(PADDING_MECHANISM); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[16])); return cipher.doFinal(value); } private static Key getSymmetricKey(String keyStorePath, String keyAlias, KeyStorePasswordCallback passwordCallback) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, UnrecoverableKeyException { KeyStore ks = SecurityUtil.loadKeyStore(keyStorePath, "jceks", passwordCallback); if (ks == null) { throw new IOException("Unable to load Java keystore " + keyStorePath); } return ks.getKey(keyAlias, passwordCallback.getSecretKeyPassPhrase(keyAlias)); } public static byte[] decrypt(String keyStorePath, String keyAlias, KeyStorePasswordCallback passwordCallback, byte[] encrypted) throws GeneralSecurityException, IOException { Key secretKey = getSymmetricKey(keyStorePath, keyAlias, passwordCallback); Cipher cipher = Cipher.getInstance(PADDING_MECHANISM); cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(new byte[16])); return cipher.doFinal(encrypted); } public static String decryptString(String keyStorePath, String keyAlias, KeyStorePasswordCallback passwordCallback, byte[] encrypted) throws GeneralSecurityException, IOException { byte[] decrypted = decrypt(keyStorePath, keyAlias, passwordCallback, encrypted); return new String(decrypted, CHARSET_ENCODING); } public static KeyStore loadKeyStore(String keyStoreFilePath, String keyStoreType, KeyStorePasswordCallback passwordCallback) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { java.io.FileInputStream fis = null; try { fis = new java.io.FileInputStream(keyStoreFilePath); return loadKeyStore(fis, keyStoreType, passwordCallback); } finally { if (fis != null) { fis.close(); } } } public static KeyStore loadKeyStore(InputStream inputStream, String keyStoreType, KeyStorePasswordCallback passwordCallback) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { if (keyStoreType == null) { keyStoreType = KeyStore.getDefaultType(); } KeyStore ks = KeyStore.getInstance(keyStoreType); ks.load(inputStream, passwordCallback.getStorePassword()); return ks; } }
8,937
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/Pair.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.common.utils; public class Pair<L, R> { private L left; private R right; /** * Constructs a Pair. * * @param left * @param right */ public Pair(L left, R right) { this.left = left; this.right = right; } /** * Returns the left. * * @return The left */ public L getLeft() { return this.left; } /** * Sets left. * * @param left * The left to set. */ public void setLeft(L left) { this.left = left; } /** * Returns the right. * * @return The right */ public R getRight() { return this.right; } /** * Sets right. * * @param right * The right to set. */ public void setRight(R right) { this.right = right; } }
8,938
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/XmlFormatter.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.common.utils; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.xml.serialize.OutputFormat; import org.apache.xml.serialize.XMLSerializer; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Pretty-prints xml, supplied as a string. * <p/> * eg. <code> * String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>"); * </code> */ public class XmlFormatter { /** * @param unformattedXml * @return formattedXml */ public static String format(String unformattedXml) { try { final Document document = parseXmlFile(unformattedXml); OutputFormat format = new OutputFormat(document); format.setLineWidth(65); format.setIndenting(true); format.setIndent(2); Writer out = new StringWriter(); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(document); return out.toString(); } catch (IOException e) { throw new RuntimeException(e); } } private static Document parseXmlFile(String in) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(in)); return db.parse(is); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }
8,939
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/WSDLUtil.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.common.utils; import java.io.IOException; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.util.LinkedList; import java.util.List; import javax.xml.namespace.QName; import org.apache.airavata.common.exception.UtilsException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmlpull.infoset.XmlAttribute; import org.xmlpull.infoset.XmlBuilderException; import org.xmlpull.infoset.XmlElement; import org.xmlpull.infoset.XmlNamespace; import xsul.XmlConstants; import xsul5.wsdl.WsdlBinding; import xsul5.wsdl.WsdlDefinitions; import xsul5.wsdl.WsdlPortType; import xsul5.wsdl.WsdlPortTypeOperation; import xsul5.wsdl.WsdlUtil; public class WSDLUtil { private static final Logger logger = LoggerFactory.getLogger(WSDLUtil.class); /** * @param wsdlString * @return The WSDL * @throws UtilsException */ public static WsdlDefinitions stringToWSDL(String wsdlString) throws UtilsException { try { XmlElement wsdlElement = XMLUtil.stringToXmlElement(wsdlString); WsdlDefinitions definitions = new WsdlDefinitions(wsdlElement); return definitions; } catch (RuntimeException e) { throw new UtilsException(e); } } /** * @param definitions3 * @return The WsdlDefinitions (XSUL5) */ public static xsul5.wsdl.WsdlDefinitions wsdlDefinitions3ToWsdlDefintions5(xsul.wsdl.WsdlDefinitions definitions3) { return new xsul5.wsdl.WsdlDefinitions(XMLUtil.xmlElement3ToXmlElement5(definitions3)); } /** * @param definitions5 * @return The WsdlDefinitions (XSUL3) */ public static xsul.wsdl.WsdlDefinitions wsdlDefinitions5ToWsdlDefintions3(xsul5.wsdl.WsdlDefinitions definitions5) { return new xsul.wsdl.WsdlDefinitions(XMLUtil.xmlElement5ToXmlElement3(definitions5.xml())); } /** * @param definitions * @return The name of the WSDL. */ public static String getWSDLName(WsdlDefinitions definitions) { String wsdlName = definitions.xml().attributeValue(WSConstants.NAME_ATTRIBUTE); if (wsdlName == null) { // name is optional. wsdlName = ""; } return wsdlName; } /** * @param definitions * @return The QName of the WSDL. */ public static QName getWSDLQName(WsdlDefinitions definitions) { String targetNamespace = definitions.getTargetNamespace(); String wsdlName = getWSDLName(definitions); return new QName(targetNamespace, wsdlName); } /** * @param definitions * @return The first portType * @throws UtilsException */ public static WsdlPortType getFirstPortType(WsdlDefinitions definitions) throws UtilsException { for (WsdlPortType portType : definitions.portTypes()) { return portType; } throw new UtilsException("No portType is defined in WSDL"); } public static WsdlPortTypeOperation getFirstOperation(WsdlDefinitions definitions) throws UtilsException { for (WsdlPortTypeOperation operation : getFirstPortType(definitions).operations()) { return operation; } throw new UtilsException("No portType is defined in WSDL"); } /** * @param definitions * @return The QName of the first portType. * @throws UtilsException */ public static QName getFirstPortTypeQName(WsdlDefinitions definitions) throws UtilsException { String targetNamespace = definitions.getTargetNamespace(); for (WsdlPortType portType : definitions.portTypes()) { String portTypeName = portType.getName(); QName portTypeQName = new QName(targetNamespace, portTypeName); return portTypeQName; } throw new UtilsException("No portType is defined."); } /** * @param definitions * @param portTypeQName * @return The name of the first operation in a given portType. * @throws UtilsException */ public static String getFirstOperationName(WsdlDefinitions definitions, QName portTypeQName) throws UtilsException { WsdlPortType portType = definitions.getPortType(portTypeQName.getLocalPart()); for (WsdlPortTypeOperation operation : portType.operations()) { String operationName = operation.getOperationName(); // XXX Temporary solution to skip some GFac specific operations. if ("Shutdown".equals(operationName)) { continue; } else if ("Kill".equals(operationName)) { continue; } else if ("Ping".equals(operationName)) { continue; } return operationName; } throw new UtilsException("No operation is defined"); } /** * @param definitions * @return The cloned WsdlDefinitions */ public static WsdlDefinitions deepClone(WsdlDefinitions definitions) throws UtilsException { return new WsdlDefinitions(XMLUtil.deepClone(definitions.xml())); } /** * @param definitions * @param paramType * @return The schema that includes the type definition */ public static XmlElement getSchema(WsdlDefinitions definitions, QName paramType) throws UtilsException { XmlElement types = definitions.getTypes(); Iterable<XmlElement> schemas = types.elements(WSConstants.XSD_NS, WSConstants.SCHEMA_TAG); for (XmlElement schema : schemas) { if (isTypeDefinedInSchema(paramType, schema)) { return schema; } } // ok we didnt find the type in the schema in first level // now we try try to see if it exist in schema imports. // we loop in two step because its better to avoid the network // connection if possible for (XmlElement schema : schemas) { Iterable<XmlElement> imports = schema.elements(WSConstants.XSD_NS, WSConstants.IMPORT_TAG); for (XmlElement importEle : imports) { String schemaLocation = importEle.attributeValue(WSConstants.SCHEMA_LOCATION_ATTRIBUTE); if (null != schemaLocation && !"".equals(schemaLocation)) { try { // connect using a url connection URL url = new URL(schemaLocation); URLConnection connection = url.openConnection(); connection.connect(); XmlElement importedSchema = xsul5.XmlConstants.BUILDER.parseFragmentFromInputStream(connection .getInputStream()); if (isTypeDefinedInSchema(paramType, importedSchema)) { // still return the parent schema return schema; } } catch (MalformedURLException e) { throw new UtilsException(e); } catch (XmlBuilderException e) { throw new UtilsException(e); } catch (IOException e) { throw new UtilsException(e); } } } } return null; } private static boolean isTypeDefinedInSchema(QName paramType, XmlElement schema) { String schemaTargetNamespace = schema.attributeValue(WSConstants.TARGET_NAMESPACE_ATTRIBUTE); if (schemaTargetNamespace.equals(paramType.getNamespaceURI())) { for (XmlElement complexType : schema.elements(WSConstants.XSD_NS, WSConstants.COMPLEX_TYPE_TAG)) { String complexTypeName = complexType.attributeValue(WSConstants.NAME_ATTRIBUTE); if (complexTypeName.equals(paramType.getLocalPart())) { return true; } } for (XmlElement simpleType : schema.elements(WSConstants.XSD_NS, WSConstants.SIMPLE_TYPE_TAG)) { String simpleTypeName = simpleType.attributeValue(WSConstants.NAME_ATTRIBUTE); if (simpleTypeName.equals(paramType.getLocalPart())) { return true; } } } return false; } /** * @param definitions * @param paramType * @return The type definition */ public static XmlElement getTypeDefinition(WsdlDefinitions definitions, QName paramType) throws UtilsException { XmlElement types = definitions.getTypes(); XmlElement returnType = null; types.element(null, WSConstants.SCHEMA_TAG); Iterable<XmlElement> schemas = types.elements(null, WSConstants.SCHEMA_TAG); for (XmlElement schema : schemas) { returnType = findTypeInSchema(paramType, schema); if (returnType != null) { return returnType; } } // ok we didnt find the type in the schemas // try to find it in the schema imports. // if not found it will return null so we would return null return findTypeDefinitionInImports(definitions, paramType); } /** * * @param definitions * @param paramType * @return */ public static XmlElement getImportContainingTypeDefinition(WsdlDefinitions definitions, QName paramType) throws UtilsException { XmlElement types = definitions.getTypes(); XmlElement returnType = null; Iterable<XmlElement> schemas = types.elements(WSConstants.XSD_NS, WSConstants.SCHEMA_TAG); for (XmlElement schema : schemas) { Iterable<XmlElement> imports = schema.elements(WSConstants.XSD_NS, WSConstants.IMPORT_TAG); for (XmlElement importEle : imports) { String schemaLocation = importEle.attributeValue(WSConstants.SCHEMA_LOCATION_ATTRIBUTE); if (null != schemaLocation && !"".equals(schemaLocation)) { try { // connect using a url connection URL url = new URL(schemaLocation); URLConnection connection = url.openConnection(); connection.connect(); XmlElement importedSchema = xsul5.XmlConstants.BUILDER.parseFragmentFromInputStream(connection .getInputStream()); returnType = findTypeInSchema(paramType, importedSchema); if (returnType != null) { return importEle; } } catch (MalformedURLException e) { throw new UtilsException(e); } catch (XmlBuilderException e) { throw new UtilsException(e); } catch (IOException e) { throw new UtilsException(e); } } } } return null; } /** * * @param definitions * @param paramType * @return */ public static XmlElement findTypeDefinitionInImports(WsdlDefinitions definitions, QName paramType) throws UtilsException { XmlElement types = definitions.getTypes(); XmlElement returnType = null; Iterable<XmlElement> schemas = types.elements(null, WSConstants.SCHEMA_TAG); for (XmlElement schema : schemas) { Iterable<XmlElement> imports = schema.elements(WSConstants.XSD_NS, WSConstants.IMPORT_TAG); for (XmlElement importEle : imports) { String schemaLocation = importEle.attributeValue(WSConstants.SCHEMA_LOCATION_ATTRIBUTE); if (null != schemaLocation && !"".equals(schemaLocation)) { try { // connect using a url connection URL url = new URL(schemaLocation); URLConnection connection = url.openConnection(); connection.connect(); XmlElement importedSchema = xsul5.XmlConstants.BUILDER.parseFragmentFromInputStream(connection .getInputStream()); returnType = findTypeInSchema(paramType, importedSchema); if (returnType != null) { return returnType; } } catch (MalformedURLException e) { throw new UtilsException(e); } catch (XmlBuilderException e) { throw new UtilsException(e); } catch (IOException e) { throw new UtilsException(e); } } } } return null; } private static XmlElement findTypeInSchema(QName paramType, XmlElement schema) { String schemaTargetNamespace = schema.attributeValue(WSConstants.TARGET_NAMESPACE_ATTRIBUTE); if (null != schemaTargetNamespace && schemaTargetNamespace.equals(paramType.getNamespaceURI())) { for (XmlElement complexType : schema.elements(WSConstants.XSD_NS, WSConstants.COMPLEX_TYPE_TAG)) { String complexTypeName = complexType.attributeValue(WSConstants.NAME_ATTRIBUTE); if (complexTypeName.equals(paramType.getLocalPart())) { return complexType; } } for (XmlElement simpleType : schema.elements(WSConstants.XSD_NS, WSConstants.SIMPLE_TYPE_TAG)) { String simpleTypeName = simpleType.attributeValue(WSConstants.NAME_ATTRIBUTE); if (simpleTypeName.equals(paramType.getLocalPart())) { return simpleType; } } } return null; } /** * @param wsdl * @return true if the WSDL is AWSDL; false otherwise. */ public static boolean isAWSDL(WsdlDefinitions wsdl) { if (wsdl.services().iterator().hasNext()) { return false; } return true; } /** * @param definitions * @return true if the service supports asynchronous invocation; false otherwise; */ public static boolean isAsynchronousSupported(WsdlDefinitions definitions) { for (WsdlBinding binding : definitions.bindings()) { XmlElement element = binding.xml().element(WSConstants.USING_ADDRESSING_TAG); if (element != null) { return true; } } return false; } /** * Converts a specified AWSDL to CWSDL using DSC URI. * * @param definitions * The specified AWSDL. This will be modified. * @param url * The URL of the service * @return The CWSDL converted. */ public static WsdlDefinitions convertToCWSDL(WsdlDefinitions definitions, URI url) { for (WsdlPortType portType : definitions.portTypes()) { WsdlUtil.createCWSDL(definitions, portType, url); } return definitions; } /** * @param uri * @return The URI with "?wsdl" at the end. */ public static String appendWSDLQuary(String uri) { URI wsdlURI = appendWSDLQuary(URI.create(uri)); return wsdlURI.toString(); } public static List<XmlNamespace> getNamespaces(XmlElement element) { LinkedList<XmlNamespace> namespaces = new LinkedList<XmlNamespace>(); namespaces.add(element.getNamespace()); Iterable<XmlAttribute> attributes = element.attributes(); for (XmlAttribute xmlAttribute : attributes) { if (xmlAttribute.getNamespace() != null && !namespaces.contains(xmlAttribute.getNamespace())) { namespaces.add(xmlAttribute.getNamespace()); } int index = xmlAttribute.getValue().indexOf(':'); if (-1 != index) { String prefix = xmlAttribute.getValue().substring(0, index); if (element.lookupNamespaceByPrefix(prefix) != null) { namespaces.add(element.lookupNamespaceByPrefix(prefix)); } } } Iterable children = element.children(); for (Object object : children) { if (object instanceof XmlElement) { List<XmlNamespace> newNSs = getNamespaces((XmlElement) object); for (XmlNamespace xmlNamespace : newNSs) { if (!namespaces.contains(xmlNamespace)) { namespaces.add(xmlNamespace); } } } } return namespaces; } /** * @param uri * @return The URI with "?wsdl" at the end. */ public static URI appendWSDLQuary(URI uri) { if (uri.toString().endsWith("?wsdl")) { logger.warn("URL already has ?wsdl at the end: " + uri.toString()); // Don't throw exception to be more error tolerant. return uri; } String path = uri.getPath(); if (path == null || path.length() == 0) { uri = uri.resolve("/"); } uri = URI.create(uri.toString() + "?wsdl"); return uri; } /** * @param valueElement * @return */ public static org.xmlpull.v1.builder.XmlElement xmlElement5ToXmlElementv1(XmlElement valueElement) { return XmlConstants.BUILDER.parseFragmentFromReader(new StringReader(xsul5.XmlConstants.BUILDER .serializeToStringPretty(valueElement))); } /** * * @param vals * @param <T> * @return */ public static <T extends Object> T getfirst(Iterable<T> vals) { for (T class1 : vals) { return class1; } throw new RuntimeException("Iterator empty"); } /** * @param serviceSchema */ public static void print(XmlElement serviceSchema) { System.out.println(xsul5.XmlConstants.BUILDER.serializeToStringPretty(serviceSchema)); } /** * @param workflowID * @return */ public static String findWorkflowName(URI workflowID) { String[] splits = workflowID.toString().split("/"); return splits[splits.length - 1]; } /** * * @param element * @param name * @param oldValue * @param newValue */ public static void replaceAttributeValue(XmlElement element, String name, String oldValue, String newValue) { XmlAttribute attribute = element.attribute(name); if (null != attribute && oldValue.equals(attribute.getValue())) { element.removeAttribute(attribute); element.setAttributeValue(name, newValue); } Iterable iterator = element.children(); for (Object object : iterator) { if (object instanceof XmlElement) { replaceAttributeValue((XmlElement) object, name, oldValue, newValue); } } } public static boolean attributeExist(XmlElement element, String name, String value) { XmlAttribute attribute = element.attribute(name); if (null != attribute && value.equals(attribute.getValue())) { return true; } Iterable iterator = element.children(); boolean ret = false; for (Object object : iterator) { if (object instanceof XmlElement) { ret = ret || attributeExist((XmlElement) object, name, value); } } return ret; } }
8,940
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/ExecutionMode.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.common.utils; public enum ExecutionMode { CLIENT, SERVER, UNKNOWN }
8,941
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/StringUtil.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.common.utils; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringUtil { public static final String DELIMETER=","; public static final String QUOTE="\""; // Merits for the following function should go to // http://blog.houen.net/java-get-url-from-string/ public static List<String> getURLS(String text) { List<String> links = new ArrayList<String>(); String regex = "\\(?\\b((http|https|ftp)://|www[.])[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(text); while (m.find()) { String urlStr = m.group(); if (urlStr.startsWith("(") && urlStr.endsWith(")")) { urlStr = urlStr.substring(1, urlStr.length() - 1); } if (!links.contains(urlStr)) { links.add(urlStr); } } return links; } public static String createHTMLUrlTaggedString2(String value, List<String> pullLinks) { for (String url : pullLinks) { String hyperlinkString="<a href='"+url+"'>"+url+"</a>"; value=value.replaceAll(Pattern.quote(url), hyperlinkString); } return value; } public static String createHTMLUrlTaggedString(String value) { String urledString = ""; int lastIndex=0,index=0; while(index!=-1){ index=value.toLowerCase().indexOf("://",lastIndex); if (index!=-1){ int beginIndex=value.lastIndexOf(" ",index); urledString+=value.substring(lastIndex,beginIndex+1); int endIndex=value.indexOf(" ",index); if (beginIndex==-1){ beginIndex=0; }else{ beginIndex++; } if (endIndex==-1){ endIndex=value.length(); } String url=value.substring(beginIndex, endIndex); urledString+="<a href='"+url+"'>"+url+"</a>"; lastIndex=endIndex; } } urledString+=value.substring(lastIndex, value.length()); return urledString; } private static boolean isQuoted(String s, String delimiter){ //Check if we need quotes if (s.contains(delimiter)){ //Check if its already quoted s=s.replaceAll("\"\"", ""); return (s.substring(0,1).equals(QUOTE) && s.subSequence(s.length()-1, s.length()).equals(QUOTE)); } //no delimiters present, so already in proper form return true; } private static boolean isQuoted(String s){ return isQuoted(s, DELIMETER); } /** * Create a delimiter separated string out of a list * @param list * @return */ public static String createDelimiteredString(String[] list) { return createDelimiteredString(list, DELIMETER); } /** * Create a delimiter separated string out of a list * @param list * @return */ public static String createDelimiteredString(String[] list,String delimiter){ String s=null; for (String ss : list) { ss=quoteString(ss, delimiter); if (s==null){ s=ss; }else{ s+=delimiter +ss; } } return s; } /** * Return a proper quoted string if the string contains the delimiter character * @param s * @return */ public static String quoteString(String s) { return quoteString(s, DELIMETER); } /** * Return a proper quoted string if the string contains the delimiter character * @param s * @return */ public static String quoteString(String s,String delimiter){ if (isQuoted(s,delimiter)){ return s; }else{ return QUOTE+s.replaceAll(QUOTE, QUOTE+QUOTE)+QUOTE; } } /** * Parse the delimitered string and return elements as a string array * @param s * @return */ public static String[] getElementsFromString(String s, String delimeter, String quote) { List<String> list=new ArrayList<String>(); String currentItem=""; String previousChar=null; boolean insideQuote=false; for(int i=0;i<s.length();i++){ String c=s.substring(i,i+1); if (c.equals(delimeter)){ //if not inside a quoted string ignore the delimiter character if (insideQuote) { currentItem+=c; }else{ list.add(currentItem); currentItem = ""; } }else if (c.equals(quote)){ if (quote.equals(previousChar)){ //which means previousChar was an escape character, not a quote for the string currentItem+=quote; if (insideQuote){ //mistakenly thought previous char was opening quote char, thus need to make this false insideQuote=false; }else{ //mistakenly thought previous char was closing quote char, thus need to make this true insideQuote=true; } } else{ if (insideQuote){ //quote ended insideQuote=false; }else{ //quote beginning insideQuote=true; } } }else{ currentItem+=c; } previousChar=c; } list.add(currentItem); return list.toArray(new String[]{}); } /** * Parse the delimitered string and return elements as a string array * @param s * @return */ public static String[] getElementsFromString(String s) { return getElementsFromString(s, DELIMETER, QUOTE); } /** * Converts object to String without worrying about null check. * * @param object * @return The object.toString if object is not null; "" otherwise. */ public static String toString(Object object) { if (object == null) { return ""; } else { return object.toString(); } } /** * Trims a specified string, and makes it null if the result is empty string. * * @param string * @return the string processed */ public static String trimAndNullify(String string) { if (string != null) { string = string.trim(); if (string.equals("")) { string = null; } } return string; } /** * @param oldName * @return Trimmed String */ public static String trimSpaceInString(String oldName) { if (oldName == null) { return ""; } return oldName.replace(" ", ""); } /** * Converts a specified string to a Java identifier. * * @param name * @return the Java identifier */ public static String convertToJavaIdentifier(String name) { final char REPLACE_CHAR = '_'; if (name == null || name.length() == 0) { return "" + REPLACE_CHAR; } StringBuilder buf = new StringBuilder(); char c = name.charAt(0); if (!Character.isJavaIdentifierStart(c)) { // Add _ at the beggining instead of replacing it to _. This is // more readable if the name is like 3D_Model. buf.append(REPLACE_CHAR); } for (int i = 0; i < name.length(); i++) { c = name.charAt(i); if (Character.isJavaIdentifierPart(c)) { buf.append(c); } else { buf.append(REPLACE_CHAR); } } return buf.toString(); } /** * Creates a new name by incrementing the number after the underscore at the end of the old name. If there is no * underscore and number at the end, put "_2" at the end. * * @param oldName * @return the new name */ public static String incrementName(String oldName) { final char PREFIX = '_'; String newName; if (oldName == null || oldName.length() == 0) { newName = "noName"; } else { int lastDashIndex = oldName.lastIndexOf(PREFIX); if (lastDashIndex < 0) { newName = oldName + PREFIX + 2; } else { String suffix = oldName.substring(lastDashIndex + 1); try { int number = Integer.parseInt(suffix); int newNumber = number + 1; newName = oldName.substring(0, lastDashIndex + 1) + newNumber; } catch (RuntimeException e) { // It was not a number newName = oldName + PREFIX + 2; } } } return newName; } /** * Returns the local class name of a specified class. * * @param klass * The specified class * @return The local class name */ public static String getClassName(Class klass) { String fullName = klass.getName(); int index = fullName.lastIndexOf("."); if (index < 0) { return fullName; } else { return fullName.substring(index + 1); } } /** * @param throwable * @return The stackTrace in String */ public static String getStackTraceInString(Throwable throwable) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(byteArrayOutputStream); throwable.printStackTrace(printStream); printStream.flush(); return byteArrayOutputStream.toString(); } }
8,942
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/ApplicationSettings.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.common.utils; import java.io.FileOutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.airavata.common.exception.ApplicationSettingsLoadException; import org.apache.airavata.common.exception.ApplicationSettingsStoreException; import org.apache.airavata.common.exception.UnspecifiedApplicationSettingsException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class ApplicationSettings { public static final String SERVER_PROPERTIES="airavata-server.properties"; public static final String CLIENT_PROPERTIES="airavata-client.properties"; private static Properties properties = new Properties(); private static Exception propertyLoadException; protected static final String TRUST_STORE_PATH="trust.store"; protected static final String TRUST_STORE_PASSWORD="trust.store.password"; private static final String REGULAR_EXPRESSION = "\\$\\{[a-zA-Z.-]*\\}"; private final static Logger logger = LoggerFactory.getLogger(ApplicationSettings.class); static{ loadProperties(); } private static void loadProperties() { URL url = getPropertyFileURL(); try { properties.load(url.openStream()); } catch (Exception e) { propertyLoadException=e; } } private static URL getPropertyFileURL() { URL url; if (AiravataUtils.isServer()){ url=ApplicationSettings.class.getClassLoader().getResource(SERVER_PROPERTIES); }else{ url=ApplicationSettings.class.getClassLoader().getResource(CLIENT_PROPERTIES); } return url; } private static void saveProperties() throws ApplicationSettingsStoreException{ URL url = getPropertyFileURL(); if (url.getProtocol().equalsIgnoreCase("file")){ try { properties.store(new FileOutputStream(url.getPath()), Calendar.getInstance().toString()); } catch (Exception e) { throw new ApplicationSettingsStoreException(url.getPath(), e); } }else{ logger.warn("Properties cannot be updated to location "+url.toString()); } } private static void validateSuccessfulPropertyFileLoad() throws ApplicationSettingsException{ if (propertyLoadException!=null){ throw new ApplicationSettingsLoadException(propertyLoadException); } } public static String getSetting(String key) throws ApplicationSettingsException{ validateSuccessfulPropertyFileLoad(); if (properties.containsKey(key)){ return properties.getProperty(key); } throw new UnspecifiedApplicationSettingsException(key); } /** * Returns the configuration value relevant for the given key. * If configuration value contains references to other configuration values they will also * be replaced. E.g :- If configuration key reads http://${ip}:${port}/axis2/services/RegistryService?wsdl, * the variables ip and port will get replaced by their appropriated values in the configuration. * @param key The configuration key to read value of * @return The configuration value. For above example caller will get a value like * http://192.2.33.12:8080/axis2/services/RegistryService?wsdl * @throws ApplicationSettingsException If an error occurred while reading configurations. */ public static String getAbsoluteSetting(String key) throws ApplicationSettingsException { String configurationValueWithVariables = ApplicationSettings.getSetting(key); List<String> variableList = getAllMatches(configurationValueWithVariables, REGULAR_EXPRESSION); if (variableList == null || variableList.isEmpty()) { return configurationValueWithVariables; } for(String variableIdentifier : variableList) { String variableName = getVariableNameOnly(variableIdentifier); String value = getAbsoluteSetting(variableName); configurationValueWithVariables = configurationValueWithVariables.replace(variableIdentifier, value); } return configurationValueWithVariables; } private static String getVariableNameOnly(String variableWithIdentifiers) { return variableWithIdentifiers.substring(2, (variableWithIdentifiers.length() - 1)); } private static List<String> getAllMatches(String text, String regex) { List<String> matches = new ArrayList<String>(); Matcher m = Pattern.compile("(?=(" + regex + "))").matcher(text); while(m.find()) { matches.add(m.group(1)); } return matches; } public static String getSetting(String key, String defaultValue){ try { validateSuccessfulPropertyFileLoad(); if (properties.containsKey(key)){ return properties.getProperty(key); } } catch (ApplicationSettingsException e) { //we'll ignore this error since a default value is provided } return defaultValue; } public static void setSetting(String key, String value) throws ApplicationSettingsException{ properties.setProperty(key, value); saveProperties(); } public static boolean isSettingDefined(String key) throws ApplicationSettingsException{ validateSuccessfulPropertyFileLoad(); return properties.containsKey(key); } public static String getTrustStorePath() throws ApplicationSettingsException { return getSetting(TRUST_STORE_PATH); } public static String getTrustStorePassword() throws ApplicationSettingsException { return getSetting(TRUST_STORE_PASSWORD); } public static void initializeTrustStore() throws ApplicationSettingsException { SecurityUtil.setTrustStoreParameters(getTrustStorePath(), getTrustStorePassword()); } public static Properties getProperties() { return properties; } }
8,943
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/WSConstants.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.common.utils; import javax.xml.namespace.QName; import org.xmlpull.infoset.XmlNamespace; import xsul5.XmlConstants; public interface WSConstants { /** * xmlns */ public final static String XMLNS = "xmlns"; /** * XML Schema prefix, xsd */ public static final String XSD_NS_PREFIX = "xsd"; /** * XML Schema URI. */ public static final String XSD_NS_URI = "http://www.w3.org/2001/XMLSchema"; /** * XML Schema Namespace */ public static final XmlNamespace XSD_NS = XmlConstants.BUILDER.newNamespace(XSD_NS_PREFIX, XSD_NS_URI); /** * The any type. */ public static final QName XSD_ANY_TYPE = new QName(XSD_NS_URI, "any", XSD_NS_PREFIX); /** * xsd:anyURI */ public static final QName XSD_ANY_URI = new QName(XSD_NS_URI, "anyURI", XSD_NS_PREFIX); /** * tns */ public static final String TARGET_NS_PREFIX = "tns"; /** * typens */ public static final String TYPE_NS_PREFIX = "typens"; /** * schema */ public static final String SCHEMA_TAG = "schema"; /** * Element name for annotation, annotation */ public static final String ANNOTATION_TAG = "annotation"; /** * Element name for documentation, documentation */ public static final String DOCUMENTATION_TAG = "documentation"; /** * appinfo */ public static final String APPINFO_TAG = "appinfo"; /** * element */ public static final String ELEMENT_TAG = "element"; /** * sequence */ public static final String SEQUENCE_TAG = "sequence"; /** * complexType */ public static final String COMPLEX_TYPE_TAG = "complexType"; /** * simpleType */ public static final String SIMPLE_TYPE_TAG = "simpleType"; /** * name */ public static final String NAME_ATTRIBUTE = "name"; /** * type */ public static final String TYPE_ATTRIBUTE = "type"; /** * targetNamespace */ public static final String TARGET_NAMESPACE_ATTRIBUTE = "targetNamespace"; /** * elementFormDefault */ public final static String ELEMENT_FORM_DEFAULT_ATTRIBUTE = "elementFormDefault"; /** * unqualified */ public final static String UNQUALIFIED_VALUE = "unqualified"; /** * default */ public static final String DEFAULT_ATTRIBUTE = "default"; /** * UsingAddressing */ public static final String USING_ADDRESSING_TAG = "UsingAddressing"; /** * <appinfo xmlns="http://www.w3.org/2001/XMLSchema"> * * </appinfo> */ public static final String EMPTY_APPINFO = "<appinfo xmlns=\"http://www.w3.org/2001/XMLSchema\">\n\n</appinfo>"; /** * minOccurs */ public static final String MIN_OCCURS_ATTRIBUTE = "minOccurs"; /** * maxOccurs */ public static final String MAX_OCCURS_ATTRIBUTE = "maxOccurs"; /** * unbounded */ public static final String UNBOUNDED_VALUE = "unbounded"; /** * import */ public static final String IMPORT_TAG = "import"; /** * schemaLocation */ public static final String SCHEMA_LOCATION_ATTRIBUTE = "schemaLocation"; public static final String LEAD_NS_URI = "http://www.extreme.indiana.edu/lead"; /** * The any type. */ public static final QName LEAD_ANY_TYPE = new QName(LEAD_NS_URI, "any", XSD_NS_PREFIX); }
8,944
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/KeyStorePasswordCallback.java
package org.apache.airavata.common.utils;/* * * 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. * */ /** * User: AmilaJ (amilaj@apache.org) * Date: 10/11/13 * Time: 11:30 AM */ /** * An interface to get keystore password in a form of a callback. */ public interface KeyStorePasswordCallback { /** * Caller should implement the interface. Should return the password for * the keystore. This should return the keystore password. i.e. password used to open the keystore. * Instead of the actual file. * @return The password to open the keystore. */ char[] getStorePassword(); /** * Caller should implement the interface. Should return the pass phrase for * the secret key. * Instead of the actual file. * @param keyAlias The alias of the key * @return The pass phrase for the secret key. */ char[] getSecretKeyPassPhrase(String keyAlias); }
8,945
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/AiravataUtils.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.common.utils; public class AiravataUtils { public static final String EXECUTION_MODE="application.execution.mode"; public static void setExecutionMode(ExecutionMode mode){ System.setProperty(EXECUTION_MODE, mode.name()); } public static ExecutionMode getExecutionMode(){ if (System.getProperties().containsKey(EXECUTION_MODE)) { return ExecutionMode.valueOf(System.getProperty(EXECUTION_MODE)); }else{ return null; } } public static boolean isServer(){ return getExecutionMode()==ExecutionMode.SERVER; } public static boolean isClient(){ return getExecutionMode()==ExecutionMode.CLIENT; } public static void setExecutionAsServer(){ setExecutionMode(ExecutionMode.SERVER); } public static void setExecutionAsClient(){ setExecutionMode(ExecutionMode.CLIENT); } }
8,946
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/XMLUtil.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.common.utils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.airavata.common.exception.UtilsException; import org.apache.xmlbeans.XmlError; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Text; import org.xml.sax.SAXException; import org.xmlpull.infoset.XmlDocument; import org.xmlpull.infoset.XmlElement; import org.xmlpull.infoset.XmlNamespace; import org.xmlpull.mxp1.MXParserFactory; import org.xmlpull.mxp1_serializer.MXSerializer; public class XMLUtil { /** * The XML builder for XPP5 */ public static final org.xmlpull.infoset.XmlInfosetBuilder BUILDER = org.xmlpull.infoset.XmlInfosetBuilder .newInstance(); /** * The XML builder for XPP3. */ public static final org.xmlpull.v1.builder.XmlInfosetBuilder BUILDER3 = org.xmlpull.v1.builder.XmlInfosetBuilder .newInstance(new MXParserFactory()); private static final Logger logger = LoggerFactory.getLogger(XMLUtil.class); private final static String PROPERTY_SERIALIZER_INDENTATION = "http://xmlpull.org/v1/doc/properties.html#serializer-indentation"; private final static String INDENT = " "; /** * Parses a specified string and returns the XmlElement (XPP3). * * @param string * @return The XmlElement (XPP3) parsed. */ public static org.xmlpull.v1.builder.XmlElement stringToXmlElement3(String string) { return BUILDER3.parseFragmentFromReader(new StringReader(string)); } /** * Parses a specified string and returns the XmlElement (XPP5). * * @param string * @return The XmlElement (XPP5) parsed. */ public static org.xmlpull.infoset.XmlElement stringToXmlElement(String string) { XmlDocument document = BUILDER.parseString(string); org.xmlpull.infoset.XmlElement element = document.getDocumentElement(); return element; } /** * Converts a specified XmlElement (XPP3) to the XmlElement (XPP5). * * @param element * @return The XmlElement (XPP5) converted. */ public static org.xmlpull.infoset.XmlElement xmlElement3ToXmlElement5(org.xmlpull.v1.builder.XmlElement element) { String string = xmlElementToString(element); return stringToXmlElement(string); } /** * Converts a specified XmlElement (XPP5) to the XmlElement (XPP3). * * @param element * @return The XmlElement (XPP3) converted. */ public static org.xmlpull.v1.builder.XmlElement xmlElement5ToXmlElement3(org.xmlpull.infoset.XmlElement element) { String string = xmlElementToString(element); return stringToXmlElement3(string); } /** * Returns the XML string of a specified XmlElement. * * @param element * The specified XmlElement * @return The XML string */ public static String xmlElementToString(org.xmlpull.v1.builder.XmlElement element) { MXSerializer serializer = new MXSerializer(); StringWriter writer = new StringWriter(); serializer.setOutput(writer); serializer.setProperty(PROPERTY_SERIALIZER_INDENTATION, INDENT); BUILDER3.serialize(element, serializer); String xmlText = writer.toString(); return xmlText; } /** * Returns the XML string as a specified XmlElement (XPP5). * * @param element * The specified XmlElement * @return The XML string */ public static String xmlElementToString(org.xmlpull.infoset.XmlElement element) { String string; if (element == null) { string = ""; } else { string = BUILDER.serializeToStringPretty(element); } return string; } /** * Converts a specified XPP5 XML element to a DOM element under a specified document. * * @param xppElement * @param document * @return The converted DOM element. */ public static Element xppElementToDomElement(org.xmlpull.infoset.XmlElement xppElement, Document document) { Element domElement = document.createElement(xppElement.getName()); for (org.xmlpull.infoset.XmlNamespace namespace : xppElement.namespaces()) { logger.debug("namespace: " + namespace); } for (org.xmlpull.infoset.XmlAttribute attribute : xppElement.attributes()) { domElement.setAttribute(attribute.getName(), attribute.getValue()); } for (Object object : xppElement.children()) { if (object instanceof org.xmlpull.infoset.XmlElement) { domElement.appendChild(xppElementToDomElement((org.xmlpull.infoset.XmlElement) object, document)); } else if (object instanceof String) { Text text = document.createTextNode((String) object); domElement.appendChild(text); } else { logger.debug("object.getClass(): " + object.getClass()); } } return domElement; } /** * @param definitions3 * @return The WsdlDefinitions (XSUL5) */ @Deprecated public static xsul5.wsdl.WsdlDefinitions wsdlDefinitions3ToWsdlDefintions5(xsul.wsdl.WsdlDefinitions definitions3) { return WSDLUtil.wsdlDefinitions3ToWsdlDefintions5(definitions3); } /** * @param definitions5 * @return The WsdlDefinitions (XSUL3) */ @Deprecated public static xsul.wsdl.WsdlDefinitions wsdlDefinitions5ToWsdlDefintions3(xsul5.wsdl.WsdlDefinitions definitions5) { return WSDLUtil.wsdlDefinitions5ToWsdlDefintions3(definitions5); } /** * Converts a specified XPP3 XML element to a DOM element under a specified document. * * @param xppElement * @param document * @return The converted DOM element. */ public static Element xppElementToDomElement(org.xmlpull.v1.builder.XmlElement xppElement, Document document) { Element domElement = document.createElement(xppElement.getName()); Iterator nsIt = xppElement.namespaces(); while (nsIt.hasNext()) { org.xmlpull.v1.builder.XmlNamespace namespace = (org.xmlpull.v1.builder.XmlNamespace) nsIt.next(); logger.debug("namespace: " + namespace); // TODO } Iterator attrIt = xppElement.attributes(); while (attrIt.hasNext()) { org.xmlpull.v1.builder.XmlAttribute attribute = (org.xmlpull.v1.builder.XmlAttribute) attrIt.next(); // TODO namespace domElement.setAttribute(attribute.getName(), attribute.getValue()); } Iterator elementIt = xppElement.children(); while (elementIt.hasNext()) { Object object = elementIt.next(); if (object instanceof org.xmlpull.v1.builder.XmlElement) { domElement.appendChild(xppElementToDomElement((org.xmlpull.v1.builder.XmlElement) object, document)); } else if (object instanceof String) { Text text = document.createTextNode((String) object); domElement.appendChild(text); } else { logger.debug("object.getClass(): " + object.getClass()); } } return domElement; } /** * @param element * @return The cloned XmlElement. */ public static org.xmlpull.infoset.XmlElement deepClone(org.xmlpull.infoset.XmlElement element) throws UtilsException { try { XmlElement clonedElement = element.clone(); clonedElement.setParent(null); return clonedElement; } catch (CloneNotSupportedException e) { // This should not happen because we don't put any special Objects. throw new UtilsException(e); } } /** * Saves a specified XmlElement to a specified file. * * @param element * @param file * @throws IOException */ public static void saveXML(org.xmlpull.infoset.XmlElement element, File file) throws IOException { XmlDocument document = BUILDER.newDocument(); document.setDocumentElement(element); String xmlText = BUILDER.serializeToStringPretty(document); IOUtil.writeToFile(xmlText, file); } /** * Saves a specified XmlElement to a specified file. * * @param element * @param file * @throws IOException */ public static void saveXML(org.xmlpull.v1.builder.XmlElement element, File file) throws IOException { saveXML(xmlElement3ToXmlElement5(element), file); } /** * @param file * @return The XmlElement in the document. * @throws IOException */ public static org.xmlpull.infoset.XmlElement loadXML(InputStream stream) throws IOException { String xmlText = IOUtil.readToString(stream); XmlDocument document = BUILDER.parseString(xmlText); return document.getDocumentElement(); } /** * @param file * @return The XmlElement in the document. * @throws IOException */ public static org.xmlpull.infoset.XmlElement loadXML(File file) throws IOException { return loadXML(new FileInputStream(file)); } /** * @param string * @return true if the specified string is XML, false otherwise */ public static boolean isXML(String string) { try { stringToXmlElement(string); return true; } catch (RuntimeException e) { return false; } } /** * Validates a specified XmlObject along with logging errors if any. * * @param xmlObject */ public static void validate(XmlObject xmlObject) throws UtilsException { XmlOptions validateOptions = new XmlOptions(); ArrayList errorList = new ArrayList(); validateOptions.setErrorListener(errorList); boolean isValid = xmlObject.validate(validateOptions); if (isValid) { // Valid return; } // Error StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < errorList.size(); i++) { XmlError error = (XmlError) errorList.get(i); logger.warn("Message: " + error.getMessage()); logger.warn("Location of invalid XML: " + error.getCursorLocation().xmlText()); stringBuilder.append("Message:" + error.getMessage()); stringBuilder.append("Location of invalid XML: " + error.getCursorLocation().xmlText()); } throw new UtilsException(stringBuilder.toString()); } /** * Returns the local part of a specified QName. * * @param qname * the specified QName in string, e.g. ns:value * @return the local part of the QName, e.g. value */ public static String getLocalPartOfQName(String qname) { int index = qname.indexOf(':'); if (index < 0) { return qname; } else { return qname.substring(index + 1); } } /** * Returns the prefix of a specified QName. * * @param qname * the specified QName in string, e.g. ns:value * @return the prefix of the QName, e.g. ns */ public static String getPrefixOfQName(String qname) { int index = qname.indexOf(':'); if (index < 0) { return null; } else { return qname.substring(0, index); } } /** * @param prefixCandidate * @param uri * @param alwaysUseSuffix * @param element * @return The namespace found or declared. */ public static XmlNamespace declareNamespaceIfNecessary(String prefixCandidate, String uri, boolean alwaysUseSuffix, XmlElement element) { XmlNamespace namespace = element.lookupNamespaceByName(uri); if (namespace == null) { return declareNamespace(prefixCandidate, uri, alwaysUseSuffix, element); } else { return namespace; } } /** * @param prefixCandidate * @param uri * @param alwaysUseSuffix * @param element * @return The namespace declared. */ public static XmlNamespace declareNamespace(String prefixCandidate, String uri, boolean alwaysUseSuffix, XmlElement element) { if (prefixCandidate == null || prefixCandidate.length() == 0) { prefixCandidate = "a"; } String prefix = prefixCandidate; if (alwaysUseSuffix) { prefix += "0"; } if (element.lookupNamespaceByPrefix(prefix) != null) { int i = 1; prefix = prefixCandidate + i; while (element.lookupNamespaceByPrefix(prefix) != null) { i++; } } XmlNamespace namespace = element.declareNamespace(prefix, uri); return namespace; } /** * * @param xml * @param name */ public static void removeElements(XmlElement xml, String name) { Iterable<XmlElement> removeElements = xml.elements(null, name); LinkedList<XmlElement> removeList = new LinkedList<XmlElement>(); for (XmlElement xmlElement : removeElements) { removeList.add(xmlElement); } for (XmlElement xmlElement : removeList) { xml.removeChild(xmlElement); } Iterable children = xml.children(); for (Object object : children) { if (object instanceof XmlElement) { XmlElement element = (XmlElement) object; removeElements(element, name); } } } /** * @param url * @return Document */ public static Document retrievalXMLDocFromUrl(String url) { try { URL xmlUrl = new URL(url); InputStream in = xmlUrl.openStream(); Document ret = null; DocumentBuilderFactory domFactory; DocumentBuilder builder; domFactory = DocumentBuilderFactory.newInstance(); domFactory.setValidating(false); domFactory.setNamespaceAware(false); builder = domFactory.newDocumentBuilder(); ret = builder.parse(in); return ret; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; } /** * @param url * @return Document */ public static Document retrievalXMLDocForParse(String url) { try { URL xmlUrl = new URL(url); InputStream in = xmlUrl.openStream(); DocumentBuilderFactory xmlFact = DocumentBuilderFactory.newInstance(); xmlFact.setNamespaceAware(true); DocumentBuilder builder = xmlFact.newDocumentBuilder(); Document doc = builder.parse(in); return doc; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } return null; } public static boolean isEqual(XmlElement elem1, XmlElement elem2) throws Exception { if (elem1 == null && elem2 == null) { return true; } else if (elem1 == null) { return false; } else if (elem2 == null) { return false; } if (!elem1.getName().equals(elem2.getName())) { return false; } else { // now check if children are the same Iterator children1 = elem1.children().iterator(); Iterator children2 = elem2.children().iterator(); //check first ones for string Object child1 = null; Object child2 = null; if (children1.hasNext() && children2.hasNext()) { child1 = children1.next(); child2 = children2.next(); if (!children1.hasNext() && !children2.hasNext()) { //only one node could be string could be xmlelement return compareObjs(child1, child2); } else { //get new iterators List<XmlElement> elemSet1 = getXmlElementsOnly(elem1.children().iterator()); List<XmlElement> elemSet2 = getXmlElementsOnly(elem2.children().iterator()); if(elemSet1.size() != elemSet2.size()){ return false; } for(int i =0; i< elemSet1.size(); ++i){ if(!isEqual(elemSet1.get(i), elemSet2.get(i))){ return false; } } return true; } }else { //no internal element return true; } } } private static List<XmlElement> getXmlElementsOnly(Iterator itr){ LinkedList<XmlElement> list = new LinkedList<XmlElement>(); while(itr.hasNext()){ Object obj = itr.next(); if(obj instanceof XmlElement){ list.add((XmlElement) obj); } } return list; } private static boolean compareObjs(Object child1, Object child2) throws Exception { if (child1 instanceof String && child2 instanceof String) { return child1.equals(child2); } else if (child1 instanceof XmlElement && child2 instanceof XmlElement) { return isEqual((XmlElement) child1, (XmlElement) child2); } else { return false; } } }
8,947
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/IOUtil.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.common.utils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.Writer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class IOUtil { private static final Logger logger = LoggerFactory.getLogger(IOUtil.class); /** * @param path * @param content * @throws IOException */ public static void writeToFile(String content, String path) throws IOException { logger.debug("Path:" + path + " Content:" + content); FileWriter fw = new FileWriter(path); writeToWriter(content, fw); } /** * @param content * @param file * @throws IOException */ public static void writeToFile(String content, File file) throws IOException { FileWriter fw = new FileWriter(file); writeToWriter(content, fw); } /** * @param inputStream * @param file * @throws IOException */ public static void writeToFile(InputStream inputStream, File file) throws IOException { FileOutputStream outputStream = new FileOutputStream(file); byte[] bytes = new byte[1024]; int len; while ((len = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } outputStream.close(); } /** * Writes a specified String to a specified Writer. * * @param content * The content to write * @param writer * The specified Writer * * @throws IOException */ public static void writeToWriter(String content, Writer writer) throws IOException { writer.write(content); writer.close(); } /** * Returns the content of a specified file as a String. * * @param path * @return the content of a specified file as a String * @throws IOException */ public static String readFileToString(String path) throws IOException { FileReader read = new FileReader(path); return readToString(read); } /** * Returns the content of a specified file as a String. * * @param file * @return the content of a specified file as a String * @throws IOException */ public static String readFileToString(File file) throws IOException { FileReader reader = new FileReader(file); return readToString(reader); } /** * Returns a String read from a specified InputStream. * * @param stream * The specified InputStream * @return The String read from the specified InputStream * @throws IOException */ public static String readToString(InputStream stream) throws IOException { return readToString(new InputStreamReader(stream)); } /** * Returns a String read from a specified Reader. * * @param reader * The specified Reader * @return The String read from the specified Reader * @throws IOException */ public static String readToString(Reader reader) throws IOException { char[] cbuf = new char[1024]; StringBuilder sbuf = new StringBuilder(); int len; while ((len = reader.read(cbuf)) != -1) { sbuf.append(cbuf, 0, len); } return sbuf.toString(); } /** * @param file * @return The byte array * @throws IOException */ public static byte[] readToByteArray(File file) throws IOException { return readToByteArray(new FileInputStream(file)); } /** * @param inputStream * @return The byte array. * @throws IOException */ public static byte[] readToByteArray(InputStream inputStream) throws IOException { byte[] buf = new byte[1024]; ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream(); int len; while ((len = inputStream.read(buf)) != -1) { byteArrayStream.write(buf, 0, len); } return byteArrayStream.toByteArray(); } /** * @param path * @return <code>true</code> if and only if the file or directory is successfully deleted; <code>false</code> * otherwise */ public static boolean deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); for (File file : files) { if (file.isDirectory()) { deleteDirectory(file); } else { file.delete(); } } } return path.delete(); } /** * Gets the extension of a specified file. * * @param file * the specified file. * @return the extension of the file in lower case if there is an extension; null otherwise */ public static String getExtension(File file) { String ext = null; String name = file.getName(); int index = name.lastIndexOf('.'); if (index > 0 && index < name.length() - 1) { ext = name.substring(index + 1).toLowerCase(); } return ext; } }
8,948
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/DerbyUtil.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.common.utils; import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import java.sql.DriverManager; import org.apache.derby.drda.NetworkServerControl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.SQLException; /** * This class includes methods to start stop Derby database. Mainly user for tests. */ public class DerbyUtil { private static NetworkServerControl server; private static final Logger logger = LoggerFactory.getLogger(DerbyUtil.class); public static final String DERBY_SERVER_MODE_SYS_PROPERTY = "derby.drda.startNetworkServer"; /** * Starts new derby server instance with given configurations. * * @param hostAddress * The host address start the server. * @param port * The port number which server is starting. * @param user * JDBC user name. * @param password * JDBC password. * @throws Exception * If an error occurred while starting the server. */ public static void startDerbyInServerMode(String hostAddress, int port, String user, String password) throws Exception { PrintWriter consoleWriter = null; try { System.setProperty(DERBY_SERVER_MODE_SYS_PROPERTY, "true"); server = new NetworkServerControl(InetAddress.getByName(hostAddress), port, user, password); consoleWriter = new 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", e); throw e; } catch (Exception e) { logger.error("Unable to start Apache derby in the server mode! Check whether " + "specified port is available", e); throw e; } finally { if (consoleWriter != null) { consoleWriter.close(); } } } /** * Starts derby server in embedded mode. * * @throws ClassNotFoundException * If specified driver not found in the class path. * @throws SQLException * If an error occurred while creat */ public static void startDerbyInEmbeddedMode() throws ClassNotFoundException, SQLException { Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); DriverManager.getConnection("jdbc:derby:memory:unit-testing-jpa;create=true").close(); } /** * Shuts down the server. * * @throws Exception * If an error occurred while shutting down. */ public static void stopDerbyServer() throws Exception { try { server.shutdown(); } catch (Exception e) { logger.error("Error shutting down derby server.", e); throw e; } } }
8,949
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/NameValidator.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.common.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NameValidator { /** * @param name * @return Is it valid name? */ public static boolean validate(String name) { // Set the name pattern string Pattern p = Pattern.compile("([a-zA-Z]){1,}([0-9]|_|\\.|[a-zA-Z]){0,}$"); // Match the given string with the pattern Matcher m = p.matcher(name); // Check whether match is found boolean matchFound = m.matches(); return matchFound; } /** * @param args * @Description some quick tests */ public static void main(String[] args) { System.out.println(validate("abc90_90abc")); // true System.out.println(validate("abc_abc_123")); // true System.out.println(validate("abc_abc_")); // true System.out.println(validate("abc_abc")); // true System.out.println(validate("abc.abc")); // true System.out.println(validate("9abc_abc")); // false, name cannot start with number System.out.println(validate("_abc_abc")); // false, name cannot start with "_" System.out.println(validate("\\abc_abc")); // false, name cannot start with "\" System.out.println(validate("abc\\_abc")); // false, name cannot contain "\" } }
8,950
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/AiravataJobState.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.common.utils; /* These are the job statuses shared in database level between orchestrator and gfac instances */ public class AiravataJobState { public enum State { CREATED { public String toString() { return "CREATED"; } }, ACCEPTED { public String toString() { return "ACCEPTED"; } }, FETCHED { public String toString() { return "FETCHED"; } }, INHANDLERSDONE { public String toString() { return "INHANDLERSDONE"; } }, SUBMITTED { public String toString() { return "SUBMITTED"; } }, OUTHANDLERSDONE { public String toString() { return "OUTHANDLERSDONE"; } }, RUNNING { public String toString() { return "RUNNING"; } }, FAILED { public String toString() { return "FAILED"; } }, PAUSED { public String toString() { return "PAUSED"; } }, FINISHED { public String toString() { return "FINISHED"; } }, PENDING { public String toString() { return "PENDING"; } }, ACTIVE { public String toString() { return "ACTIVE"; } }, DONE { public String toString() { return "DONE"; } }, UNKNOWN { public String toString() { return "UNKNOWN"; } } } }
8,951
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/BrowserLauncher.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.common.utils; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import org.apache.airavata.common.exception.UtilsException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Opens URLs with the OS-specific browser. */ public class BrowserLauncher { private static final String ERROR_MESSAGE = "Error while attempting to launch web browser"; private static Logger logger = LoggerFactory.getLogger(BrowserLauncher.class); /** * Opens a specified URL with the browser. * * @param url * The specified URL. * @throws UtilsException */ public static void openURL(URL url) throws UtilsException { openURL(url.toString()); } /** * Opens a specified URL with the browser. * * @param url * The specified URL. * @throws UtilsException */ public static void openURL(String url) throws UtilsException { logger.debug("Enter:" + url); String osName = System.getProperty("os.name"); try { if (osName.startsWith("Mac OS")) { Class macUtils = Class.forName("com.apple.mrj.MRJFileUtils"); Method openURL = macUtils.getDeclaredMethod("openURL", new Class[] { String.class }); openURL.invoke(null, new Object[] { url }); } else if (osName.startsWith("Windows")) Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url); else { // assume Unix or Linux String[] browsers = { "firefox", "mozilla", "netscape", "opera", "konqueror" }; String browser = null; for (int count = 0; count < browsers.length && browser == null; count++) if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0) browser = browsers[count]; if (browser == null) { throw new UtilsException("Could not find web browser."); } else { Runtime.getRuntime().exec(new String[] { browser, url }); } } } catch (ClassNotFoundException e) { throw new UtilsException(ERROR_MESSAGE, e); } catch (NoSuchMethodException e) { throw new UtilsException(ERROR_MESSAGE, e); } catch (IllegalAccessException e) { throw new UtilsException(ERROR_MESSAGE, e); } catch (InvocationTargetException e) { throw new UtilsException(ERROR_MESSAGE, e); } catch (IOException e) { throw new UtilsException(ERROR_MESSAGE, e); } catch (InterruptedException e) { throw new UtilsException(ERROR_MESSAGE, e); } catch (RuntimeException e) { throw new UtilsException(ERROR_MESSAGE, e); } } }
8,952
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/Version.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.common.utils; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement public class Version { public String PROJECT_NAME; private Integer majorVersion=0; private Integer minorVersion=0; private Integer maintenanceVersion; private String versionData; private BuildType buildType; public static enum BuildType{ ALPHA, BETA, RC } public Version() { } public Version(String PROJECT_NAME,Integer majorVersion,Integer minorVersion,Integer maintenanceVersion,String versionData,BuildType buildType) { this.PROJECT_NAME=PROJECT_NAME; this.majorVersion=majorVersion; this.minorVersion=minorVersion; this.maintenanceVersion=maintenanceVersion; this.versionData=versionData; this.buildType=buildType; } public Integer getMajorVersion() { return majorVersion; } public Integer getMinorVersion() { return minorVersion; } public Integer getMaintenanceVersion() { return maintenanceVersion; } public String getVersionData() { return versionData; } public BuildType getBuildType() { return buildType; } public String getVersion(){ String version = getBaseVersion(); version = attachVersionData(version); return version; } private String attachVersionData(String version) { if (getVersionData()!=null){ version+="-"+getVersionData(); } return version; } public String getBaseVersion() { String version=getMajorVersion().toString()+"."+getMinorVersion(); return version; } public String getFullVersion(){ String version = getBaseVersion(); version = attachMaintainanceVersion(version); version = attachVersionData(version); version = attachBuildType(version); return version; } private String attachMaintainanceVersion(String version) { if (getMaintenanceVersion()!=null){ version+="."+getMaintenanceVersion(); } return version; } private String attachBuildType(String version) { if (getBuildType()!=null){ version+="-"+getBuildType().name(); } return version; } @Override public String toString() { return getVersion(); } }
8,953
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/utils/Constants.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.common.utils; /** * Constants used in Airavata should go here. */ public final class Constants { public static final String USER_IN_SESSION = "userName"; public static final String GATEWAY_NAME = "gateway_id"; }
8,954
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/exception/AiravataException.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.common.exception; public class AiravataException extends Exception { private static final long serialVersionUID = -5665822765183116821L; public AiravataException() { } public AiravataException(String message, Throwable e) { super(message,e); } public AiravataException(String message) { super(message); } }
8,955
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/exception/ApplicationSettingsLoadException.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.common.exception; public class ApplicationSettingsLoadException extends ApplicationSettingsException { private static final long serialVersionUID = -5102090895499711299L; public ApplicationSettingsLoadException(String message) { super(message); } public ApplicationSettingsLoadException(Throwable e) { this(e.getMessage(),e); } public ApplicationSettingsLoadException(String message, Throwable e) { super(message,e); } }
8,956
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/exception/ApplicationSettingsException.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.common.exception; public class ApplicationSettingsException extends AiravataException { private static final long serialVersionUID = -4901850535475160411L; public ApplicationSettingsException(String message) { super(message); } public ApplicationSettingsException(String message, Throwable e) { super(message, e); } }
8,957
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/exception/UtilsException.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.common.exception; public class UtilsException extends Exception { /** * Constructs a UtilsException. * */ public UtilsException() { super(); } /** * Constructs a UtilsException. * * @param message */ public UtilsException(String message) { super(message); } /** * Constructs a UtilsException. * * @param cause */ public UtilsException(Throwable cause) { super(cause); } /** * Constructs a UtilsException. * * @param message * @param cause */ public UtilsException(String message, Throwable cause) { super(message, cause); } }
8,958
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/exception/UnspecifiedApplicationSettingsException.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.common.exception; public class UnspecifiedApplicationSettingsException extends ApplicationSettingsException { private static final long serialVersionUID = -1159027432434546003L; public UnspecifiedApplicationSettingsException(String key) { super("The '"+key+"' is not configured in settings!!!"); } }
8,959
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/exception/ApplicationSettingsStoreException.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.common.exception; public class ApplicationSettingsStoreException extends ApplicationSettingsException { private static final long serialVersionUID = -5102090895499711299L; public ApplicationSettingsStoreException(String filePath) { super("Error while attempting to store settings in "+filePath); } public ApplicationSettingsStoreException(String filePath, Throwable e) { super(filePath,e); } }
8,960
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/exception/LazyLoadedDataException.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.common.exception; public class LazyLoadedDataException extends AiravataException { private static final long serialVersionUID = -3164776318582067936L; public LazyLoadedDataException(String message) { super(message); } }
8,961
0
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common
Create_ds/airavata-sandbox/utils/src/main/java/org/apache/airavata/common/exception/AiravataConfigurationException.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.common.exception; public class AiravataConfigurationException extends AiravataException { private static final long serialVersionUID = -9124231436834631249L; public AiravataConfigurationException() { } public AiravataConfigurationException(String message){ this(message, null); } public AiravataConfigurationException(String message, Throwable e){ super(message,e); } }
8,962
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/test/java/org/apache/airavata/core/gfac/services
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/test/java/org/apache/airavata/core/gfac/services/impl/SchedulerTest.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.core.gfac.services.impl; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.core.gfac.context.invocation.impl.DefaultExecutionContext; import org.apache.airavata.core.gfac.context.invocation.impl.DefaultInvocationContext; import org.apache.airavata.core.gfac.context.message.impl.ParameterContextImpl; import org.apache.airavata.core.gfac.notification.impl.LoggingNotification; import org.apache.airavata.core.gfac.provider.Provider; import org.apache.airavata.core.gfac.provider.impl.GramProvider; import org.apache.airavata.core.gfac.provider.impl.LocalProvider; import org.apache.airavata.core.gfac.scheduler.Scheduler; import org.apache.airavata.core.gfac.scheduler.impl.SchedulerImpl; import org.apache.airavata.registry.api.impl.AiravataJCRRegistry; import org.apache.airavata.schemas.gfac.ApplicationDeploymentDescriptionType; import org.apache.airavata.schemas.gfac.InputParameterType; import org.apache.airavata.schemas.gfac.OutputParameterType; import org.apache.airavata.schemas.gfac.StringParameterType; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.fail; public class SchedulerTest { private AiravataJCRRegistry jcrRegistry; @Before public void setUp() throws Exception { /* * Create database */ Map<String,String> config = new HashMap<String,String>(); config.put("org.apache.jackrabbit.repository.home","target"); jcrRegistry = new AiravataJCRRegistry(null, "org.apache.jackrabbit.core.RepositoryFactoryImpl", "admin", "admin", config); /* * Host */ HostDescription host = new HostDescription(); host.getType().setHostName("localhost"); host.getType().setHostAddress("10.11.111.1"); /* * App */ ApplicationDeploymentDescription appDesc = new ApplicationDeploymentDescription(); ApplicationDeploymentDescriptionType app = appDesc.getType(); ApplicationDeploymentDescriptionType.ApplicationName name = ApplicationDeploymentDescriptionType.ApplicationName.Factory.newInstance(); name.setStringValue("EchoLocal"); app.setApplicationName(name); app.setExecutableLocation("/bin/echo"); app.setScratchWorkingDirectory("/tmp"); app.setStaticWorkingDirectory("/tmp"); app.setInputDataDirectory("/tmp/input"); app.setOutputDataDirectory("/tmp/output"); app.setStandardOutput("/tmp/echo.stdout"); app.setStandardError("/tmp/echo.stdout"); /* * Service */ ServiceDescription serv = new ServiceDescription(); serv.getType().setName("SimpleEcho"); List<InputParameterType> inputList = new ArrayList<InputParameterType>(); InputParameterType input = InputParameterType.Factory.newInstance(); input.setParameterName("echo_input"); input.setParameterType(StringParameterType.Factory.newInstance()); inputList.add(input); InputParameterType[] inputParamList = inputList.toArray(new InputParameterType[inputList .size()]); List<OutputParameterType> outputList = new ArrayList<OutputParameterType>(); OutputParameterType output = OutputParameterType.Factory.newInstance(); output.setParameterName("echo_output"); output.setParameterType(StringParameterType.Factory.newInstance()); outputList.add(output); OutputParameterType[] outputParamList = outputList .toArray(new OutputParameterType[outputList.size()]); serv.getType().setInputParametersArray(inputParamList); serv.getType().setOutputParametersArray(outputParamList); /* * Save to registry */ jcrRegistry.saveHostDescription(host); jcrRegistry.saveDeploymentDescription(serv.getType().getName(), host .getType().getHostName(), appDesc); jcrRegistry.saveServiceDescription(serv); jcrRegistry.deployServiceOnHost(serv.getType().getName(), host .getType().getHostName()); } @Test public void testExecute() { try { DefaultInvocationContext ct = new DefaultInvocationContext(); DefaultExecutionContext ec = new DefaultExecutionContext(); ec.addNotifiable(new LoggingNotification()); ct.setExecutionContext(ec); ct.setServiceName("SimpleEcho"); /* * Input */ ParameterContextImpl input = new ParameterContextImpl(); ActualParameter echo_input = new ActualParameter(); ((StringParameterType)echo_input.getType()).setValue("echo_output=hello"); input.add("echo_input", echo_input); /* * Output */ ParameterContextImpl output = new ParameterContextImpl(); ActualParameter echo_output = new ActualParameter(); output.add("echo_output", echo_output); // parameter ct.setInput(input); ct.setOutput(output); ct.getExecutionContext().setRegistryService(jcrRegistry); Scheduler scheduler = new SchedulerImpl(); Provider provider = scheduler.schedule(ct); if(provider instanceof GramProvider){ junit.framework.Assert.assertTrue(true); }else { junit.framework.Assert.assertTrue(false); } } catch (Exception e) { e.printStackTrace(); fail("ERROR"); } } }
8,963
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/test/java/org/apache/airavata/core/gfac/services
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/test/java/org/apache/airavata/core/gfac/services/impl/PropertiesBasedServiceImplTest.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.core.gfac.services.impl; import static org.junit.Assert.fail; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.core.gfac.context.invocation.impl.DefaultExecutionContext; import org.apache.airavata.core.gfac.context.invocation.impl.DefaultInvocationContext; import org.apache.airavata.core.gfac.context.message.impl.ParameterContextImpl; import org.apache.airavata.core.gfac.notification.impl.LoggingNotification; import org.apache.airavata.registry.api.impl.AiravataJCRRegistry; import org.apache.airavata.schemas.gfac.ApplicationDeploymentDescriptionType; import org.apache.airavata.schemas.gfac.ApplicationDeploymentDescriptionType.ApplicationName; import org.apache.airavata.schemas.gfac.InputParameterType; import org.apache.airavata.schemas.gfac.OutputParameterType; import org.apache.airavata.schemas.gfac.StringParameterType; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.SystemUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class PropertiesBasedServiceImplTest { @Before public void setUp() throws Exception { /* * Create database */ Map<String,String> config = new HashMap<String,String>(); config.put("org.apache.jackrabbit.repository.home","target"); AiravataJCRRegistry jcrRegistry = new AiravataJCRRegistry(null, "org.apache.jackrabbit.core.RepositoryFactoryImpl", "admin", "admin", config); /* * Host */ HostDescription host = new HostDescription(); host.getType().setHostName("localhost"); host.getType().setHostAddress("localhost"); /* * App */ ApplicationDeploymentDescription appDesc = new ApplicationDeploymentDescription(); ApplicationDeploymentDescriptionType app = appDesc.getType(); ApplicationName name = ApplicationName.Factory.newInstance(); name.setStringValue("EchoLocal"); app.setApplicationName(name); /* * Use bat file if it is compiled on Windows */ if(SystemUtils.IS_OS_WINDOWS){ URL url = this.getClass().getClassLoader().getResource("echo.bat"); app.setExecutableLocation(url.getFile()); }else{ //for unix and Mac app.setExecutableLocation("/bin/echo"); } /* * Default tmp location */ String tempDir = System.getProperty("java.io.tmpdir"); if(tempDir == null){ tempDir = "/tmp"; } app.setScratchWorkingDirectory(tempDir); app.setStaticWorkingDirectory(tempDir); app.setInputDataDirectory(tempDir + File.separator + "input"); app.setOutputDataDirectory(tempDir + File.separator + "output"); app.setStandardOutput(tempDir + File.separator + "echo.stdout"); app.setStandardError(tempDir + File.separator + "echo.stdout"); /* * Service */ ServiceDescription serv = new ServiceDescription(); serv.getType().setName("SimpleEcho"); List<InputParameterType> inputList = new ArrayList<InputParameterType>(); InputParameterType input = InputParameterType.Factory.newInstance(); input.setParameterName("echo_input"); input.setParameterType(StringParameterType.Factory.newInstance()); inputList.add(input); InputParameterType[] inputParamList = inputList.toArray(new InputParameterType[inputList .size()]); List<OutputParameterType> outputList = new ArrayList<OutputParameterType>(); OutputParameterType output = OutputParameterType.Factory.newInstance(); output.setParameterName("echo_output"); output.setParameterType(StringParameterType.Factory.newInstance()); outputList.add(output); OutputParameterType[] outputParamList = outputList .toArray(new OutputParameterType[outputList.size()]); serv.getType().setInputParametersArray(inputParamList); serv.getType().setOutputParametersArray(outputParamList); /* * Save to registry */ jcrRegistry.saveHostDescription(host); jcrRegistry.saveDeploymentDescription(serv.getType().getName(), host .getType().getHostName(), appDesc); jcrRegistry.saveServiceDescription(serv); jcrRegistry.deployServiceOnHost(serv.getType().getName(), host .getType().getHostName()); } @Test public void testExecute() { try { DefaultInvocationContext ct = new DefaultInvocationContext(); DefaultExecutionContext ec = new DefaultExecutionContext(); ec.addNotifiable(new LoggingNotification()); ct.setExecutionContext(ec); Map<String,String> config = new HashMap<String,String>(); config.put("org.apache.jackrabbit.repository.home","target"); AiravataJCRRegistry jcrRegistry = new AiravataJCRRegistry(null, "org.apache.jackrabbit.core.RepositoryFactoryImpl", "admin", "admin", config); ec.setRegistryService(jcrRegistry); ct.setServiceName("SimpleEcho"); /* * Input */ ParameterContextImpl input = new ParameterContextImpl(); ActualParameter echo_input = new ActualParameter(); ((StringParameterType)echo_input.getType()).setValue("echo_output=hello"); input.add("echo_input", echo_input); /* * Output */ ParameterContextImpl output = new ParameterContextImpl(); ActualParameter echo_output = new ActualParameter(); output.add("echo_output", echo_output); // parameter ct.setInput(input); ct.setOutput(output); PropertiesBasedServiceImpl service = new PropertiesBasedServiceImpl(); service.init(); service.execute(ct); Assert.assertNotNull(ct.getOutput()); Assert.assertNotNull(ct.getOutput().getValue("echo_output")); Assert.assertEquals("hello", ((StringParameterType)((ActualParameter)ct.getOutput().getValue("echo_output")).getType()).getValue()); } catch (Exception e) { e.printStackTrace(); fail("ERROR"); } } }
8,964
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/GfacAPI.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.core.gfac; import org.apache.airavata.common.workflow.execution.context.WorkflowContextHeaderBuilder; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.core.gfac.context.GFacConfiguration; import org.apache.airavata.core.gfac.context.JobContext; import org.apache.airavata.core.gfac.context.invocation.impl.DefaultExecutionContext; import org.apache.airavata.core.gfac.context.invocation.impl.DefaultInvocationContext; import org.apache.airavata.core.gfac.context.message.impl.ParameterContextImpl; import org.apache.airavata.core.gfac.context.message.impl.WorkflowContextImpl; import org.apache.airavata.core.gfac.context.security.impl.GSISecurityContext; import org.apache.airavata.core.gfac.factory.PropertyServiceFactory; import org.apache.airavata.core.gfac.notification.impl.LoggingNotification; import org.apache.airavata.core.gfac.notification.impl.WorkflowTrackingNotification; import org.apache.airavata.core.gfac.services.GenericService; import org.apache.airavata.registry.api.Axis2Registry; import org.apache.airavata.schemas.gfac.*; import org.apache.airavata.schemas.wec.SecurityContextDocument; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.Map; public class GfacAPI { private static final Logger log = LoggerFactory.getLogger(GfacAPI.class); public static final String REPOSITORY_PROPERTIES = "repository.properties"; public DefaultInvocationContext gridJobSubmit(JobContext jobContext,GFacConfiguration gfacConfig) throws Exception { String workflowNodeId = WorkflowContextHeaderBuilder.getCurrentContextHeader().getWorkflowMonitoringContext().getWorkflowNodeId(); String workflowInstanceId = WorkflowContextHeaderBuilder.getCurrentContextHeader().getWorkflowMonitoringContext().getWorkflowInstanceId(); WorkflowTrackingNotification workflowNotification = new WorkflowTrackingNotification(jobContext.getBrokerURL(), jobContext.getTopic(),workflowNodeId,workflowInstanceId); LoggingNotification loggingNotification = new LoggingNotification(); DefaultInvocationContext invocationContext = new DefaultInvocationContext(); invocationContext.setExecutionContext(new DefaultExecutionContext()); invocationContext.setServiceName(jobContext.getServiceName()); invocationContext.getExecutionContext().setRegistryService(gfacConfig.getRegistry()); invocationContext.getExecutionContext().addNotifiable(workflowNotification); invocationContext.getExecutionContext().addNotifiable(loggingNotification); GSISecurityContext gssContext = new GSISecurityContext(); // if (gridMyproxyRepository == null) { gssContext.setMyproxyPasswd(gfacConfig.getMyProxyPassphrase()); gssContext.setMyproxyUserName(gfacConfig.getMyProxyUser()); gssContext.setMyproxyLifetime(gfacConfig.getMyProxyLifeCycle()); gssContext.setMyproxyServer(gfacConfig.getMyProxyServer()); // } else { // gssContext.setMyproxyPasswd(gridMyproxyRepository.getPassword()); // gssContext.setMyproxyUserName(gridMyproxyRepository.getUsername()); // gssContext.setMyproxyLifetime(gridMyproxyRepository.getLifeTimeInhours()); // gssContext.setMyproxyServer(gridMyproxyRepository.getMyproxyServer()); // } gssContext.setTrustedCertLoc(gfacConfig.getTrustedCertLocation()); invocationContext.addSecurityContext("myproxy", gssContext); /* * Add workflow context */ ServiceDescription serviceDescription = gfacConfig.getRegistry().getServiceDescription(jobContext.getServiceName()); ServiceDescriptionType serviceDescriptionType = serviceDescription.getType(); ParameterContextImpl inputParam = new ParameterContextImpl(); WorkflowContextImpl workflowContext = new WorkflowContextImpl(); workflowContext.setValue(WorkflowContextImpl.WORKFLOW_ID, URI.create(jobContext.getTopic()).toString()); invocationContext.addMessageContext(WorkflowContextImpl.WORKFLOW_CONTEXT_NAME, workflowContext); for(Parameter parameter:jobContext.getParameters().keySet()){ inputParam.add(parameter.getParameterName(), jobContext.getParameters().get(parameter)); } /* * Output */ ParameterContextImpl outputParam = new ParameterContextImpl(); // List<Parameter> outputs = serviceDescription.getOutputParameters(); for (OutputParameterType parameter : serviceDescriptionType.getOutputParametersArray()) { ActualParameter actualParameter = new ActualParameter(); if ("String".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(StringParameterType.type); } else if ("Double".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(DoubleParameterType.type); } else if ("Integer".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(IntegerParameterType.type); } else if ("Float".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(FloatParameterType.type); } else if ("Boolean".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(BooleanParameterType.type); } else if ("File".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(FileParameterType.type); } else if ("URI".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(URIParameterType.type); } else if ("StringArray".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(StringArrayType.type); } else if ("DoubleArray".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(DoubleArrayType.type); } else if ("IntegerArray".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(IntegerArrayType.type); } else if ("FloatArray".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(FloatArrayType.type); } else if ("BooleanArray".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(BooleanArrayType.type); } else if ("FileArray".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(FileArrayType.type); } else if ("URIArray".equals(parameter.getParameterType().getName())) { actualParameter.getType().changeType(URIArrayType.type); } outputParam.add(parameter.getParameterName(), actualParameter); } invocationContext.setInput(inputParam); invocationContext.setOutput(outputParam); GenericService service = new PropertyServiceFactory(GfacAPI.REPOSITORY_PROPERTIES).createService(); service.execute(invocationContext); return invocationContext; } }
8,965
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/GFacConfiguration.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.core.gfac.context; import org.apache.airavata.registry.api.AiravataRegistry; import org.apache.airavata.registry.api.Axis2Registry; public class GFacConfiguration { private String myProxyServer; private String myProxyUser; private String myProxyPassphrase; private int myProxyLifeCycle; private AiravataRegistry registry; private String trustedCertLocation; public GFacConfiguration(String myProxyServer, String myProxyUser, String myProxyPassphrase, int myProxyLifeCycle, AiravataRegistry axis2Registry, String trustedCertLocation) { this.myProxyServer = myProxyServer; this.myProxyUser = myProxyUser; this.myProxyPassphrase = myProxyPassphrase; this.myProxyLifeCycle = myProxyLifeCycle; this.registry = axis2Registry; this.trustedCertLocation = trustedCertLocation; } public String getMyProxyServer() { return myProxyServer; } public String getMyProxyUser() { return myProxyUser; } public String getMyProxyPassphrase() { return myProxyPassphrase; } public int getMyProxyLifeCycle() { return myProxyLifeCycle; } public AiravataRegistry getRegistry() { return registry; } public String getTrustedCertLocation() { return trustedCertLocation; } }
8,966
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/JobContext.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.core.gfac.context; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.schemas.gfac.Parameter; import java.util.Map; public class JobContext { private Map<Parameter,ActualParameter> parameters; private String topic; private String serviceName; private String brokerURL; public JobContext(Map<Parameter, ActualParameter> parameters, String topic, String serviceName,String brokerURL) { this.parameters = parameters; this.topic = topic; this.serviceName = serviceName; this.brokerURL = brokerURL; } public Map<Parameter, ActualParameter> getParameters() { return parameters; } public String getTopic() { return topic; } public String getServiceName() { return serviceName; } public String getBrokerURL() { return brokerURL; } public void setBrokerURL(String brokerURL) { this.brokerURL = brokerURL; } }
8,967
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/invocation/InvocationContext.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.core.gfac.context.invocation; import org.apache.airavata.core.gfac.context.message.MessageContext; import org.apache.airavata.core.gfac.context.security.SecurityContext; /** * InvocationContext is the main context contains other contexts. It is used (per invocation) as a parameter to pass to * all modules in the Gfac service. * */ public interface InvocationContext { /** * Get ServiceName for the invocation * * @return */ String getServiceName(); /** * Get input. Use to handle specific MessageContext for input * * @return MessageContext contains input */ <T> MessageContext<T> getInput(); /** * Set MessageContext as input * * @param value */ void setInput(MessageContext<?> value); /** * Get output. Use to handle specific MessageContext for output * * @return MessageContext contains output */ <T> MessageContext<T> getOutput(); /** * Set MessageContext as output * * @param value */ void setOutput(MessageContext<?> value); /** * Get ExecutionDescription * * @return ExecutionDescription */ ExecutionDescription getExecutionDescription(); /** * Set ExecutionDescription * * @param value */ void setExecutionDescription(ExecutionDescription value); /** * Get ExecutionContext * * @return ExecutionContext */ ExecutionContext getExecutionContext(); /** * Set ExecutionContext * * @param value */ void setExecutionContext(ExecutionContext value); /** * Get MessageContext * * @param name * @return MessageContext */ <T> MessageContext<T> getMessageContext(String name); /** * Add MessageContext to the invocation with specific name. * * @param name * @param value */ void addMessageContext(String name, MessageContext<?> value); /** * Get SecurityContext * * @param name * @return */ SecurityContext getSecurityContext(String name); /** * Add SecurityContext to the invocation with specific name. * * @param name * @param value */ void addSecurityContext(String name, SecurityContext value); }
8,968
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/invocation/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.core.gfac.context.invocation; import org.apache.airavata.core.gfac.notification.GFacNotifiable; import org.apache.airavata.core.gfac.notification.GFacNotifier; import org.apache.airavata.registry.api.AiravataRegistry; import org.apache.axiom.om.OMElement; import xsul.lead.LeadContextHeader; /** * The Execution Context is used for passing information around the whole service. It keeps information about general * execution step. For example, notification service, registry service. * */ public interface ExecutionContext { /** * Get Notifier object to used for notification. * * @return NotificationService to be used. */ GFacNotifier getNotifier(); /** * add Notifiable object. * * @param Notifiable * object to used */ void addNotifiable(GFacNotifiable value); /** * Get Registry object. It is used to retrieve important information about application execution. * * @return Registry object */ AiravataRegistry getRegistryService(); /** * Set Registry object. * * @param AiravataRegistry * object to used. */ void setRegistryService(AiravataRegistry value); public OMElement getSecurityContextHeader(); public void setSecurityContextHeader(OMElement header); }
8,969
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/invocation/ExecutionDescription.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.core.gfac.context.invocation; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; /** * ExecutionDescription represents an application description which is used to determine how to invoke an application. * For example, host where an application is deployed, service name, service parameters, etc. * */ public interface ExecutionDescription { /** * Get HostDescription * * @return HostDescription */ HostDescription getHost(); /** * Set HostDescription * * @param host */ <T extends HostDescription> void setHost(T host); /** * Get ApplicationDeploymentDescription * * @return ApplicationDeploymentDescription */ ApplicationDeploymentDescription getApp(); /** * Set ApplicationDeploymentDescription * * @param app */ <T extends ApplicationDeploymentDescription> void setApp(T app); /** * Get ServiceDescription * * @return service */ ServiceDescription getService(); /** * Set ServiceDescription * * @param service */ <T extends ServiceDescription> void setService(T service); }
8,970
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/invocation
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/invocation/impl/DefaultExecutionDescription.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.core.gfac.context.invocation.impl; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.core.gfac.context.invocation.ExecutionDescription; /** * This class provides access to the Host, Application Deployment, and Service descriptions, which are XML<->JavaBean * serializations. */ public class DefaultExecutionDescription implements ExecutionDescription { private HostDescription host; private ApplicationDeploymentDescription app; private ServiceDescription service; public HostDescription getHost() { return host; } public void setHost(HostDescription host) { this.host = host; } public ApplicationDeploymentDescription getApp() { return app; } public void setApp(ApplicationDeploymentDescription app) { this.app = app; } public ServiceDescription getService() { return service; } public void setService(ServiceDescription service) { this.service = service; } }
8,971
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/invocation
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/invocation/impl/DefaultInvocationContext.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.core.gfac.context.invocation.impl; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.apache.airavata.core.gfac.context.invocation.ExecutionContext; import org.apache.airavata.core.gfac.context.invocation.ExecutionDescription; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.context.message.MessageContext; import org.apache.airavata.core.gfac.context.security.SecurityContext; /** * Main context that is used throughout the service */ public class DefaultInvocationContext implements InvocationContext { protected final String MESSAGE_CONTEXT_INPUT = "input"; protected final String MESSAGE_CONTEXT_OUTPUT = "output"; private String serviceName; private ExecutionContext executionContext; private ExecutionDescription gfacContext; private Map<String, MessageContext<?>> messageContextMap = new LinkedHashMap<String, MessageContext<?>>(); private Map<String, SecurityContext> securityContextMap = new LinkedHashMap<String, SecurityContext>(); public void setServiceName(String name) { this.serviceName = name; } public String getServiceName() { return this.serviceName; } public ExecutionDescription getExecutionDescription() { return this.gfacContext; } public void setExecutionDescription(ExecutionDescription value) { this.gfacContext = value; } public ExecutionContext getExecutionContext() { return this.executionContext; } public void setExecutionContext(ExecutionContext value) { this.executionContext = value; } public <T> MessageContext<T> getMessageContext(String name) { return (MessageContext<T>) this.messageContextMap.get(name); } public SecurityContext getSecurityContext(String name) { return this.securityContextMap.get(name); } public void addMessageContext(String name, MessageContext<?> value) { this.messageContextMap.put(name, value); } public void addSecurityContext(String name, SecurityContext value) { this.securityContextMap.put(name, value); } public <T> MessageContext<T> getInput() { return getMessageContext(MESSAGE_CONTEXT_INPUT); } public void setInput(MessageContext<?> value) { this.messageContextMap.put(MESSAGE_CONTEXT_INPUT, value); } public <T> MessageContext<T> getOutput() { return getMessageContext(MESSAGE_CONTEXT_OUTPUT); } public void setOutput(MessageContext<?> value) { this.messageContextMap.put(MESSAGE_CONTEXT_OUTPUT, value); }; }
8,972
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/invocation
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/invocation/impl/DefaultExecutionContext.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.core.gfac.context.invocation.impl; import org.apache.airavata.core.gfac.context.invocation.ExecutionContext; import org.apache.airavata.core.gfac.notification.GFacNotifiable; import org.apache.airavata.core.gfac.notification.GFacNotifier; import org.apache.airavata.core.gfac.notification.impl.DefaultNotifier; import org.apache.airavata.registry.api.AiravataRegistry; import org.apache.axiom.om.OMElement; /** * DefaultExecutionContext is a simple implementation of ExecutionContext. It uses DefaultNotifier as its base notifier. * */ public class DefaultExecutionContext implements ExecutionContext { private GFacNotifier notificationService = new DefaultNotifier(); private AiravataRegistry registryService; private OMElement header; public GFacNotifier getNotifier() { return this.notificationService; } public void addNotifiable(GFacNotifiable service) { this.notificationService.addNotifiable(service); } public AiravataRegistry getRegistryService() { return this.registryService; } public void setRegistryService(AiravataRegistry registryService) { this.registryService = registryService; } public OMElement getSecurityContextHeader() { return header; } public void setSecurityContextHeader(OMElement header) { this.header = header; } }
8,973
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/security/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.core.gfac.context.security; /** * SecurityContext is the representation of security object used by providers. * */ public interface SecurityContext { }
8,974
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/security
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/security/impl/SSHSecurityContextImpl.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.core.gfac.context.security.impl; import org.apache.airavata.core.gfac.context.security.SecurityContext; public class SSHSecurityContextImpl implements SecurityContext { private String username; private String privateKeyLoc; private String keyPass; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPrivateKeyLoc() { return privateKeyLoc; } public void setPrivateKeyLoc(String privateKeyLoc) { this.privateKeyLoc = privateKeyLoc; } public String getKeyPass() { return keyPass; } public void setKeyPass(String keyPass) { this.keyPass = keyPass; } }
8,975
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/security
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/security/impl/GSISecurityContext.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.core.gfac.context.security.impl; import org.apache.airavata.core.gfac.context.security.SecurityContext; import org.apache.airavata.core.gfac.context.security.impl.utils.MyProxyManager; import org.apache.airavata.core.gfac.exception.SecurityException; import org.globus.tools.MyProxy; import org.ietf.jgss.GSSCredential; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GSISecurityContext implements SecurityContext { protected final Logger log = LoggerFactory.getLogger(this.getClass()); private MyProxyManager proxyRenewer; private String myproxyUserName; private String myproxyPasswd; private String myproxyServer; private int myproxyLifetime; private String trustedCertLoc; private GSSCredential gssCredentails; public GSISecurityContext() { } public GSSCredential getGssCredentails() throws SecurityException { try { System.out.println(gssCredentails); if (gssCredentails == null || gssCredentails.getRemainingLifetime() < 10 * 90) { if (proxyRenewer != null) { gssCredentails = proxyRenewer.renewProxy(); } else if (myproxyUserName != null && myproxyPasswd != null && myproxyServer != null) { this.proxyRenewer = new MyProxyManager(myproxyUserName, myproxyPasswd, MyProxy.MYPROXY_SERVER_PORT, myproxyLifetime, myproxyServer,trustedCertLoc); log.info("loaded credentails from Proxy server"); gssCredentails = this.proxyRenewer.renewProxy(); } } return gssCredentails; } catch (Exception e) { throw new SecurityException(e.getMessage(), e); } } public String getTrustedCertLoc() { return trustedCertLoc; } public void setTrustedCertLoc(String trustedCertLoc) { this.trustedCertLoc = trustedCertLoc; } public String getMyproxyUserName() { return myproxyUserName; } public void setMyproxyUserName(String myproxyUserName) { this.myproxyUserName = myproxyUserName; } public String getMyproxyPasswd() { return myproxyPasswd; } public void setMyproxyPasswd(String myproxyPasswd) { this.myproxyPasswd = myproxyPasswd; } public String getMyproxyServer() { return myproxyServer; } public void setMyproxyServer(String myproxyServer) { this.myproxyServer = myproxyServer; } public int getMyproxyLifetime() { return myproxyLifetime; } public void setMyproxyLifetime(int myproxyLifetime) { this.myproxyLifetime = myproxyLifetime; } }
8,976
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/security
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/security/impl/AmazonSecurityContext.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.core.gfac.context.security.impl; import org.apache.airavata.core.gfac.context.security.SecurityContext; public class AmazonSecurityContext implements SecurityContext { private String accessKey; private String secretKey; public String getAccessKey() { return accessKey; } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public String getSecretKey() { return secretKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } }
8,977
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/security/impl
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/security/impl/utils/MyProxyManager.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.core.gfac.context.security.impl.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.UUID; import org.globus.gsi.GlobusCredential; import org.globus.gsi.TrustedCertificates; import org.globus.gsi.gssapi.GlobusGSSCredentialImpl; import org.globus.myproxy.MyProxy; import org.globus.myproxy.MyProxyException; import org.ietf.jgss.GSSCredential; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyProxyManager { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final String username; private final String password; private final int port; private final int lifetime; private final String hostname; private String trustedCertsLoc; public MyProxyManager(final String username, final String password, final int port, final int lifetime, final String hostname) { this.username = username; this.password = password; this.port = port; this.lifetime = lifetime; this.hostname = hostname; } public MyProxyManager(final String username, final String password, final int port, final int lifetime, final String hostname, String trustedCertsLoc) { this.username = username; this.password = password; this.port = port; this.lifetime = lifetime; this.hostname = hostname; this.trustedCertsLoc = trustedCertsLoc; } private void init() { if (trustedCertsLoc != null) { TrustedCertificates certificates = TrustedCertificates.load(trustedCertsLoc); TrustedCertificates.setDefaultTrustedCertificates(certificates); } } public GSSCredential renewProxy() throws MyProxyException, IOException { init(); String proxyloc = null; MyProxy myproxy = new MyProxy(hostname, port); GSSCredential proxy = myproxy.get(username, password, lifetime); GlobusCredential globusCred = null; if (proxy instanceof GlobusGSSCredentialImpl) { globusCred = ((GlobusGSSCredentialImpl) proxy).getGlobusCredential(); log.info("got proxy from myproxy for " + username + " with " + lifetime + " lifetime."); String uid = username; // uid = XpolaUtil.getSysUserid(); log.info("uid: " + uid); proxyloc = "/tmp/x509up_u" + uid + UUID.randomUUID().toString(); log.info("proxy location: " + proxyloc); File proxyfile = new File(proxyloc); if (!proxyfile.exists()) { String dirpath = proxyloc.substring(0, proxyloc.lastIndexOf('/')); File dir = new File(dirpath); if (!dir.exists()) { if (dir.mkdirs()) { log.info("new directory " + dirpath + " is created."); } else { log.error("error in creating directory " + dirpath); } } proxyfile.createNewFile(); log.info("new proxy file " + proxyloc + " is created."); } FileOutputStream fout = null; try { fout = new FileOutputStream(proxyfile); globusCred.save(fout); } finally { if (fout != null) { fout.close(); } } Runtime.getRuntime().exec("/bin/chmod 600 " + proxyloc); log.info("Proxy file renewed to " + proxyloc + " for the user " + username + " with " + lifetime + " lifetime."); } return proxy; } }
8,978
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/message/MessageContext.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.core.gfac.context.message; import java.util.Iterator; /** * * MessageContext represents a message that could be used by all provider or in specific provider. Mostly, this context * will be stored in the format of <key, value> pair. For example, MessageContext<AbstractParameter> represents a * message for input or output as a parameter to the service. * * @param <T> * class that associate with this message */ public interface MessageContext<T> { /** * Get list of names in the context * * @return */ public Iterator<String> getNames(); /** * Return value associated with the key * * @param name * @return value */ T getValue(String name); /** * Return value associated with the key as a String object * * @param name * @return string represents value */ String getStringValue(String name); /** * Add new object associated with the key * * @param name * @param value */ void add(String name, T value); /** * * @param name * @param value */ void remove(String name); /** * Update the current value associated with the key * * @param name * @param value */ void setValue(String name, T value); }
8,979
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/message
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/message/impl/WorkflowContextImpl.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.core.gfac.context.message.impl; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.airavata.core.gfac.context.message.MessageContext; /** * This class contains actual parameters in service invocation. */ public class WorkflowContextImpl implements MessageContext<String> { public static final String WORKFLOW_CONTEXT_NAME = "workflow_context"; public static final String WORKFLOW_ID = "workflowId"; private Map<String, String> value; public WorkflowContextImpl() { this.value = new HashMap<String, String>(); } public Iterator<String> getNames() { return this.value.keySet().iterator(); } public String getValue(String name) { return this.value.get(name); } public String getStringValue(String name) { return this.value.get(name); } public void add(String name, String value) { this.value.put(name, value); } public void setValue(String name, String value) { this.value.put(name, value); } @Override public void remove(String name) { this.value.remove(name); } }
8,980
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/message
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/context/message/impl/ParameterContextImpl.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.core.gfac.context.message.impl; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.commons.gfac.type.MappingFactory; import org.apache.airavata.core.gfac.context.message.MessageContext; /** * This class contains actual parameters in service invocation. */ public class ParameterContextImpl implements MessageContext<ActualParameter> { private Map<String, ActualParameter> value; public ParameterContextImpl() { this.value = new LinkedHashMap<String, ActualParameter>(); } public Iterator<String> getNames() { return this.value.keySet().iterator(); } public ActualParameter getValue(String name) { return this.value.get(name); } public String getStringValue(String name) { if (this.value.containsKey(name)) return MappingFactory.toString(this.value.get(name)); else return null; } public void add(String name, ActualParameter value) { this.value.put(name, value); } public void remove(String name) { this.value.remove(name); } public void setValue(String name, ActualParameter value) { this.value.put(name, value); } }
8,981
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension/PostExecuteChain.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.core.gfac.extension; import org.apache.airavata.core.gfac.provider.Provider; /** * The data service chain is a plugin which will be executed after {@link Provider} execution */ public abstract class PostExecuteChain extends ExitableChain { }
8,982
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension/DataServiceChain.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.core.gfac.extension; import org.apache.airavata.core.gfac.provider.Provider; /** * The data service chain is a plugin which will be executed before {@link Provider} initialization */ public abstract class DataServiceChain extends ExitableChain { }
8,983
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension/Chain.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.core.gfac.extension; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.exception.ExtensionException; /** * Class implements the Chain of Responsibility Pattern */ public abstract class Chain<T> { private T next; /** * Set the next item in the chain * * @param nextChain * @return the next item */ public T setNext(T nextChain) { this.next = nextChain; return this.next; } /** * Get the next item in the Chain * * @return next items */ protected T getNext() { return next; } /** * Start the chain * * @param context * @throws ExtensionException */ public abstract void start(InvocationContext context) throws ExtensionException; }
8,984
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension/PreExecuteChain.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.core.gfac.extension; import org.apache.airavata.core.gfac.provider.Provider; /** * The data service chain is a plugin which will be executed before {@link Provider} execution */ public abstract class PreExecuteChain extends ExitableChain { }
8,985
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension/ExitableChain.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.core.gfac.extension; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.exception.ExtensionException; /** * The implementation of Chain of Responsibility with twist. The item in the chain can stop the process by return * <code>true</code> from execution method. * */ public abstract class ExitableChain extends Chain<ExitableChain> { public final void start(InvocationContext context) throws ExtensionException { boolean breakTheChain = this.execute(context); if (getNext() != null && !breakTheChain) { this.getNext().start(context); } } /** * Execution method to be called for each item * * @param context * @return true if no need for further processing * @throws ExtensionException */ protected abstract boolean execute(InvocationContext context) throws ExtensionException; }
8,986
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension/post/GridFtpOutputStaging.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.core.gfac.extension.post; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.Iterator; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.context.message.MessageContext; import org.apache.airavata.core.gfac.context.security.impl.GSISecurityContext; import org.apache.airavata.core.gfac.exception.ExtensionException; import org.apache.airavata.core.gfac.exception.SecurityException; import org.apache.airavata.core.gfac.exception.ToolsException; import org.apache.airavata.core.gfac.extension.PostExecuteChain; import org.apache.airavata.core.gfac.external.GridFtp; import org.apache.airavata.core.gfac.utils.GfacUtils; import org.apache.airavata.schemas.gfac.ApplicationDeploymentDescriptionType; import org.apache.airavata.schemas.gfac.DataType; import org.apache.airavata.schemas.gfac.FileParameterType; import org.apache.airavata.schemas.gfac.GlobusHostType; import org.apache.airavata.schemas.gfac.HostDescriptionType; import org.ietf.jgss.GSSCredential; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Output plugin to transfer file from GridFTP host to location given in output parameter */ public class GridFtpOutputStaging extends PostExecuteChain { public static final Logger log = LoggerFactory.getLogger(GridFtpOutputStaging.class); public static final String MYPROXY_SECURITY_CONTEXT = "myproxy"; public boolean execute(InvocationContext context) throws ExtensionException { try { MessageContext<ActualParameter> outputContext = context.getOutput(); if (outputContext != null) { for (Iterator<String> iterator = outputContext.getNames(); iterator.hasNext();) { String key = iterator.next(); if (outputContext.getValue(key).hasType(DataType.FILE)) { FileParameterType fileParameter = (FileParameterType) outputContext.getValue(key).getType(); /* * Determine scheme */ URI uri = URI.create(fileParameter.getValue()); if (uri.getScheme().equalsIgnoreCase(GridFtp.GSIFTP_SCHEME)) { /* * src complete URI */ File file = new File(uri.getPath()); String srcFilePath = file.getName(); ApplicationDeploymentDescriptionType app = context.getExecutionDescription().getApp() .getType(); srcFilePath = app.getOutputDataDirectory() + File.separator + srcFilePath; HostDescriptionType hostDescription = context.getExecutionDescription().getHost().getType(); if (hostDescription instanceof GlobusHostType) { gridFTPTransfer(context, uri, srcFilePath); } else if (GfacUtils.isLocalHost(hostDescription.getHostAddress())) { uploadFile(context, uri, srcFilePath); } } } } } else { log.debug("Output Context is null"); } } catch (UnknownHostException e) { throw new ExtensionException("Cannot find IP Address for current host", e); } catch (URISyntaxException e) { throw new ExtensionException("URI is in the wrong format:" + e.getMessage(), e); } catch (ToolsException e) { throw new ExtensionException(e.getMessage(), e); } catch (SecurityException e) { throw new ExtensionException(e.getMessage(), e); } return false; } private void gridFTPTransfer(InvocationContext context, URI dest, String remoteSrcFile) throws SecurityException, ToolsException, URISyntaxException { GridFtp ftp = new GridFtp(); GSSCredential gssCred = ((GSISecurityContext) context.getSecurityContext(MYPROXY_SECURITY_CONTEXT)) .getGssCredentails(); GlobusHostType host = (GlobusHostType) context.getExecutionDescription().getHost().getType(); for (String endpoint : host.getGridFTPEndPointArray()) { try { URI srcURI = GfacUtils.createGsiftpURI(endpoint, remoteSrcFile); ftp.transfer(srcURI, dest, gssCred, true); return; } catch (ToolsException e) { log.error(e.getMessage(), e); } } } private void uploadFile(InvocationContext context, URI dest, String localFile) throws SecurityException, ToolsException { GridFtp ftp = new GridFtp(); GSSCredential gssCred = ((GSISecurityContext) context.getSecurityContext(MYPROXY_SECURITY_CONTEXT)) .getGssCredentails(); ftp.uploadFile(dest, gssCred, new File(localFile)); } }
8,987
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension/post/OutputRegister.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.core.gfac.extension.post; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.airavata.common.registry.api.exception.RegistryException; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.context.message.MessageContext; import org.apache.airavata.core.gfac.context.message.impl.WorkflowContextImpl; import org.apache.airavata.core.gfac.exception.ExtensionException; import org.apache.airavata.core.gfac.extension.PostExecuteChain; import org.apache.airavata.registry.api.DataRegistry; import org.apache.airavata.registry.api.AiravataRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Register output to Registry */ public class OutputRegister extends PostExecuteChain { private static final Logger log = LoggerFactory.getLogger(OutputRegister.class); public boolean execute(InvocationContext context) throws ExtensionException { // output context MessageContext<ActualParameter> outputContext = context.getOutput(); // workflow context MessageContext<String> workflowContext = context.getMessageContext(WorkflowContextImpl.WORKFLOW_CONTEXT_NAME); // registry AiravataRegistry registry = context.getExecutionContext().getRegistryService(); if (outputContext != null && workflowContext != null) { String workflowId = workflowContext.getValue(WorkflowContextImpl.WORKFLOW_ID); List<ActualParameter> outputs = new ArrayList<ActualParameter>(); for (Iterator<String> iterator = outputContext.getNames(); iterator.hasNext();) { String key = iterator.next(); outputs.add(outputContext.getValue(key)); } if (registry != null && DataRegistry.class.isAssignableFrom(registry.getClass())) { try { ((DataRegistry) registry).saveOutput(workflowId, outputs); } catch (RegistryException e) { log.error(e.getLocalizedMessage(), e); } } else { log.debug("Registry does not support for Data Catalog, CLass: " + registry.getClass()); } } else { log.debug("Context is null"); } return false; } }
8,988
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension/pre/GridFtpInputStaging.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.core.gfac.extension.pre; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.Iterator; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.context.message.MessageContext; import org.apache.airavata.core.gfac.context.security.impl.GSISecurityContext; import org.apache.airavata.core.gfac.exception.ExtensionException; import org.apache.airavata.core.gfac.exception.SecurityException; import org.apache.airavata.core.gfac.exception.ToolsException; import org.apache.airavata.core.gfac.extension.PreExecuteChain; import org.apache.airavata.core.gfac.external.GridFtp; import org.apache.airavata.core.gfac.utils.GfacUtils; import org.apache.airavata.schemas.gfac.ApplicationDeploymentDescriptionType; import org.apache.airavata.schemas.gfac.DataType; import org.apache.airavata.schemas.gfac.FileParameterType; import org.apache.airavata.schemas.gfac.GlobusHostType; import org.apache.airavata.schemas.gfac.HostDescriptionType; import org.ietf.jgss.GSSCredential; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Input plugin to transfer file from GridFTP host to target GridFTP host */ public class GridFtpInputStaging extends PreExecuteChain { public static final Logger log = LoggerFactory.getLogger(GridFtpInputStaging.class); public static final String MYPROXY_SECURITY_CONTEXT = "myproxy"; public boolean execute(InvocationContext context) throws ExtensionException { try { MessageContext<ActualParameter> inputContext = context.getInput(); if (inputContext != null) { for (Iterator<String> iterator = inputContext.getNames(); iterator.hasNext();) { String key = iterator.next(); if (inputContext.getValue(key).hasType(DataType.FILE)) { FileParameterType fileParameter = (FileParameterType) inputContext.getValue(key).getType(); /* * Determine scheme */ URI uri = URI.create(fileParameter.getValue()); if (uri.getScheme().equalsIgnoreCase(GridFtp.GSIFTP_SCHEME)) { /* * Destination complete URI */ File file = new File(uri.getPath()); String destFilePath = file.getName(); ApplicationDeploymentDescriptionType app = context.getExecutionDescription().getApp().getType(); destFilePath = app.getInputDataDirectory() + File.separator + destFilePath; HostDescriptionType hostDescription = context.getExecutionDescription().getHost().getType(); if (hostDescription instanceof GlobusHostType) { gridFTPTransfer(context, uri, destFilePath); } else if (GfacUtils.isLocalHost(hostDescription.getHostAddress())) { downloadFile(context, uri, destFilePath); } /* * Replace parameter */ fileParameter.setValue(destFilePath); } } } } else { log.debug("Input Context is null"); } } catch (UnknownHostException e) { throw new ExtensionException("Cannot find IP Address for current host", e); } catch (URISyntaxException e) { throw new ExtensionException("URI is in the wrong format:" + e.getMessage(), e); } catch (ToolsException e) { throw new ExtensionException(e.getMessage(), e); } catch (SecurityException e) { throw new ExtensionException(e.getMessage(), e); } return false; } private void gridFTPTransfer(InvocationContext context, URI src, String remoteFile) throws SecurityException, ToolsException, URISyntaxException { GridFtp ftp = new GridFtp(); GSSCredential gssCred = ((GSISecurityContext) context.getSecurityContext(MYPROXY_SECURITY_CONTEXT)) .getGssCredentails(); GlobusHostType host = (GlobusHostType) context.getExecutionDescription().getHost().getType(); for (String endpoint : host.getGridFTPEndPointArray()) { try { URI inputURI = GfacUtils.createGsiftpURI(endpoint, remoteFile); ftp.transfer(src, inputURI, gssCred, true); return; } catch (ToolsException e) { log.error(e.getMessage(), e); } } } private void downloadFile(InvocationContext context, URI src, String localFile) throws SecurityException, ToolsException { GridFtp ftp = new GridFtp(); GSSCredential gssCred = ((GSISecurityContext) context.getSecurityContext(MYPROXY_SECURITY_CONTEXT)) .getGssCredentails(); ftp.downloadFile(src, gssCred, new File(localFile)); } }
8,989
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension/pre/HttpInputStaging.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.core.gfac.extension.pre; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Iterator; import org.apache.airavata.commons.gfac.type.ActualParameter; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.context.message.MessageContext; import org.apache.airavata.core.gfac.context.security.impl.GSISecurityContext; import org.apache.airavata.core.gfac.exception.ExtensionException; import org.apache.airavata.core.gfac.exception.SecurityException; import org.apache.airavata.core.gfac.exception.ToolsException; import org.apache.airavata.core.gfac.extension.PreExecuteChain; import org.apache.airavata.core.gfac.external.GridFtp; import org.apache.airavata.core.gfac.utils.GfacUtils; import org.apache.airavata.schemas.gfac.ApplicationDeploymentDescriptionType; import org.apache.airavata.schemas.gfac.DataType; import org.apache.airavata.schemas.gfac.FileParameterType; import org.apache.airavata.schemas.gfac.GlobusHostType; import org.apache.airavata.schemas.gfac.HostDescriptionType; import org.ietf.jgss.GSSCredential; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Input plugin to transfer file from Http location to target GridFTP host */ public class HttpInputStaging extends PreExecuteChain { public static final Logger log = LoggerFactory.getLogger(HttpInputStaging.class); public static final String MYPROXY_SECURITY_CONTEXT = "myproxy"; public boolean execute(InvocationContext context) throws ExtensionException { try { MessageContext<ActualParameter> inputContext = context.getInput(); if (inputContext != null) { for (Iterator<String> iterator = inputContext.getNames(); iterator.hasNext();) { String key = iterator.next(); if (inputContext.getValue(key).hasType(DataType.FILE)) { FileParameterType fileParameter = (FileParameterType) inputContext.getValue(key).getType(); /* * Determine scheme */ URI uri = URI.create(fileParameter.getValue()); if (uri.getScheme().equalsIgnoreCase("http")) { /* * Desctination complete URI */ File file = new File(uri.getPath()); String destFilePath = file.getName(); ApplicationDeploymentDescriptionType app = context.getExecutionDescription().getApp().getType(); destFilePath = app.getInputDataDirectory() + File.separator + destFilePath; HostDescriptionType hostDescription = context.getExecutionDescription().getHost().getType(); if (hostDescription instanceof GlobusHostType) { uploadToGridFTPFromHttp(context, uri, destFilePath); } else { downloadFile(context, uri, destFilePath); } /* * Replace parameter */ fileParameter.setValue(destFilePath); } } } } else { log.debug("Input Context is null"); } } catch (SecurityException e) { throw new ExtensionException(e.getMessage(), e); } catch (ToolsException e) { throw new ExtensionException(e.getMessage(), e); } catch (URISyntaxException e) { throw new ExtensionException("URI is in the wrong format:" + e.getMessage(), e); } catch (IOException e) { throw new ExtensionException("Cannot load from HTTP", e); } return false; } private void uploadToGridFTPFromHttp(InvocationContext context, URI src, String remoteLocation) throws SecurityException, ToolsException, URISyntaxException, IOException { GridFtp ftp = new GridFtp(); GSSCredential gssCred = ((GSISecurityContext) context.getSecurityContext(MYPROXY_SECURITY_CONTEXT)) .getGssCredentails(); GlobusHostType host = (GlobusHostType) context.getExecutionDescription().getHost().getType(); for (String endpoint : host.getGridFTPEndPointArray()) { try { URI destURI = GfacUtils.createGsiftpURI(endpoint, remoteLocation); InputStream in = null; try { in = src.toURL().openStream(); ftp.uploadFile(destURI, gssCred, in); } finally { try { if (in != null) { in.close(); } } catch (Exception e) { log.warn("Cannot close URL inputstream"); } } return; } catch (ToolsException e) { log.error(e.getMessage(), e); } } } private void downloadFile(InvocationContext context, URI src, String localFile) throws IOException { OutputStream out = null; InputStream in = null; try { /* * Open an output stream to the destination file on our local filesystem */ in = src.toURL().openStream(); out = new BufferedOutputStream(new FileOutputStream(localFile)); // Get the data byte[] buffer = new byte[1024]; int numRead; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); } out.flush(); } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { log.warn("Cannot close URL inputstream"); } } if (out != null) { try { out.close(); } catch (IOException ioe) { log.warn("Cannot close URL outputstream"); } } } } }
8,990
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/extension/data/RegistryDataService.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.core.gfac.extension.data; import java.io.File; import java.util.Date; import java.util.UUID; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.exception.ExtensionException; import org.apache.airavata.core.gfac.extension.DataServiceChain; import org.apache.airavata.schemas.gfac.ApplicationDeploymentDescriptionType; /** * This plugin fills out all information that is missing in {@link ApplicationDeploymentDescription} based on Unix * system. For instance, it will use "/tmp" as default temporary directory. * */ public class RegistryDataService extends DataServiceChain { public boolean execute(InvocationContext context) throws ExtensionException { ServiceDescription serviceDesc = context.getExecutionDescription().getService(); HostDescription hostDesc = context.getExecutionDescription().getHost(); ApplicationDeploymentDescriptionType appDesc = context.getExecutionDescription().getApp().getType(); if (serviceDesc != null && hostDesc != null && appDesc != null) { /* * if there is no setting in deployment description, use from host */ if (appDesc.getScratchWorkingDirectory() == null) { appDesc.setScratchWorkingDirectory("/tmp"); } /* * Working dir */ if (appDesc.getStaticWorkingDirectory() == null || "null".equals(appDesc.getStaticWorkingDirectory())) { String date = new Date().toString(); date = date.replaceAll(" ", "_"); date = date.replaceAll(":", "_"); String tmpDir = appDesc.getScratchWorkingDirectory() + File.separator + appDesc.getApplicationName().getStringValue() + "_" + date + "_" + UUID.randomUUID(); appDesc.setStaticWorkingDirectory(tmpDir); } /* * Input and Output Directory */ if (appDesc.getInputDataDirectory() == null || "".equals(appDesc.getInputDataDirectory()) ) { appDesc.setInputDataDirectory(appDesc.getStaticWorkingDirectory() + File.separator + "inputData"); } if (appDesc.getOutputDataDirectory() == null || "".equals(appDesc.getOutputDataDirectory())) { appDesc.setOutputDataDirectory(appDesc.getStaticWorkingDirectory() + File.separator + "outputData"); } /* * Stdout and Stderr for Shell */ if (appDesc.getStandardOutput() == null || "".equals(appDesc.getStandardOutput())) { appDesc.setStandardOutput(appDesc.getStaticWorkingDirectory() + File.separator + appDesc.getApplicationName().getStringValue() + ".stdout"); } if (appDesc.getStandardError() == null || "".equals(appDesc.getStandardError())) { appDesc.setStandardError(appDesc.getStaticWorkingDirectory() + File.separator + appDesc.getApplicationName().getStringValue() + ".stderr"); } } else { throw new ExtensionException("Service Map for " + context.getServiceName() + " does not found on resource Catalog " + context.getExecutionContext().getRegistryService()); } return false; } }
8,991
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/notification/Subject.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.core.gfac.notification; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; /** * This class represents a topic or subject that can be notified from {@link GFacNotifier} to {@link GFacNotifiable}. * * TODO: Think about a better way */ public interface Subject { /* * */ void startSchedule(InvocationContext context); void finishSchedule(InvocationContext context); /* * */ void input(InvocationContext context, String... data); void output(InvocationContext context, String... data); /* * */ void startExecution(InvocationContext context); void applicationInfo(InvocationContext context, String... data); void finishExecution(InvocationContext context); void statusChanged(InvocationContext context, String... data); void executionFail(InvocationContext context, Exception e, String... data); /* * Interface for developer to use */ void debug(InvocationContext context, String... data); void info(InvocationContext context, String... data); void warning(InvocationContext context, String... data); void exception(InvocationContext context, String... data); }
8,992
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/notification/GFacNotifiable.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.core.gfac.notification; /** * Object that will be notified */ public interface GFacNotifiable extends Subject { }
8,993
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/notification/GFacNotifier.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.core.gfac.notification; /** * Object which sends out notification */ public interface GFacNotifier extends Subject { /** * Add {@link GFacNotifiable} object to be notified * * @param notif */ void addNotifiable(GFacNotifiable notif); /** * Get the current {@link GFacNotifiable} objects * * @return array of objects */ GFacNotifiable[] getNotifiable(); }
8,994
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/notification
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/notification/impl/WorkflowTrackingNotification.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.core.gfac.notification.impl; import java.net.URI; import java.util.Properties; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.notification.GFacNotifiable; import org.apache.airavata.workflow.tracking.Notifier; import org.apache.airavata.workflow.tracking.NotifierFactory; import org.apache.airavata.workflow.tracking.common.DurationObj; import org.apache.airavata.workflow.tracking.common.InvocationEntity; import org.apache.airavata.workflow.tracking.common.WorkflowTrackingContext; /** * Workflow Tracking notification TODO:: implement properly */ public class WorkflowTrackingNotification implements GFacNotifiable { private Notifier notifier; private String topic; private URI workflowID; private WorkflowTrackingContext context; private InvocationEntity initiator; private InvocationEntity receiver; private DurationObj duration; private org.apache.airavata.workflow.tracking.common.InvocationContext invocationContext; public WorkflowTrackingNotification(String brokerURL, String topic,String workflowNodeID,String workflowID) { this.topic = topic; this.workflowID = URI.create(this.topic); Properties props = new Properties(); this.notifier = NotifierFactory.createNotifier(); URI initiatorWorkflowID = URI.create(workflowID); URI initiatorServiceID = URI.create(topic); String initiatorWorkflowNodeID = workflowNodeID; Integer initiatorWorkflowTimeStep = null; this.context = this.notifier.createTrackingContext(props, brokerURL, initiatorWorkflowID, initiatorServiceID, initiatorWorkflowNodeID, initiatorWorkflowTimeStep); this.context.setTopic(topic); this.initiator = this.notifier.createEntity(initiatorWorkflowID, initiatorServiceID, initiatorWorkflowNodeID, initiatorWorkflowTimeStep); URI receiverWorkflowID = this.workflowID; URI receiverServiceID = this.workflowID; String receiverWorkflowNodeID = null; Integer receiverWorkflowTimeStep = null; setReceiver(this.notifier.createEntity(receiverWorkflowID, receiverServiceID, receiverWorkflowNodeID, receiverWorkflowTimeStep)); // send start workflow this.invocationContext = this.notifier.workflowInvoked(this.context, this.initiator); } public void startSchedule(InvocationContext context) { } public void finishSchedule(InvocationContext context) { } public void input(InvocationContext context, String... data) { } public void output(InvocationContext context, String... data) { } public void startExecution(InvocationContext context) { this.duration = this.notifier.computationStarted(); } public void applicationInfo(InvocationContext context, String... data) { } public void finishExecution(InvocationContext context) { this.duration = this.notifier.computationFinished(this.context, this.duration); } public void statusChanged(InvocationContext context, String... data) { this.notifier.info(this.context, data); } public void executionFail(InvocationContext context, Exception e, String... data) { this.notifier.sendingFault(this.context, this.invocationContext, data); } public void debug(InvocationContext context, String... data) { } public void info(InvocationContext context, String... data) { this.notifier.info(this.context, data); } public void warning(InvocationContext context, String... data) { } public void exception(InvocationContext context, String... data) { } public InvocationEntity getReceiver() { return receiver; } public void setReceiver(InvocationEntity receiver) { this.receiver = receiver; } }
8,995
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/notification
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/notification/impl/DefaultNotifier.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.core.gfac.notification.impl; import java.util.ArrayList; import java.util.List; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.notification.GFacNotifiable; import org.apache.airavata.core.gfac.notification.GFacNotifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The default notifier which uses {@link ArrayList} to store * {@link org.apache.airavata.core.gfac.notification.GFacNotifiable} objects. Notification method is done by a single * thread. It ignore all errors from {@link org.apache.airavata.core.gfac.notification.GFacNotifiable} object. */ public class DefaultNotifier implements GFacNotifier { private static final Logger logger = LoggerFactory.getLogger(DefaultNotifier.class); private List<GFacNotifiable> notifiableObjects = new ArrayList<GFacNotifiable>(); public void addNotifiable(GFacNotifiable notif) { notifiableObjects.add(notif); } public GFacNotifiable[] getNotifiable() { return notifiableObjects.toArray(new GFacNotifiable[] {}); } public void startSchedule(InvocationContext context) { for (GFacNotifiable notif : notifiableObjects) { try { notif.startSchedule(context); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public void finishSchedule(InvocationContext context) { for (GFacNotifiable notif : notifiableObjects) { try { notif.finishSchedule(context); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public void input(InvocationContext context, String... data) { for (GFacNotifiable notif : notifiableObjects) { try { notif.info(context, data); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public void output(InvocationContext context, String... data) { for (GFacNotifiable notif : notifiableObjects) { try { notif.output(context, data); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public void startExecution(InvocationContext context) { for (GFacNotifiable notif : notifiableObjects) { try { notif.startExecution(context); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public void applicationInfo(InvocationContext context, String... data) { for (GFacNotifiable notif : notifiableObjects) { try { notif.applicationInfo(context, data); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public void finishExecution(InvocationContext context) { for (GFacNotifiable notif : notifiableObjects) { try { notif.finishExecution(context); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public void statusChanged(InvocationContext context, String... data) { for (GFacNotifiable notif : notifiableObjects) { try { notif.statusChanged(context, data); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public void executionFail(InvocationContext context, Exception e, String... data) { for (GFacNotifiable notif : notifiableObjects) { try { notif.executionFail(context, e, data); } catch (Exception ex) { logger.error(ex.getMessage(), ex); } } } public void debug(InvocationContext context, String... data) { for (GFacNotifiable notif : notifiableObjects) { try { notif.debug(context, data); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public void info(InvocationContext context, String... data) { for (GFacNotifiable notif : notifiableObjects) { try { notif.info(context, data); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public void warning(InvocationContext context, String... data) { for (GFacNotifiable notif : notifiableObjects) { try { notif.warning(context, data); } catch (Exception e) { logger.error(e.getMessage(), e); } } } public void exception(InvocationContext context, String... data) { for (GFacNotifiable notif : notifiableObjects) { try { notif.exception(context, data); } catch (Exception e) { logger.error(e.getMessage(), e); } } } }
8,996
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/notification
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/notification/impl/LoggingNotification.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.core.gfac.notification.impl; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.notification.GFacNotifiable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link org.apache.airavata.core.gfac.notification.GFacNotifiable} object as a SLF4J logger. Log out all the message * as configured in SLF4J */ public class LoggingNotification implements GFacNotifiable { protected final Logger log = LoggerFactory.getLogger(LoggingNotification.class); public void startSchedule(InvocationContext context) { printOut(context, "Start scheduling"); } public void finishSchedule(InvocationContext context) { printOut(context, "Finish scheduling"); } public void input(InvocationContext context, String... data) { printOut(context, data); } public void output(InvocationContext context, String... data) { printOut(context, data); } public void startExecution(InvocationContext context) { printOut(context, "Start execution"); } public void applicationInfo(InvocationContext context, String... data) { printOut(context, data); } public void finishExecution(InvocationContext context) { printOut(context, "Finish execution"); } public void statusChanged(InvocationContext context, String... data) { printOut(context, data); } public void executionFail(InvocationContext context, Exception e, String... data) { printOut(context, data); } public void debug(InvocationContext context, String... data) { printOut(context, data); } public void info(InvocationContext context, String... data) { printOut(context, data); } public void warning(InvocationContext context, String... data) { printOut(context, data); } public void exception(InvocationContext context, String... data) { printOut(context, data); } private void printOut(InvocationContext context, String... data) { log.info("Notifier: " + this.getClass().toString()); if (data != null) { log.info("-----DATA-----"); for (int i = 0; i < data.length; i++) { log.info(data[i]); } log.info("-----END DATA-----"); } } }
8,997
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/notification
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/notification/impl/StandardOutNotification.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.core.gfac.notification.impl; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.notification.GFacNotifiable; /** * Print out all notification to System.out */ public class StandardOutNotification implements GFacNotifiable { public void startSchedule(InvocationContext context) { printOut(context); } public void finishSchedule(InvocationContext context) { printOut(context); } public void input(InvocationContext context, String... data) { printOut(context, data); } public void output(InvocationContext context, String... data) { printOut(context, data); } public void startExecution(InvocationContext context) { printOut(context); } public void applicationInfo(InvocationContext context, String... data) { printOut(context, data); } public void finishExecution(InvocationContext context) { printOut(context); } public void statusChanged(InvocationContext context, String... data) { printOut(context, data); } public void executionFail(InvocationContext context, Exception e, String... data) { printOut(context, data); } public void debug(InvocationContext context, String... data) { printOut(context, data); } public void info(InvocationContext context, String... data) { printOut(context, data); } public void warning(InvocationContext context, String... data) { printOut(context, data); } public void exception(InvocationContext context, String... data) { printOut(context, data); } private void printOut(InvocationContext context, String... data) { System.out.println("Notifier: " + this.getClass().toString()); if (data != null) { System.out.println("-----DATA-----"); for (int i = 0; i < data.length; i++) { System.out.println(data[i]); } System.out.println("-----END DATA-----"); } } }
8,998
0
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac
Create_ds/airavata-sandbox/gfac-refactoring/gfac-core/src/main/java/org/apache/airavata/core/gfac/provider/Provider.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.core.gfac.provider; import java.util.Map; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.core.gfac.context.invocation.InvocationContext; import org.apache.airavata.core.gfac.exception.GfacException; import org.apache.airavata.core.gfac.exception.ProviderException; /** * Main component in GFAC. It executes an application according to {@link ApplicationDeploymentDescription}. */ public interface Provider { /** * The method is used for initialization step. * * @param invocationContext * @throws ProviderException */ void initialize(InvocationContext invocationContext) throws ProviderException; /** * Execution step * * @param invocationContext * @return result of execution in Map as key and value pair * @throws ProviderException */ Map<String, ?> execute(InvocationContext invocationContext) throws ProviderException; /** * Dispose is always called whether there is an exception or not. * * @param invocationContext * @throws GfacException */ void dispose(InvocationContext invocationContext) throws GfacException; }
8,999