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/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app/HTCondorJobConfiguration.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.helix.impl.task.submission.config.app;
import org.apache.airavata.helix.impl.task.submission.config.JobManagerConfiguration;
import org.apache.airavata.helix.impl.task.submission.config.OutputParser;
import org.apache.airavata.helix.impl.task.submission.config.RawCommandInfo;
import org.apache.airavata.model.appcatalog.computeresource.JobManagerCommand;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.util.Map;
public class HTCondorJobConfiguration implements JobManagerConfiguration {
private final Map<JobManagerCommand, String> jMCommands;
private String jobDescriptionTemplateName;
private String scriptExtension;
private String installedPath;
private OutputParser parser;
public HTCondorJobConfiguration(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.jMCommands = jobManagerCommands;
}
public RawCommandInfo getCancelCommand(String jobID) {
return new RawCommandInfo(this.installedPath + jMCommands.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 + jMCommands.get(JobManagerCommand.JOB_MONITORING).trim() + " " + jobID + " -nobatch");
}
public String getScriptExtension() {
return scriptExtension;
}
public RawCommandInfo getSubmitCommand(String workingDirectory,String pbsFilePath) {
return new RawCommandInfo(this.installedPath + jMCommands.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 + jMCommands.get(JobManagerCommand.JOB_MONITORING).trim() + " -submitter " + userName);
}
@Override
public RawCommandInfo getJobIdMonitorCommand(String jobName, String userName) {
return new RawCommandInfo(this.installedPath + jMCommands.get(JobManagerCommand.JOB_MONITORING).trim() + " " + jobName + " -submitter " + userName);
}
@Override
public String getBaseCancelCommand() {
return jMCommands.get(JobManagerCommand.DELETION).trim();
}
@Override
public String getBaseMonitorCommand() {
return jMCommands.get(JobManagerCommand.JOB_MONITORING).trim();
}
@Override
public String getBaseSubmitCommand() {
return jMCommands.get(JobManagerCommand.SUBMISSION).trim();
}
@Override
public String getLivenessCheckCommand(String queueName, String partition) {
return null;
}
} | 600 |
0 | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app/parser/PBSOutputParser.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.helix.impl.task.submission.config.app.parser;
import org.apache.airavata.helix.impl.task.submission.config.OutputParser;
import org.apache.airavata.helix.impl.task.submission.config.app.JobUtil;
import org.apache.airavata.model.status.JobStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PBSOutputParser implements OutputParser {
private static final Logger log = LoggerFactory.getLogger(PBSOutputParser.class);
public String parseJobSubmission(String rawOutput) {
log.debug(rawOutput);
String jobId = rawOutput;
if (!rawOutput.isEmpty() && rawOutput.contains("\n")){
String[] split = rawOutput.split("\n");
if (split.length != 0){
jobId = split[0];
}
}
return jobId; //In PBS stdout is going to be directly the jobID
}
@Override
public boolean isJobSubmissionFailed(String rawOutput) {
return false;
}
public JobStatus parseJobStatus(String jobID, String rawOutput) {
boolean jobFount = false;
log.debug(rawOutput);
String[] info = rawOutput.split("\n");
String[] line = null;
int index = 0;
for (String anInfo : info) {
index++;
if (anInfo.contains("Job Id:")) {
if (anInfo.contains(jobID)) {
jobFount = true;
break;
}
}
}
if (jobFount) {
for (int i=index;i<info.length;i++) {
String anInfo = info[i];
if (anInfo.contains("=")) {
line = anInfo.split("=", 2);
if (line.length != 0) {
if (line[0].contains("job_state")) {
return new JobStatus(JobUtil.getJobState(line[1].replaceAll(" ", "")));
}
}
}
}
}
return null;
}
public void parseJobStatuses(String userName, Map<String, JobStatus> statusMap, String rawOutput) {
log.debug(rawOutput);
String[] info = rawOutput.split("\n");
// int lastStop = 0;
for (String jobID : statusMap.keySet()) {
String jobName = jobID.split(",")[1];
boolean found = false;
for (int i = 0; i < info.length; i++) {
if (info[i].contains(jobName.substring(0,8))) {
// now starts processing this line
log.info(info[i]);
String correctLine = info[i];
String[] columns = correctLine.split(" ");
List<String> columnList = new ArrayList<String>();
for (String s : columns) {
if (!"".equals(s)) {
columnList.add(s);
}
}
// lastStop = i + 1;
try {
statusMap.put(jobID, new JobStatus(JobUtil.getJobState(columnList.get(9))));
}catch(IndexOutOfBoundsException e) {
statusMap.put(jobID, new JobStatus(JobUtil.getJobState("U")));
}
found = true;
break;
}
}
if(!found)
log.error("Couldn't find the status of the Job with JobName: " + jobName + "Job Id: " + jobID.split(",")[0]);
}
}
@Override
public String parseJobId(String jobName, String rawOutput) throws Exception {
/* output will look like
Job Id: 2080802.gordon-fe2.local
Job_Name = A312402627
*/
String regJobId = "jobId";
Pattern pattern = Pattern.compile("(?<" + regJobId + ">[^\\s]*)\\s*.* " + jobName);
if (rawOutput != null) {
Matcher matcher = pattern.matcher(rawOutput);
if (matcher.find()) {
return matcher.group(regJobId);
} else {
log.error("No match is found for JobName");
return null;
}
} else {
log.error("Error: RawOutput shouldn't be null");
return null;
}
}
}
| 601 |
0 | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app/parser/HTCondorOutputParser.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.helix.impl.task.submission.config.app.parser;
import org.apache.airavata.helix.impl.task.submission.config.OutputParser;
import org.apache.airavata.helix.impl.task.submission.config.app.JobUtil;
import org.apache.airavata.model.status.JobState;
import org.apache.airavata.model.status.JobStatus;
import org.apache.airavata.registry.core.utils.DBConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HTCondorOutputParser implements OutputParser {
private static final Logger log = LoggerFactory.getLogger(HTCondorOutputParser.class);
public static final int JOB_NAME_OUTPUT_LENGTH = 8;
public static final String STATUS = "status";
public static final String JOBID = "jobId";
/**
* 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 {
log.info(rawOutput);
if (rawOutput != null && !rawOutput.isEmpty()) {
Pattern pattern = Pattern.compile("\\d+ job\\(s\\) submitted to cluster (?<" + JOBID + ">\\d+)");
Matcher matcher = pattern.matcher(rawOutput);
if (matcher.find()) {
return matcher.group(JOBID);
}
}
return "";
}
/**
* 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) {
Pattern pattern = Pattern.compile("failed");
Matcher matcher = pattern.matcher(rawOutput);
return matcher.find();
}
/**
* 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 {
log.info(rawOutput);
if (rawOutput != null && !rawOutput.isEmpty()) {
Pattern pattern = Pattern.compile("\\s+" + jobID + ".\\d+(?=\\s+\\S+\\s+\\S+\\s+\\S+\\s+\\S+\\s+(?<" + STATUS + ">\\w+))");
Matcher matcher = pattern.matcher(rawOutput);
if (matcher.find()) {
if (matcher.group(STATUS).equals("E")) {
log.info("parsing the job status returned : " + STATUS);
return new JobStatus(JobState.FAILED);
}
return new JobStatus(JobUtil.getJobState(matcher.group(STATUS)));
}
}
return null;
}
/**
* 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 {
log.debug(rawOutput);
String[] info = rawOutput.split("\n");
String lastString = info[info.length - 1];
if (lastString.contains("ID") || lastString.contains("OWNER")) {
log.info("There are no jobs with this username ... ");
return;
}
for (String jobID : statusMap.keySet()) {
String jobId = jobID.split(",")[0];
String ownerName = jobID.split(",")[1];
boolean found = false;
for (int i = 1; i < info.length; i++) {
if (info[i].contains(ownerName)) {
// now starts processing this line
log.info(info[i]);
String correctLine = info[i];
String[] columns = correctLine.split(" ");
List<String> columnList = new ArrayList<String>();
for (String s : columns) {
if (!"".equals(s)) {
columnList.add(s);
}
}
if ("E".equals(columnList.get(4))) {
columnList.set(4, "Er");
}
try {
statusMap.put(jobID, new JobStatus(JobState.valueOf(columnList.get(4))));
} catch (IndexOutOfBoundsException e) {
statusMap.put(jobID, new JobStatus(JobState.valueOf("U")));
}
found = true;
break;
}
}
if (!found) {
log.error("Couldn't find the status of the Job with Owner: " + ownerName + "Job Id: " + jobId);
}
}
}
@Override
public String parseJobId(String jobName, String rawOutput) throws Exception {
String regJobId = "jobId";
if (jobName == null) {
return null;
} else if(jobName.length() > JOB_NAME_OUTPUT_LENGTH) {
jobName = jobName.substring(0, JOB_NAME_OUTPUT_LENGTH);
}
Pattern pattern = Pattern.compile("(?=(?<" + regJobId + ">\\d+)\\s+\\w+\\s+" + jobName + ")"); // regex - look ahead and match
if (rawOutput != null) {
Matcher matcher = pattern.matcher(rawOutput);
if (matcher.find()) {
return matcher.group(regJobId);
} else {
log.error("No match is found for JobName");
return null;
}
} else {
log.error("Error: RawOutput shouldn't be null");
return null;
}
}
} | 602 |
0 | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app/parser/AiravataCustomCommandOutputParser.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.helix.impl.task.submission.config.app.parser;
import org.apache.airavata.helix.impl.task.submission.config.OutputParser;
import org.apache.airavata.model.status.JobStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class AiravataCustomCommandOutputParser implements OutputParser {
private static final Logger log = LoggerFactory.getLogger(AiravataCustomCommandOutputParser.class);
@Override
public String parseJobSubmission(String rawOutput) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public boolean isJobSubmissionFailed(String rawOutput) {
throw new UnsupportedOperationException();
}
@Override
public JobStatus parseJobStatus(String jobID, String rawOutput) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public void parseJobStatuses(String userName, Map<String, JobStatus> statusMap, String rawOutput) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public String parseJobId(String jobName, String rawOutput) throws Exception {
throw new UnsupportedOperationException();
}
}
| 603 |
0 | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app/parser/UGEOutputParser.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.helix.impl.task.submission.config.app.parser;
import org.apache.airavata.helix.impl.task.submission.config.OutputParser;
import org.apache.airavata.model.status.JobState;
import org.apache.airavata.model.status.JobStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UGEOutputParser implements OutputParser {
private static final Logger log = LoggerFactory.getLogger(PBSOutputParser.class);
public static final String JOB_ID = "jobId";
public String parseJobSubmission(String rawOutput) {
log.debug(rawOutput);
if (rawOutput != null && !rawOutput.isEmpty() && !isJobSubmissionFailed(rawOutput)) {
String[] info = rawOutput.split("\n");
String lastLine = info[info.length - 1];
return lastLine.split(" ")[2]; // In PBS stdout is going to be directly the jobID
} else {
return "";
}
}
@Override
public boolean isJobSubmissionFailed(String rawOutput) {
Pattern pattern = Pattern.compile("Rejecting");
Matcher matcher = pattern.matcher(rawOutput);
return matcher.find();
}
public JobStatus parseJobStatus(String jobID, String rawOutput) {
Pattern pattern = Pattern.compile("job_number:[\\s]+" + jobID);
Matcher matcher = pattern.matcher(rawOutput);
if (matcher.find()) {
return new JobStatus(JobState.QUEUED); // fixme; return correct status.
}
return new JobStatus(JobState.UNKNOWN);
}
public void parseJobStatuses(String userName, Map<String, JobStatus> statusMap, String rawOutput) {
log.debug(rawOutput);
String[] info = rawOutput.split("\n");
int lastStop = 0;
for (String jobID : statusMap.keySet()) {
for(int i=lastStop;i<info.length;i++){
if(jobID.split(",")[0].contains(info[i].split(" ")[0]) && !"".equals(info[i].split(" ")[0])){
// now starts processing this line
log.info(info[i]);
String correctLine = info[i];
String[] columns = correctLine.split(" ");
List<String> columnList = new ArrayList<String>();
for (String s : columns) {
if (!"".equals(s)) {
columnList.add(s);
}
}
lastStop = i+1;
if ("E".equals(columnList.get(4))) {
// There is another status with the same letter E other than error status
// to avoid that we make a small tweek to the job status
columnList.set(4, "Er");
}
statusMap.put(jobID, new JobStatus(JobState.valueOf(columnList.get(4))));
break;
}
}
}
}
@Override
public String parseJobId(String jobName, String rawOutput) throws Exception {
if (jobName.length() > 10) {
jobName = jobName.substring(0, 10);
}
Pattern pattern = Pattern.compile("(?<" + JOB_ID + ">\\S+)\\s+\\S+\\s+(" + jobName + ")");
Matcher matcher = pattern.matcher(rawOutput);
if (matcher.find()) {
return matcher.group(JOB_ID);
}
return null;
}
}
| 604 |
0 | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app/parser/SlurmOutputParser.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.helix.impl.task.submission.config.app.parser;
import org.apache.airavata.helix.impl.task.submission.config.OutputParser;
import org.apache.airavata.helix.impl.task.submission.config.app.JobUtil;
import org.apache.airavata.model.status.JobState;
import org.apache.airavata.model.status.JobStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SlurmOutputParser implements OutputParser {
private static final Logger log = LoggerFactory.getLogger(SlurmOutputParser.class);
public static final int JOB_NAME_OUTPUT_LENGTH = 8;
public static final String STATUS = "status";
public static final String JOBID = "jobId";
/**
* This can be used to parseSingleJob the outpu of sbatch and extrac the jobID from the content
*
* @param rawOutput
* @return
*/
public String parseJobSubmission(String rawOutput) throws Exception {
log.info(rawOutput);
Pattern pattern = Pattern.compile("Submitted batch job (?<" + JOBID + ">[^\\s]*)");
Matcher matcher = pattern.matcher(rawOutput);
if (matcher.find()) {
return matcher.group(JOBID);
}
return "";
}
@Override
public boolean isJobSubmissionFailed(String rawOutput) {
Pattern pattern = Pattern.compile("FAILED");
Matcher matcher = pattern.matcher(rawOutput);
return matcher.find();
}
public JobStatus parseJobStatus(String jobID, String rawOutput) throws Exception {
log.info(rawOutput);
Pattern pattern = Pattern.compile(jobID + "(?=\\s+\\S+\\s+\\S+\\s+\\S+\\s+(?<" + STATUS + ">\\w+))");
Matcher matcher = pattern.matcher(rawOutput);
if (matcher.find()) {
return new JobStatus(JobUtil.getJobState(matcher.group(STATUS)));
}
return null;
}
public void parseJobStatuses(String userName, Map<String, JobStatus> statusMap, String rawOutput) throws Exception {
log.debug(rawOutput);
String[] info = rawOutput.split("\n");
String lastString = info[info.length - 1];
if (lastString.contains("JOBID") || lastString.contains("PARTITION")) {
log.info("There are no jobs with this username ... ");
return;
}
// int lastStop = 0;
for (String jobID : statusMap.keySet()) {
String jobId = jobID.split(",")[0];
String jobName = jobID.split(",")[1];
boolean found = false;
for (int i = 0; i < info.length; i++) {
if (info[i].contains(jobName.substring(0, 8))) {
// now starts processing this line
log.info(info[i]);
String correctLine = info[i];
String[] columns = correctLine.split(" ");
List<String> columnList = new ArrayList<String>();
for (String s : columns) {
if (!"".equals(s)) {
columnList.add(s);
}
}
try {
statusMap.put(jobID, new JobStatus(JobState.valueOf(columnList.get(4))));
} catch (IndexOutOfBoundsException e) {
statusMap.put(jobID, new JobStatus(JobState.valueOf("U")));
}
found = true;
break;
}
}
if (!found) {
log.error("Couldn't find the status of the Job with JobName: " + jobName + "Job Id: " + jobId);
}
}
}
@Override
public String parseJobId(String jobName, String rawOutput) throws Exception {
String regJobId = "jobId";
if (jobName == null) {
return null;
} else if(jobName.length() > JOB_NAME_OUTPUT_LENGTH) {
jobName = jobName.substring(0, JOB_NAME_OUTPUT_LENGTH);
}
Pattern pattern = Pattern.compile("(?=(?<" + regJobId + ">\\d+)\\s+\\w+\\s+" + jobName + ")"); // regex - look ahead and match
if (rawOutput != null) {
Matcher matcher = pattern.matcher(rawOutput);
if (matcher.find()) {
return matcher.group(regJobId);
} else {
log.error("No match is found for JobName");
return null;
}
} else {
log.error("Error: RawOutput shouldn't be null");
return null;
}
}
}
| 605 |
0 | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app/parser/ForkOutputParser.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.helix.impl.task.submission.config.app.parser;
import org.apache.airavata.common.utils.AiravataUtils;
import org.apache.airavata.helix.impl.task.submission.config.OutputParser;
import org.apache.airavata.model.status.JobStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class ForkOutputParser implements OutputParser {
private static final Logger log = LoggerFactory.getLogger(ForkOutputParser.class);
@Override
public String parseJobSubmission(String rawOutput) throws Exception {
return AiravataUtils.getId("JOB_ID_");
}
@Override
public boolean isJobSubmissionFailed(String rawOutput) {
return false;
}
@Override
public JobStatus parseJobStatus(String jobID, String rawOutput) throws Exception {
return null;
}
@Override
public void parseJobStatuses(String userName, Map<String, JobStatus> statusMap, String rawOutput) throws Exception {
}
@Override
public String parseJobId(String jobName, String rawOutput) throws Exception {
// For fork jobs there is no job ID, hence airavata generates a job ID
return AiravataUtils.getId(jobName);
}
}
| 606 |
0 | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app | Create_ds/airavata/modules/airavata-helix/helix-spectator/src/main/java/org/apache/airavata/helix/impl/task/submission/config/app/parser/LSFOutputParser.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.helix.impl.task.submission.config.app.parser;
import org.apache.airavata.helix.impl.task.submission.config.OutputParser;
import org.apache.airavata.model.status.JobState;
import org.apache.airavata.model.status.JobStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LSFOutputParser implements OutputParser {
private final static Logger logger = LoggerFactory.getLogger(LSFOutputParser.class);
@Override
public String parseJobSubmission(String rawOutput) throws Exception {
logger.debug(rawOutput);
if (rawOutput.indexOf("<") >= 0) {
return rawOutput.substring(rawOutput.indexOf("<")+1,rawOutput.indexOf(">"));
} else {
return null;
}
}
@Override
public boolean isJobSubmissionFailed(String rawOutput) {
return false;
}
@Override
public JobStatus parseJobStatus(String jobID, String rawOutput) throws Exception {
boolean jobFount = false;
logger.debug(rawOutput);
//todo this is not used anymore
return null;
}
@Override
public void parseJobStatuses(String userName, Map<String, JobStatus> statusMap, String rawOutput) throws Exception {
logger.debug(rawOutput);
String[] info = rawOutput.split("\n");
// int lastStop = 0;
for (String jobID : statusMap.keySet()) {
String jobName = jobID.split(",")[1];
boolean found = false;
for (int i = 0; i < info.length; i++) {
if (info[i].contains(jobName.substring(0,8))) {
// now starts processing this line
logger.info(info[i]);
String correctLine = info[i];
String[] columns = correctLine.split(" ");
List<String> columnList = new ArrayList<String>();
for (String s : columns) {
if (!"".equals(s)) {
columnList.add(s);
}
}
// lastStop = i + 1;
try {
statusMap.put(jobID, new JobStatus(JobState.valueOf(columnList.get(2))));
}catch(IndexOutOfBoundsException e) {
statusMap.put(jobID, new JobStatus(JobState.valueOf("U")));
}
found = true;
break;
}
}
if(!found)
logger.error("Couldn't find the status of the Job with JobName: " + jobName + "Job Id: " + jobID.split(",")[0]);
}
}
@Override
public String parseJobId(String jobName, String rawOutput) throws Exception {
String regJobId = "jobId";
Pattern pattern = Pattern.compile("(?=(?<" + regJobId + ">\\d+)\\s+\\w+\\s+" + jobName + ")"); // regex - look ahead and match
if (rawOutput != null) {
Matcher matcher = pattern.matcher(rawOutput);
if (matcher.find()) {
return matcher.group(regJobId);
} else {
logger.error("No match is found for JobName");
return null;
}
} else {
logger.error("Error: RawOutput shouldn't be null");
return null;
}
}
public static void main(String[] args) {
String test = "Job <2477982> is submitted to queue <short>.";
System.out.println(test.substring(test.indexOf("<")+1, test.indexOf(">")));
String test1 = "JOBID USER STAT QUEUE FROM_HOST EXEC_HOST JOB_NAME SUBMIT_TIME\n" +
"2636607 lg11w RUN long ghpcc06 c11b02 *069656647 Mar 7 00:58\n" +
"2636582 lg11w RUN long ghpcc06 c02b01 2134490944 Mar 7 00:48";
Map<String, JobStatus> statusMap = new HashMap<String, JobStatus>();
statusMap.put("2477983,2134490944", new JobStatus(JobState.UNKNOWN));
LSFOutputParser lsfOutputParser = new LSFOutputParser();
try {
lsfOutputParser.parseJobStatuses("cjh", statusMap, test1);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
System.out.println(statusMap.get("2477983,2134490944"));
}
}
| 607 |
0 | Create_ds/airavata/modules/airavata-helix/task-api/src/main/java/org/apache/airavata/helix/task | Create_ds/airavata/modules/airavata-helix/task-api/src/main/java/org/apache/airavata/helix/task/api/TaskParamType.java | package org.apache.airavata.helix.task.api;
public interface TaskParamType {
public String serialize();
public void deserialize(String content);
}
| 608 |
0 | Create_ds/airavata/modules/airavata-helix/task-api/src/main/java/org/apache/airavata/helix/task | Create_ds/airavata/modules/airavata-helix/task-api/src/main/java/org/apache/airavata/helix/task/api/TaskHelper.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.helix.task.api;
import org.apache.airavata.helix.task.api.support.AdaptorSupport;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface TaskHelper {
public AdaptorSupport getAdaptorSupport();
}
| 609 |
0 | Create_ds/airavata/modules/airavata-helix/task-api/src/main/java/org/apache/airavata/helix/task/api | Create_ds/airavata/modules/airavata-helix/task-api/src/main/java/org/apache/airavata/helix/task/api/annotation/TaskDef.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.helix.task.api.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TaskDef {
public String name();
}
| 610 |
0 | Create_ds/airavata/modules/airavata-helix/task-api/src/main/java/org/apache/airavata/helix/task/api | Create_ds/airavata/modules/airavata-helix/task-api/src/main/java/org/apache/airavata/helix/task/api/annotation/TaskParam.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.helix.task.api.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TaskParam {
public String name();
public String defaultValue() default "";
public boolean mandatory() default false;
}
| 611 |
0 | Create_ds/airavata/modules/airavata-helix/task-api/src/main/java/org/apache/airavata/helix/task/api | Create_ds/airavata/modules/airavata-helix/task-api/src/main/java/org/apache/airavata/helix/task/api/annotation/TaskOutPort.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.helix.task.api.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TaskOutPort {
public String name();
}
| 612 |
0 | Create_ds/airavata/modules/airavata-helix/task-api/src/main/java/org/apache/airavata/helix/task/api | Create_ds/airavata/modules/airavata-helix/task-api/src/main/java/org/apache/airavata/helix/task/api/support/AdaptorSupport.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.helix.task.api.support;
import org.apache.airavata.agents.api.*;
import org.apache.airavata.model.appcatalog.computeresource.JobSubmissionProtocol;
import org.apache.airavata.model.data.movement.DataMovementProtocol;
import java.io.File;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public interface AdaptorSupport {
public void initializeAdaptor();
public AgentAdaptor fetchAdaptor(String gatewayId, String computeResource, JobSubmissionProtocol protocol, String authToken, String userId) throws Exception;
public StorageResourceAdaptor fetchStorageAdaptor(String gatewayId, String storageResourceId, DataMovementProtocol protocol, String authToken, String userId) throws AgentException;
}
| 613 |
0 | Create_ds/airavata/modules/airavata-helix/workflow-impl/src/main/java/org/apache/airavata/helix | Create_ds/airavata/modules/airavata-helix/workflow-impl/src/main/java/org/apache/airavata/helix/workflow/QueueOperator.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.helix.workflow;
import org.apache.airavata.helix.core.AbstractTask;
import org.apache.airavata.helix.task.api.annotation.TaskDef;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.task.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* {@link QueueOperator} is responsible for handling Airavata Task Queues. Unlike in workflow, queue has the
* following properties.
* <ul>
* <li>Queue will be there until user delete it.</li>
* <li>Queue can keep accepting tasks.</li>
* <li>No parallel run allowed except intentionally configured.</li>
* </ul>
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class QueueOperator {
private final static Logger logger = LoggerFactory.getLogger(QueueOperator.class);
private static final String QUEUE_PREFIX = "Job_queue_";
private HelixManager helixManager;
private TaskDriver taskDriver;
/**
* This is the constructor for {@link QueueOperator}
*
* @param helixClusterName is the name of the Helix cluster
* @param instanceName is the name of the Helix instance
* @param zkConnectionString is the connection details for Zookeeper connection in {@code <host>:<port>} format
* @throws Exception can be thrown when connecting
*/
public QueueOperator(String helixClusterName, String instanceName, String zkConnectionString) throws Exception {
helixManager = HelixManagerFactory.getZKHelixManager(helixClusterName, instanceName,
InstanceType.SPECTATOR, zkConnectionString);
helixManager.connect();
Runtime.getRuntime().addShutdownHook(
new Thread(() -> helixManager.disconnect())
);
taskDriver = new TaskDriver(helixManager);
}
/**
* Creates a new Helix job queue and returns its name
*
* @param queueId is the identifier given for the queue
* @param monitor indicates whether monitoring is required for the queue
* @return the name of the queue that needs to be used for queue operations after creating it
* @throws InterruptedException can be thrown (if monitor enabled) when polling for workflow state
*/
public synchronized String createQueue(String queueId, boolean monitor) throws InterruptedException {
String queueName = QUEUE_PREFIX + queueId;
logger.info("Launching queue " + queueName + " for job queue " + queueId);
WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder(queueName);
workflowCfgBuilder.setFailureThreshold(0);
workflowCfgBuilder.setExpiry(0);
JobQueue.Builder jobQueueBuilder = new JobQueue.Builder(queueName).setWorkflowConfig(workflowCfgBuilder.build());
taskDriver.start(jobQueueBuilder.build());
if (monitor) {
TaskState taskState = taskDriver.pollForWorkflowState(queueName,
TaskState.COMPLETED, TaskState.FAILED, TaskState.STOPPED, TaskState.ABORTED);
logger.info("Queue " + queueName + " finished with state " + taskState.name());
}
return queueName;
}
/**
* Stops the queue. The queue is guaranteed to be stopped if this method completes without any exception.
*
* @param queueName is the name returned at {@link #createQueue(String, boolean)}
* @param timeout is the timeout to stop the queue in milliseconds
* @throws InterruptedException can be thrown when stopping the queue
*/
public synchronized void stopQueue(String queueName, int timeout) throws InterruptedException {
logger.info("Stopping queue: " + queueName + " with timeout: " + timeout);
taskDriver.waitToStop(queueName, timeout);
}
/**
* Resumes the queue if it was stopped
*
* @param queueName is the name returned at {@link #createQueue(String, boolean)}
*/
public synchronized void resumeQueue(String queueName) {
logger.info("Resuming queue: " + queueName);
taskDriver.resume(queueName);
}
/**
* Deletes the queue
*
* @param queueName is the name returned at {@link #createQueue(String, boolean)}
*/
public synchronized void deleteQueue(String queueName) {
if (taskDriver.getWorkflows().containsKey(queueName)) {
logger.info("Deleting queue: " + queueName);
taskDriver.delete(queueName);
}
logger.warn("Provided queue name: " + queueName + " is not available");
}
/**
* Removes all jobs that are in final states (ABORTED, FAILED, COMPLETED) from the job queue. The
* job config, job context will be removed from Zookeeper.
*
* @param queueName is the name returned at {@link #createQueue(String, boolean)}
*/
public synchronized void cleanupQueue(String queueName) {
logger.info("Cleaning up queue: " + queueName);
taskDriver.cleanupQueue(queueName);
}
/**
* Adds a new task to the queue
*
* @param queueName is the name returned at {@link #createQueue(String, boolean)}
* @param task {@link AbstractTask} instance which needs to added to the queue
* @param globalParticipant enable if needs to handled by the global participant
* @return the identifier of the added task
* @throws IllegalAccessException can be thrown when serializing the task
*/
public synchronized String addTaskToQueue(String queueName, AbstractTask task, boolean globalParticipant) throws IllegalAccessException {
logger.info("Adding task: " + task.getTaskId() + " to queue: " + queueName);
String taskType = task.getClass().getAnnotation(TaskDef.class).name();
TaskConfig.Builder taskBuilder = new TaskConfig.Builder().setTaskId("Task_" + task.getTaskId())
.setCommand(taskType);
Map<String, String> paramMap = org.apache.airavata.helix.core.util.TaskUtil.serializeTaskData(task);
paramMap.forEach(taskBuilder::addConfig);
List<TaskConfig> taskBuilds = new ArrayList<>();
taskBuilds.add(taskBuilder.build());
JobConfig.Builder job = new JobConfig.Builder()
.addTaskConfigs(taskBuilds)
.setFailureThreshold(0)
.setMaxAttemptsPerTask(task.getRetryCount());
if (!globalParticipant) {
job.setInstanceGroupTag(taskType);
}
taskDriver.enqueueJob(queueName, task.getTaskId(), job);
return task.getTaskId();
}
/**
* Removes a task from the queue
*
* @param queueName is the name returned at {@link #createQueue(String, boolean)}
* @param taskId is the identifier of the task to be removed
* @param timeout is the timeout to stop the queue before removing task in milliseconds
* @return the identifier of the removed task
* @throws InterruptedException can be thrown when stooping the queue before removing the task
*/
public synchronized String removeTaskFromQueue(String queueName, String taskId, int timeout) throws InterruptedException {
logger.info("Removing task: " + taskId + " from queue: " + queueName);
taskDriver.waitToStop(queueName, timeout);
taskDriver.deleteJob(queueName, taskId);
taskDriver.resume(queueName);
return taskId;
}
}
| 614 |
0 | Create_ds/airavata/modules/airavata-helix/workflow-impl/src/main/java/org/apache/airavata/helix | Create_ds/airavata/modules/airavata-helix/workflow-impl/src/main/java/org/apache/airavata/helix/workflow/WorkflowOperator.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.helix.workflow;
import org.apache.airavata.helix.core.AbstractTask;
import org.apache.airavata.helix.core.OutPort;
import org.apache.airavata.helix.core.util.TaskUtil;
import org.apache.airavata.helix.task.api.annotation.TaskDef;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.task.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class WorkflowOperator {
private final static Logger logger = LoggerFactory.getLogger(WorkflowOperator.class);
private static final String WORKFLOW_PREFIX = "Workflow_of_process_";
private static final long WORKFLOW_EXPIRY_TIME = 1 * 1000;
private static final long TASK_EXPIRY_TIME = 24 * 60 * 60 * 1000;
private TaskDriver taskDriver;
private HelixManager helixManager;
public WorkflowOperator(String helixClusterName, String instanceName, String zkConnectionString) throws Exception {
helixManager = HelixManagerFactory.getZKHelixManager(helixClusterName, instanceName,
InstanceType.SPECTATOR, zkConnectionString);
helixManager.connect();
Runtime.getRuntime().addShutdownHook(
new Thread() {
@Override
public void run() {
if (helixManager != null && helixManager.isConnected()) {
helixManager.disconnect();
}
}
}
);
taskDriver = new TaskDriver(helixManager);
}
public void disconnect() {
if (helixManager != null && helixManager.isConnected()) {
helixManager.disconnect();
}
}
public synchronized String launchWorkflow(String processId, List<AbstractTask> tasks, boolean globalParticipant, boolean monitor) throws Exception {
String workflowName = WORKFLOW_PREFIX + processId;
logger.info("Launching workflow " + workflowName + " for process " + processId);
Workflow.Builder workflowBuilder = new Workflow.Builder(workflowName).setExpiry(0);
for (int i = 0; i < tasks.size(); i++) {
AbstractTask data = tasks.get(i);
String taskType = data.getClass().getAnnotation(TaskDef.class).name();
TaskConfig.Builder taskBuilder = new TaskConfig.Builder().setTaskId("Task_" + data.getTaskId())
.setCommand(taskType);
Map<String, String> paramMap = org.apache.airavata.helix.core.util.TaskUtil.serializeTaskData(data);
paramMap.forEach(taskBuilder::addConfig);
List<TaskConfig> taskBuilds = new ArrayList<>();
taskBuilds.add(taskBuilder.build());
JobConfig.Builder job = new JobConfig.Builder()
.addTaskConfigs(taskBuilds)
.setFailureThreshold(0)
.setExpiry(WORKFLOW_EXPIRY_TIME)
.setTimeoutPerTask(TASK_EXPIRY_TIME)
.setNumConcurrentTasksPerInstance(20)
.setMaxAttemptsPerTask(data.getRetryCount());
if (!globalParticipant) {
job.setInstanceGroupTag(taskType);
}
workflowBuilder.addJob((data.getTaskId()), job);
List<OutPort> outPorts = TaskUtil.getOutPortsOfTask(data);
outPorts.forEach(outPort -> {
if (outPort != null) {
workflowBuilder.addParentChildDependency(data.getTaskId(), outPort.getNextJobId());
}
});
}
WorkflowConfig.Builder config = new WorkflowConfig.Builder().setFailureThreshold(0);
workflowBuilder.setWorkflowConfig(config.build());
workflowBuilder.setExpiry(WORKFLOW_EXPIRY_TIME);
Workflow workflow = workflowBuilder.build();
taskDriver.start(workflow);
//TODO : Do we need to monitor workflow status? If so how do we do it in a scalable manner? For example,
// if the hfac that monitors a particular workflow, got killed due to some reason, who is taking the responsibility
if (monitor) {
TaskState taskState = pollForWorkflowCompletion(workflow.getName(), 3600000);
logger.info("Workflow " + workflowName + " for process " + processId + " finished with state " + taskState.name());
}
return workflowName;
}
public synchronized TaskState pollForWorkflowCompletion(String workflowName, long timeout) throws InterruptedException {
return taskDriver.pollForWorkflowState(workflowName, timeout, TaskState.COMPLETED,
TaskState.FAILED, TaskState.STOPPED, TaskState.ABORTED);
}
public TaskState getWorkflowState(String workflow) {
return taskDriver.getWorkflowContext(workflow).getWorkflowState();
}
} | 615 |
0 | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core/AbstractTask.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.helix.core;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.helix.core.participant.HelixParticipant;
import org.apache.airavata.helix.core.util.MonitoringUtil;
import org.apache.airavata.helix.core.util.TaskUtil;
import org.apache.airavata.helix.task.api.TaskHelper;
import org.apache.airavata.helix.task.api.annotation.TaskOutPort;
import org.apache.airavata.helix.task.api.annotation.TaskParam;
import org.apache.airavata.patform.monitoring.CountMonitor;
import org.apache.airavata.patform.monitoring.GaugeMonitor;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.helix.HelixManager;
import org.apache.helix.task.Task;
import org.apache.helix.task.TaskCallbackContext;
import org.apache.helix.task.TaskResult;
import org.apache.helix.task.UserContentStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public abstract class AbstractTask extends UserContentStore implements Task {
private final static Logger logger = LoggerFactory.getLogger(AbstractTask.class);
private final static CountMonitor taskInitCounter = new CountMonitor("task_init_count");
private final static GaugeMonitor taskRunGauge = new GaugeMonitor("task_run_gauge");
private final static CountMonitor taskCancelCounter = new CountMonitor("task_cancel_count");
private final static CountMonitor taskFailCounter = new CountMonitor("task_fail_count");
private final static CountMonitor taskCompleteCounter = new CountMonitor("task_complete_count");
private static final String NEXT_JOB = "next-job";
private static final String WORKFLOW_STARTED = "workflow-started";
private static CuratorFramework curatorClient = null;
@TaskParam(name = "taskId")
private String taskId;
@TaskOutPort(name = "Next Task")
private OutPort nextTask;
private TaskCallbackContext callbackContext;
private TaskHelper taskHelper;
private HelixParticipant participant;
@TaskParam(name = "Retry Count")
private int retryCount = 3;
@Override
public void init(HelixManager manager, String workflowName, String jobName, String taskName) {
super.init(manager, workflowName, jobName, taskName);
try {
taskInitCounter.inc();
TaskUtil.deserializeTaskData(this, this.callbackContext.getTaskConfig().getConfigMap());
} catch (Exception e) {
taskFailCounter.inc();
logger.error("Deserialization of task parameters failed", e);
}
if (participant != null) {
participant.registerRunningTask(this);
} else {
logger.warn("Task with id: " + taskId + " is not registered since the participant is not set");
}
}
@Override
public final TaskResult run() {
try {
taskRunGauge.inc();
boolean isThisNextJob = getUserContent(WORKFLOW_STARTED, Scope.WORKFLOW) == null ||
this.callbackContext.getJobConfig().getJobId()
.equals(this.callbackContext.getJobConfig().getWorkflow() + "_" + getUserContent(NEXT_JOB, Scope.WORKFLOW));
return isThisNextJob ? onRun(this.taskHelper) : new TaskResult(TaskResult.Status.COMPLETED, "Not a target job");
} finally {
if (participant != null) {
participant.unregisterRunningTask(this);
} else {
logger.warn("Task with id: " + taskId + " is not unregistered since the participant is not set");
}
}
}
@Override
public final void cancel() {
try {
taskRunGauge.dec();
taskCancelCounter.inc();
logger.info("Cancelling task " + taskId);
onCancel();
} finally {
if (participant != null) {
participant.unregisterRunningTask(this);
} else {
logger.warn("Task with id: " + taskId + " is not unregistered since the participant is not set");
}
}
}
public abstract TaskResult onRun(TaskHelper helper);
public abstract void onCancel();
protected TaskResult onSuccess(String message) {
taskRunGauge.dec();
taskCompleteCounter.inc();
String successMessage = "Task " + getTaskId() + " completed." + (message != null ? " Message : " + message : "");
logger.info(successMessage);
return nextTask.invoke(new TaskResult(TaskResult.Status.COMPLETED, message));
}
protected TaskResult onFail(String reason, boolean fatal) {
taskRunGauge.dec();
taskFailCounter.inc();
return new TaskResult(fatal ? TaskResult.Status.FATAL_FAILED : TaskResult.Status.FAILED, reason);
}
protected void publishErrors(Throwable e) {
// TODO Publish through kafka channel with task and workflow id
e.printStackTrace();
}
public void sendNextJob(String jobId) {
putUserContent(WORKFLOW_STARTED, "TRUE", Scope.WORKFLOW);
if (jobId != null) {
putUserContent(NEXT_JOB, jobId, Scope.WORKFLOW);
}
}
protected void setContextVariable(String key, String value) {
putUserContent(key, value, Scope.WORKFLOW);
}
protected String getContextVariable(String key) {
return getUserContent(key, Scope.WORKFLOW);
}
// Getters and setters
public String getTaskId() {
return taskId;
}
public AbstractTask setTaskId(String taskId) {
this.taskId = taskId;
return this;
}
public TaskCallbackContext getCallbackContext() {
return callbackContext;
}
public AbstractTask setCallbackContext(TaskCallbackContext callbackContext) {
this.callbackContext = callbackContext;
return this;
}
public TaskHelper getTaskHelper() {
return taskHelper;
}
public AbstractTask setTaskHelper(TaskHelper taskHelper) {
this.taskHelper = taskHelper;
return this;
}
protected int getCurrentRetryCount() throws Exception {
return MonitoringUtil.getTaskRetryCount(getCuratorClient(), taskId);
}
protected void markNewRetry(int currentRetryCount) throws Exception {
MonitoringUtil.increaseTaskRetryCount(getCuratorClient(), taskId, currentRetryCount);
}
public int getRetryCount() {
return retryCount;
}
public void setRetryCount(int retryCount) {
// set the default retry count to 1
this.retryCount = retryCount <= 0 ? 1 : retryCount;
}
public OutPort getNextTask() {
return nextTask;
}
public void setNextTask(OutPort nextTask) {
this.nextTask = nextTask;
}
protected synchronized CuratorFramework getCuratorClient() {
if (curatorClient == null) {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
try {
this.curatorClient = CuratorFrameworkFactory.newClient(ServerSettings.getZookeeperConnection(), retryPolicy);
this.curatorClient.start();
} catch (ApplicationSettingsException e) {
logger.error("Failed to create curator client ", e);
throw new RuntimeException(e);
}
}
return curatorClient;
}
public AbstractTask setParticipant(HelixParticipant participant) {
this.participant = participant;
return this;
}
}
| 616 |
0 | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core/OutPort.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.helix.core;
import org.apache.helix.task.TaskResult;
import org.apache.helix.task.UserContentStore;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class OutPort {
private String nextJobId;
private AbstractTask task;
public OutPort(String nextJobId, AbstractTask task) {
this.nextJobId = nextJobId;
this.task = task;
}
public TaskResult invoke(TaskResult taskResult) {
task.sendNextJob(nextJobId);
return taskResult;
}
public String getNextJobId() {
return nextJobId;
}
public OutPort setNextJobId(String nextJobId) {
this.nextJobId = nextJobId;
return this;
}
public AbstractTask getTask() {
return task;
}
public OutPort setTask(AbstractTask task) {
this.task = task;
return this;
}
}
| 617 |
0 | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core/util/MonitoringUtil.java | package org.apache.airavata.helix.core.util;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MonitoringUtil {
private final static Logger logger = LoggerFactory.getLogger(MonitoringUtil.class);
private static final String PATH_PREFIX = "/airavata";
private static final String TASK = "/task";
private static final String RETRY = "/retry";
public static int getTaskRetryCount(CuratorFramework curatorClient, String taskId) throws Exception {
String path = PATH_PREFIX + TASK + "/" + taskId + RETRY;
if (curatorClient.checkExists().forPath(path) != null) {
byte[] processBytes = curatorClient.getData().forPath(path);
return Integer.parseInt(new String(processBytes));
} else {
return 1;
}
}
public static void increaseTaskRetryCount(CuratorFramework curatorClient, String takId, int currentRetryCount) throws Exception {
String path = PATH_PREFIX + TASK + "/" + takId + RETRY;
if (curatorClient.checkExists().forPath(path) != null) {
curatorClient.delete().forPath(path);
}
curatorClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(
path , ((currentRetryCount + 1) + "").getBytes());
}
private static void deleteIfExists(CuratorFramework curatorClient, String path) throws Exception {
if (curatorClient.checkExists().forPath(path) != null) {
curatorClient.delete().deletingChildrenIfNeeded().forPath(path);
}
}
public static void deleteTaskSpecificNodes(CuratorFramework curatorClient, String takId) throws Exception {
deleteIfExists(curatorClient, PATH_PREFIX + TASK + "/" + takId + RETRY);
}
}
| 618 |
0 | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core/util/PropertyResolver.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.helix.core.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
import java.util.Properties;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class PropertyResolver {
private Properties properties = new Properties();
public void loadFromFile(File propertyFile) throws IOException {
properties = new Properties();
properties.load(new FileInputStream(propertyFile));
}
public void loadInputStream(InputStream inputStream) throws IOException {
properties = new Properties();
properties.load(inputStream);
}
public String get(String key) {
if (properties.containsKey(key)) {
if (System.getenv(key.replace(".", "_")) != null) {
return System.getenv(key.replace(".", "_"));
} else {
return properties.getProperty(key);
}
} else {
return null;
}
}
public String get(String key, String defaultValue) {
return Optional.ofNullable(get(key)).orElse(defaultValue);
}
}
| 619 |
0 | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core/util/TaskUtil.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.helix.core.util;
import org.apache.airavata.helix.core.AbstractTask;
import org.apache.airavata.helix.core.OutPort;
import org.apache.airavata.helix.task.api.TaskParamType;
import org.apache.airavata.helix.task.api.annotation.TaskOutPort;
import org.apache.airavata.helix.task.api.annotation.TaskParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class TaskUtil {
private final static Logger logger = LoggerFactory.getLogger(TaskUtil.class);
public static <T extends AbstractTask> List<OutPort> getOutPortsOfTask(T taskObj) throws IllegalAccessException {
List<OutPort> outPorts = new ArrayList<>();
for (Class<?> c = taskObj.getClass(); c != null; c = c.getSuperclass()) {
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
TaskOutPort outPortAnnotation = field.getAnnotation(TaskOutPort.class);
if (outPortAnnotation != null) {
field.setAccessible(true);
OutPort outPort = (OutPort) field.get(taskObj);
outPorts.add(outPort);
}
}
}
return outPorts;
}
public static <T extends AbstractTask> Map<String, String> serializeTaskData(T data) throws IllegalAccessException {
Map<String, String> result = new HashMap<>();
for (Class<?> c = data.getClass(); c != null; c = c.getSuperclass()) {
Field[] fields = c.getDeclaredFields();
for (Field classField : fields) {
TaskParam parm = classField.getAnnotation(TaskParam.class);
if (parm != null) {
classField.setAccessible(true);
if (classField.get(data) instanceof TaskParamType) {
result.put(parm.name(), TaskParamType.class.cast(classField.get(data)).serialize());
} else {
result.put(parm.name(), classField.get(data).toString());
}
}
TaskOutPort outPort = classField.getAnnotation(TaskOutPort.class);
if (outPort != null) {
classField.setAccessible(true);
if (classField.get(data) != null) {
result.put(outPort.name(), ((OutPort) classField.get(data)).getNextJobId().toString());
}
}
}
}
return result;
}
public static <T extends AbstractTask> void deserializeTaskData(T instance, Map<String, String> params) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
List<Field> allFields = new ArrayList<>();
Class genericClass = instance.getClass();
while (AbstractTask.class.isAssignableFrom(genericClass)) {
Field[] declaredFields = genericClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
allFields.add(declaredField);
}
genericClass = genericClass.getSuperclass();
}
for (Field classField : allFields) {
TaskParam param = classField.getAnnotation(TaskParam.class);
if (param != null) {
if (params.containsKey(param.name())) {
classField.setAccessible(true);
if (classField.getType().isAssignableFrom(String.class)) {
classField.set(instance, params.get(param.name()));
} else if (classField.getType().isAssignableFrom(Integer.class) ||
classField.getType().isAssignableFrom(Integer.TYPE)) {
classField.set(instance, Integer.parseInt(params.get(param.name())));
} else if (classField.getType().isAssignableFrom(Long.class) ||
classField.getType().isAssignableFrom(Long.TYPE)) {
classField.set(instance, Long.parseLong(params.get(param.name())));
} else if (classField.getType().isAssignableFrom(Boolean.class) ||
classField.getType().isAssignableFrom(Boolean.TYPE)) {
classField.set(instance, Boolean.parseBoolean(params.get(param.name())));
} else if (TaskParamType.class.isAssignableFrom(classField.getType())) {
Class<?> clazz = classField.getType();
Constructor<?> ctor = clazz.getConstructor();
Object obj = ctor.newInstance();
((TaskParamType)obj).deserialize(params.get(param.name()));
classField.set(instance, obj);
}
}
}
}
for (Field classField : allFields) {
TaskOutPort outPort = classField.getAnnotation(TaskOutPort.class);
if (outPort != null) {
classField.setAccessible(true);
if (params.containsKey(outPort.name())) {
classField.set(instance, new OutPort(params.get(outPort.name()), instance));
} else {
classField.set(instance, new OutPort(null, instance));
}
}
}
}
public static String replaceSpecialCharacters(String originalTxt, String replaceTxt) {
return originalTxt.replaceAll("[^a-zA-Z0-9_-]", replaceTxt);
}
}
| 620 |
0 | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core/participant/HelixParticipant.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.helix.core.participant;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.helix.core.support.TaskHelperImpl;
import org.apache.airavata.helix.core.AbstractTask;
import org.apache.airavata.helix.core.util.PropertyResolver;
import org.apache.airavata.helix.task.api.annotation.TaskDef;
import org.apache.helix.InstanceType;
import org.apache.helix.examples.OnlineOfflineStateModelFactory;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZKHelixManager;
import org.apache.helix.manager.zk.ZNRecordSerializer;
import org.apache.helix.manager.zk.ZkClient;
import org.apache.helix.model.BuiltInStateModelDefinitions;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.participant.StateMachineEngine;
import org.apache.helix.task.TaskFactory;
import org.apache.helix.task.TaskStateModelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class HelixParticipant<T extends AbstractTask> implements Runnable {
private final static Logger logger = LoggerFactory.getLogger(HelixParticipant.class);
private int shutdownGracePeriod = 30000;
private int shutdownGraceRetries = 2;
private String zkAddress;
private String clusterName;
private String participantName;
private ZKHelixManager zkHelixManager;
private String taskTypeName;
private List<Class<? extends T>> taskClasses;
private final List<String> runningTasks = Collections.synchronizedList(new ArrayList<String>());
public HelixParticipant(List<Class<? extends T>> taskClasses, String taskTypeName) throws ApplicationSettingsException {
logger.info("Initializing Participant Node");
this.zkAddress = ServerSettings.getZookeeperConnection();
this.clusterName = ServerSettings.getSetting("helix.cluster.name");
this.participantName = getParticipantName();
this.taskTypeName = taskTypeName;
this.taskClasses = taskClasses;
logger.info("Zookeeper connection URL " + zkAddress);
logger.info("Cluster name " + clusterName);
logger.info("Participant name " + participantName);
logger.info("Task type " + taskTypeName);
if (taskClasses != null) {
for (Class<? extends T> taskClass : taskClasses) {
logger.info("Task classes include: " + taskClass.getCanonicalName());
}
}
}
public HelixParticipant(Class<T> taskClass, String taskTypeName) throws ApplicationSettingsException {
this(taskClass != null ? Collections.singletonList(taskClass) : null, taskTypeName);
}
public void setShutdownGracePeriod(int shutdownGracePeriod) {
this.shutdownGracePeriod = shutdownGracePeriod;
}
public void setShutdownGraceRetries(int shutdownGraceRetries) {
this.shutdownGraceRetries = shutdownGraceRetries;
}
public void registerRunningTask(AbstractTask task) {
runningTasks.add(task.getTaskId());
logger.info("Registered Task " + task.getTaskId() + ". Currently available " + runningTasks.size());
}
public void unregisterRunningTask(AbstractTask task) {
runningTasks.remove(task.getTaskId());
logger.info("Un registered Task " + task.getTaskId() + ". Currently available " + runningTasks.size());
}
@SuppressWarnings("WeakerAccess")
public Map<String, TaskFactory> getTaskFactory() {
Map<String, TaskFactory> taskRegistry = new HashMap<>();
for (Class<? extends T> taskClass : taskClasses) {
TaskFactory taskFac = context -> {
try {
return AbstractTask.class.cast(taskClass.newInstance())
.setParticipant(HelixParticipant.this)
.setCallbackContext(context)
.setTaskHelper(new TaskHelperImpl());
} catch (InstantiationException | IllegalAccessException e) {
logger.error("Failed to initialize the task: " + context.getTaskConfig().getId(), e);
return null;
}
};
TaskDef taskDef = taskClass.getAnnotation(TaskDef.class);
taskRegistry.put(taskDef.name(), taskFac);
}
return taskRegistry;
}
public void run() {
ZkClient zkClient = null;
try {
zkClient = new ZkClient(zkAddress, ZkClient.DEFAULT_SESSION_TIMEOUT,
ZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
ZKHelixAdmin zkHelixAdmin = new ZKHelixAdmin(zkClient);
List<String> nodesInCluster = zkHelixAdmin.getInstancesInCluster(clusterName);
if (!nodesInCluster.contains(participantName)) {
InstanceConfig instanceConfig = new InstanceConfig(participantName);
instanceConfig.setHostName("localhost");
instanceConfig.setInstanceEnabled(true);
if (taskTypeName != null) {
instanceConfig.addTag(taskTypeName);
}
zkHelixAdmin.addInstance(clusterName, instanceConfig);
logger.info("Participant: " + participantName + " has been added to cluster: " + clusterName);
} else {
if (taskTypeName != null) {
zkHelixAdmin.addInstanceTag(clusterName, participantName, taskTypeName);
}
zkHelixAdmin.enableInstance(clusterName, participantName, true);
logger.debug("Participant: " + participantName + " has been re-enabled at the cluster: " + clusterName);
}
Runtime.getRuntime().addShutdownHook(
new Thread(() -> {
logger.debug("Participant: " + participantName + " shutdown hook called");
try {
zkHelixAdmin.enableInstance(clusterName, participantName, false);
} catch (Exception e) {
logger.warn("Participant: " + participantName + " was not disabled normally", e);
}
disconnect();
})
);
// connect the participant manager
connect();
} catch (Exception ex) {
logger.error("Error in run() for Participant: " + participantName + ", reason: " + ex, ex);
} finally {
if (zkClient != null) {
zkClient.close();
}
}
}
private void connect() {
try {
zkHelixManager = new ZKHelixManager(clusterName, participantName, InstanceType.PARTICIPANT, zkAddress);
// register online-offline model
StateMachineEngine machineEngine = zkHelixManager.getStateMachineEngine();
OnlineOfflineStateModelFactory factory = new OnlineOfflineStateModelFactory(participantName);
machineEngine.registerStateModelFactory(BuiltInStateModelDefinitions.OnlineOffline.name(), factory);
// register task model
machineEngine.registerStateModelFactory("Task", new TaskStateModelFactory(zkHelixManager, getTaskFactory()));
logger.debug("Participant: " + participantName + ", registered state model factories.");
zkHelixManager.connect();
logger.info("Participant: " + participantName + ", has connected to cluster: " + clusterName);
Thread.currentThread().join();
} catch (InterruptedException ex) {
logger.error("Participant: " + participantName + ", is interrupted! reason: " + ex, ex);
} catch (Exception ex) {
logger.error("Error in connect() for Participant: " + participantName + ", reason: " + ex, ex);
} finally {
disconnect();
}
}
private void disconnect() {
logger.info("Shutting down participant. Currently available tasks " + runningTasks.size());
if (zkHelixManager != null) {
if (runningTasks.size() > 0) {
for (int i = 0; i <= shutdownGraceRetries; i++) {
logger.info("Shutting down gracefully [RETRY " + i + "]");
try {
Thread.sleep(shutdownGracePeriod);
} catch (InterruptedException e) {
logger.warn("Waiting for running tasks failed [RETRY " + i + "]", e);
}
if (runningTasks.size() == 0) {
break;
}
}
}
logger.info("Participant: " + participantName + ", has disconnected from cluster: " + clusterName);
zkHelixManager.disconnect();
}
}
public String getParticipantName() throws ApplicationSettingsException {
return ServerSettings.getSetting("helix.participant.name");
}
}
| 621 |
0 | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core/support/TaskHelperImpl.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.helix.core.support;
import org.apache.airavata.helix.core.support.adaptor.AdaptorSupportImpl;
import org.apache.airavata.helix.task.api.TaskHelper;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class TaskHelperImpl implements TaskHelper {
public AdaptorSupportImpl getAdaptorSupport() {
return AdaptorSupportImpl.getInstance();
}
}
| 622 |
0 | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core/support | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core/support/adaptor/AdaptorSupportImpl.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.helix.core.support.adaptor;
import org.apache.airavata.agents.api.*;
import org.apache.airavata.helix.adaptor.SSHJAgentAdaptor;
import org.apache.airavata.helix.adaptor.SSHJStorageAdaptor;
import org.apache.airavata.helix.task.api.support.AdaptorSupport;
import org.apache.airavata.model.appcatalog.computeresource.JobSubmissionProtocol;
import org.apache.airavata.model.data.movement.DataMovementProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class AdaptorSupportImpl implements AdaptorSupport {
private final static Logger logger = LoggerFactory.getLogger(AdaptorSupportImpl.class);
private static AdaptorSupportImpl INSTANCE;
private final AgentStore agentStore = new AgentStore();
private AdaptorSupportImpl() {}
public synchronized static AdaptorSupportImpl getInstance() {
if (INSTANCE == null) {
INSTANCE = new AdaptorSupportImpl();
}
return INSTANCE;
}
public void initializeAdaptor() {
}
public AgentAdaptor fetchAdaptor(String gatewayId, String computeResourceId, JobSubmissionProtocol protocol, String authToken, String userId) throws AgentException {
logger.debug("Fetching adaptor for compute resource " + computeResourceId + " with token " + authToken +
" with user " + userId + " with protocol" + protocol.name());
Optional<AgentAdaptor> agentAdaptorOp = agentStore.getAgentAdaptor(computeResourceId, protocol, authToken, userId);
if (agentAdaptorOp.isPresent()) {
logger.debug("Re using the adaptor for gateway " + gatewayId + ", compute resource " +
computeResourceId + ", protocol " + protocol + " , user " + userId);
return agentAdaptorOp.get();
} else {
synchronized (this) {
agentAdaptorOp = agentStore.getAgentAdaptor(computeResourceId, protocol, authToken, userId);
if (agentAdaptorOp.isPresent()) {
return agentAdaptorOp.get();
} else {
logger.debug("Could not find an adaptor for gateway " + gatewayId + ", compute resource " +
computeResourceId + ", protocol " + protocol + " , user " + userId + ". Creating new one");
switch (protocol) {
case SSH:
SSHJAgentAdaptor agentAdaptor = new SSHJAgentAdaptor();
agentAdaptor.init(computeResourceId, gatewayId, userId, authToken);
agentStore.putAgentAdaptor(computeResourceId, protocol, authToken, userId, agentAdaptor);
return agentAdaptor;
default:
throw new AgentException("Could not find an agent adaptor for gateway " + gatewayId +
", compute resource " + computeResourceId + ", protocol " + protocol + " , user " + userId);
}
}
}
}
}
@Override
public StorageResourceAdaptor fetchStorageAdaptor(String gatewayId, String storageResourceId, DataMovementProtocol protocol, String authToken, String userId) throws AgentException {
logger.debug("Fetching adaptor for storage resource " + storageResourceId + " with token " + authToken +
" with user " + userId + " with protocol" + protocol.name());
Optional<StorageResourceAdaptor> agentAdaptorOp = agentStore.getStorageAdaptor(storageResourceId, protocol, authToken, userId);
if (agentAdaptorOp.isPresent()) {
logger.debug("Re using the storage adaptor for gateway " + gatewayId + ", storage resource " +
storageResourceId + ", protocol " + protocol + " , user " + userId);
return agentAdaptorOp.get();
} else {
synchronized (this) {
agentAdaptorOp = agentStore.getStorageAdaptor(storageResourceId, protocol, authToken, userId);
if (agentAdaptorOp.isPresent()) {
return agentAdaptorOp.get();
} else {
logger.debug("Could not find a storage adaptor for gateway " + gatewayId + ", storage resource " +
storageResourceId + ", protocol " + protocol + " , user " + userId + ". Creating new one");
switch (protocol) {
case SCP:
SSHJStorageAdaptor storageResourceAdaptor = new SSHJStorageAdaptor();
storageResourceAdaptor.init(storageResourceId, gatewayId, userId, authToken);
agentStore.putStorageAdaptor(storageResourceId, protocol, authToken, userId, storageResourceAdaptor);
return storageResourceAdaptor;
default:
throw new AgentException("Could not find an storage adaptor for gateway " + gatewayId +
", storage resource " + storageResourceId + ", protocol " + protocol + " , user " + userId);
}
}
}
}
}
}
| 623 |
0 | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core/support | Create_ds/airavata/modules/airavata-helix/task-core/src/main/java/org/apache/airavata/helix/core/support/adaptor/AgentStore.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.helix.core.support.adaptor;
import org.apache.airavata.agents.api.AgentAdaptor;
import org.apache.airavata.agents.api.StorageResourceAdaptor;
import org.apache.airavata.model.appcatalog.computeresource.JobSubmissionProtocol;
import org.apache.airavata.model.data.movement.DataMovementProtocol;
import org.apache.zookeeper.Op;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class AgentStore {
// compute resource: Job submission protocol: auth token: user: adaptor
private final Map<String, Map<JobSubmissionProtocol, Map<String, Map<String, AgentAdaptor>>>> agentAdaptorCache = new HashMap<>();
private final Map<String, Map<DataMovementProtocol, Map<String, Map<String, StorageResourceAdaptor>>>> storageAdaptorCache = new HashMap<>();
public Optional<AgentAdaptor> getAgentAdaptor(String computeResource, JobSubmissionProtocol submissionProtocol, String authToken, String userId) {
Map<JobSubmissionProtocol, Map<String, Map<String, AgentAdaptor>>> protoToTokenMap = agentAdaptorCache.get(computeResource);
if (protoToTokenMap != null) {
Map<String, Map<String,AgentAdaptor>> tokenToUserMap = protoToTokenMap.get(submissionProtocol);
if (tokenToUserMap != null) {
Map<String, AgentAdaptor> userToAdaptorMap = tokenToUserMap.get(authToken);
if (userToAdaptorMap != null) {
return Optional.ofNullable(userToAdaptorMap.get(userId));
} else {
return Optional.empty();
}
} else {
return Optional.empty();
}
} else {
return Optional.empty();
}
}
public void putAgentAdaptor(String computeResource, JobSubmissionProtocol submissionProtocol, String authToken, String userId, AgentAdaptor agentAdaptor) {
Map<JobSubmissionProtocol, Map<String, Map<String,AgentAdaptor>>> protoToTokenMap = agentAdaptorCache.computeIfAbsent(computeResource, k -> new HashMap<>());
Map<String, Map<String,AgentAdaptor>> tokenToUserMap = protoToTokenMap.computeIfAbsent(submissionProtocol, k -> new HashMap<>());
Map<String, AgentAdaptor> userToAdaptorMap = tokenToUserMap.computeIfAbsent(authToken, k-> new HashMap<>());
userToAdaptorMap.put(userId, agentAdaptor);
}
public Optional<StorageResourceAdaptor> getStorageAdaptor(String computeResource, DataMovementProtocol dataMovementProtocol, String authToken, String userId) {
Map<DataMovementProtocol, Map<String, Map<String, StorageResourceAdaptor>>> protoToTokenMap = storageAdaptorCache.get(computeResource);
if (protoToTokenMap != null) {
Map<String, Map<String, StorageResourceAdaptor>> tokenToUserMap = protoToTokenMap.get(dataMovementProtocol);
if (tokenToUserMap != null) {
Map<String, StorageResourceAdaptor> userToAdaptorMap = tokenToUserMap.get(authToken);
if (userToAdaptorMap != null) {
return Optional.ofNullable(userToAdaptorMap.get(userId));
} else {
return Optional.empty();
}
} else {
return Optional.empty();
}
} else {
return Optional.empty();
}
}
public void putStorageAdaptor(String computeResource, DataMovementProtocol dataMovementProtocol, String authToken, String userId, StorageResourceAdaptor storageResourceAdaptor) {
Map<DataMovementProtocol, Map<String, Map<String, StorageResourceAdaptor>>> protoToTokenMap = storageAdaptorCache.computeIfAbsent(computeResource, k -> new HashMap<>());
Map<String, Map<String, StorageResourceAdaptor>> tokenToUserMap = protoToTokenMap.computeIfAbsent(dataMovementProtocol, k -> new HashMap<>());
Map<String, StorageResourceAdaptor> userToAdaptorMap = tokenToUserMap.computeIfAbsent(authToken, k -> new HashMap<>());
userToAdaptorMap.put(userId, storageResourceAdaptor);
}
}
| 624 |
0 | Create_ds/airavata/modules/airavata-helix/agent-impl/ssh-agent/src/main/java/org/apache/airavata/helix/agent | Create_ds/airavata/modules/airavata-helix/agent-impl/ssh-agent/src/main/java/org/apache/airavata/helix/agent/storage/StorageResourceAdaptorImpl.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.helix.agent.storage;
import org.apache.airavata.agents.api.AgentException;
import org.apache.airavata.agents.api.AgentUtils;
import org.apache.airavata.agents.api.CommandOutput;
import org.apache.airavata.agents.api.StorageResourceAdaptor;
import org.apache.airavata.helix.agent.ssh.SshAdaptorParams;
import org.apache.airavata.helix.agent.ssh.SshAgentAdaptor;
import org.apache.airavata.model.appcatalog.storageresource.StorageResourceDescription;
import org.apache.airavata.model.credential.store.SSHCredential;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StorageResourceAdaptorImpl extends SshAgentAdaptor implements StorageResourceAdaptor {
private final static Logger logger = LoggerFactory.getLogger(StorageResourceAdaptorImpl.class);
@Override
public void init(String storageResourceId, String gatewayId, String loginUser, String token) throws AgentException {
try {
logger.info("Initializing Storage Resource Adaptor for storage resource : "+ storageResourceId + ", gateway : " +
gatewayId +", user " + loginUser + ", token : " + token);
StorageResourceDescription storageResource = AgentUtils.getRegistryServiceClient().getStorageResource(storageResourceId);
logger.info("Fetching credentials for cred store token " + token);
SSHCredential sshCredential = AgentUtils.getCredentialClient().getSSHCredential(token, gatewayId);
if (sshCredential == null) {
throw new AgentException("Null credential for token " + token);
}
logger.info("Description for token : " + token + " : " + sshCredential.getDescription());
SshAdaptorParams adaptorParams = new SshAdaptorParams();
adaptorParams.setHostName(storageResource.getHostName());
adaptorParams.setUserName(loginUser);
adaptorParams.setPassphrase(sshCredential.getPassphrase());
adaptorParams.setPrivateKey(sshCredential.getPrivateKey().getBytes());
adaptorParams.setPublicKey(sshCredential.getPublicKey().getBytes());
adaptorParams.setStrictHostKeyChecking(false);
init(adaptorParams);
} catch (Exception e) {
logger.error("Error while initializing ssh agent for storage resource " + storageResourceId + " to token " + token, e);
throw new AgentException("Error while initializing ssh agent for storage resource " + storageResourceId + " to token " + token, e);
}
}
@Override
public void uploadFile(String localFile, String remoteFile) throws AgentException {
super.uploadFile(localFile, remoteFile);
}
@Override
public void downloadFile(String remoteFile, String localFile) throws AgentException {
super.downloadFile(remoteFile, localFile);
}
@Override
public CommandOutput executeCommand(String command, String workingDirectory) throws AgentException {
return super.executeCommand(command, workingDirectory);
}
}
| 625 |
0 | Create_ds/airavata/modules/airavata-helix/agent-impl/ssh-agent/src/main/java/org/apache/airavata/helix/agent | Create_ds/airavata/modules/airavata-helix/agent-impl/ssh-agent/src/main/java/org/apache/airavata/helix/agent/ssh/SshAgentAdaptor.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.helix.agent.ssh;
import com.jcraft.jsch.*;
import org.apache.airavata.agents.api.*;
import org.apache.airavata.model.credential.store.SSHCredential;
import org.apache.airavata.model.appcatalog.computeresource.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class SshAgentAdaptor implements AgentAdaptor {
private final static Logger logger = LoggerFactory.getLogger(SshAgentAdaptor.class);
private Session session = null;
public void init(AdaptorParams adaptorParams) throws AgentException {
if (adaptorParams instanceof SshAdaptorParams) {
SshAdaptorParams params = SshAdaptorParams.class.cast(adaptorParams);
JSch jSch = new JSch();
try {
if (params.getPassword() != null) {
this.session = jSch.getSession(params.getUserName(), params.getHostName(), params.getPort());
session.setPassword(params.getPassword());
session.setUserInfo(new SftpUserInfo(params.getPassword()));
} else {
jSch.addIdentity(UUID.randomUUID().toString(), params.getPrivateKey(), params.getPublicKey(),
params.getPassphrase().getBytes());
this.session = jSch.getSession(params.getUserName(), params.getHostName(),
params.getPort());
session.setUserInfo(new DefaultUserInfo(params.getUserName(), null, params.getPassphrase()));
}
if (params.isStrictHostKeyChecking()) {
jSch.setKnownHosts(params.getKnownHostsFilePath());
} else {
session.setConfig("StrictHostKeyChecking", "no");
}
session.connect(); // 0 connection timeout
} catch (JSchException e) {
throw new AgentException("Could not create ssh session for host " + params.getHostName(), e);
}
} else {
throw new AgentException("Unknown parameter type to ssh initialize agent adaptor. Required SshAdaptorParams type");
}
}
@Override
public void init(String computeResourceId, String gatewayId, String userId, String token) throws AgentException {
try {
ComputeResourceDescription computeResourceDescription = AgentUtils.getRegistryServiceClient().getComputeResource(computeResourceId);
logger.info("Fetching credentials for cred store token " + token);
SSHCredential sshCredential = AgentUtils.getCredentialClient().getSSHCredential(token, gatewayId);
if (sshCredential == null) {
throw new AgentException("Null credential for token " + token);
}
logger.info("Description for token : " + token + " : " + sshCredential.getDescription());
SshAdaptorParams adaptorParams = new SshAdaptorParams();
adaptorParams.setHostName(computeResourceDescription.getHostName());
adaptorParams.setUserName(userId);
adaptorParams.setPassphrase(sshCredential.getPassphrase());
adaptorParams.setPrivateKey(sshCredential.getPrivateKey().getBytes());
adaptorParams.setPublicKey(sshCredential.getPublicKey().getBytes());
adaptorParams.setStrictHostKeyChecking(false);
init(adaptorParams);
} catch (Exception e) {
logger.error("Error while initializing ssh agent for compute resource " + computeResourceId + " to token " + token, e);
throw new AgentException("Error while initializing ssh agent for compute resource " + computeResourceId + " to token " + token, e);
}
}
@Override
public void destroy() {
}
public CommandOutput executeCommand(String command, String workingDirectory) throws AgentException {
StandardOutReader commandOutput = new StandardOutReader();
ChannelExec channelExec = null;
try {
channelExec = ((ChannelExec) session.openChannel("exec"));
channelExec.setCommand((workingDirectory != null ? "cd " + workingDirectory + "; " : "") + command);
channelExec.setInputStream(null);
InputStream out = channelExec.getInputStream();
InputStream err = channelExec.getErrStream();
channelExec.connect();
commandOutput.readStdOutFromStream(out);
commandOutput.readStdErrFromStream(err);
return commandOutput;
} catch (JSchException | IOException e) {
logger.error("Failed to execute command " + command, e);
throw new AgentException("Failed to execute command " + command, e);
} finally {
if (channelExec != null) {
commandOutput.setExitCode(channelExec.getExitStatus());
channelExec.disconnect();
}
}
}
public void createDirectory(String path) throws AgentException {
createDirectory(path, false);
}
@Override
public void createDirectory(String path, boolean recursive) throws AgentException {
String command = (recursive? "mkdir -p " : "mkdir ") + path;
ChannelExec channelExec = null;
try {
channelExec = (ChannelExec)session.openChannel("exec");
StandardOutReader stdOutReader = new StandardOutReader();
channelExec.setCommand(command);
InputStream out = channelExec.getInputStream();
InputStream err = channelExec.getErrStream();
channelExec.connect();
stdOutReader.readStdOutFromStream(out);
stdOutReader.readStdErrFromStream(err);
if (stdOutReader.getStdError() != null && stdOutReader.getStdError().contains("mkdir:")) {
throw new AgentException(stdOutReader.getStdError());
}
} catch (JSchException e) {
System.out.println("Unable to retrieve command output. Command - " + command +
" on server - " + session.getHost() + ":" + session.getPort() +
" connecting user name - "
+ session.getUserName());
throw new AgentException(e);
} catch (IOException e) {
logger.error("Failed to create directory " + path, e);
throw new AgentException("Failed to create directory " + path, e);
} finally {
if (channelExec != null) {
channelExec.disconnect();
}
}
}
public void uploadFile(String localFile, String remoteFile) throws AgentException {
FileInputStream fis;
boolean ptimestamp = true;
ChannelExec channelExec = null;
try {
// exec 'scp -t rfile' remotely
String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + remoteFile;
channelExec = (ChannelExec)session.openChannel("exec");
StandardOutReader stdOutReader = new StandardOutReader();
//channelExec.setErrStream(stdOutReader.getStandardError());
channelExec.setCommand(command);
// get I/O streams for remote scp
OutputStream out = channelExec.getOutputStream();
InputStream in = channelExec.getInputStream();
InputStream err = channelExec.getErrStream();
channelExec.connect();
if (checkAck(in) != 0) {
String error = "Error Reading input Stream";
//log.error(error);
throw new AgentException(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";
throw new AgentException(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 AgentException(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 AgentException(error);
}
out.close();
stdOutReader.readStdErrFromStream(err);
if (stdOutReader.getStdError().contains("scp:")) {
throw new AgentException(stdOutReader.getStdError());
}
//since remote file is always a file we just return the file
//return remoteFile;
} catch (JSchException e) {
logger.error("Failed to transfer file from " + localFile + " to remote location " + remoteFile, e);
throw new AgentException("Failed to transfer file from " + localFile + " to remote location " + remoteFile, e);
} catch (FileNotFoundException e) {
logger.error("Failed to find local file " + localFile, e);
throw new AgentException("Failed to find local file " + localFile, e);
} catch (IOException e) {
logger.error("Error while handling streams", e);
throw new AgentException("Error while handling streams", e);
} finally {
if (channelExec != null) {
channelExec.disconnect();
}
}
}
@Override
public void uploadFile(InputStream localInStream, FileMetadata metadata, String remoteFile) throws AgentException {
throw new AgentException("Operation not implemented");
}
// TODO file not found does not return exception
public void downloadFile(String remoteFile, String localFile) throws AgentException {
FileOutputStream fos = null;
ChannelExec channelExec = null;
try {
String prefix = null;
if (new File(localFile).isDirectory()) {
prefix = localFile + File.separator;
}
StandardOutReader stdOutReader = new StandardOutReader();
// exec 'scp -f remotefile' remotely
String command = "scp -f " + remoteFile;
channelExec = (ChannelExec)session.openChannel("exec");
channelExec.setCommand(command);
//channelExec.setErrStream(stdOutReader.getStandardError());
// get I/O streams for remote scp
OutputStream out = channelExec.getOutputStream();
InputStream in = channelExec.getInputStream();
InputStream err = channelExec.getErrStream();
if (!channelExec.isClosed()){
channelExec.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 AgentException(error);
}
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
}
stdOutReader.readStdErrFromStream(err);
if (stdOutReader.getStdError().contains("scp:")) {
throw new AgentException(stdOutReader.getStdError());
}
} catch (JSchException e) {
logger.error("Failed to transfer file remote from file " + remoteFile + " to location " + remoteFile, e);
throw new AgentException("Failed to transfer remote file from " + localFile + " to location " + remoteFile, e);
} catch (FileNotFoundException e) {
logger.error("Failed to find local file " + localFile, e);
throw new AgentException("Failed to find local file " + localFile, e);
} catch (IOException e) {
logger.error("Error while handling streams", e);
throw new AgentException("Error while handling streams", e);
} finally {
try {
if (fos != null) fos.close();
} catch (Exception ee) {
logger.warn("Failed to close file output stream to " + localFile);
}
if (channelExec != null) {
channelExec.disconnect();
}
}
}
@Override
public void downloadFile(String remoteFile, OutputStream localOutStream, FileMetadata metadata) throws AgentException {
throw new AgentException("Operation not implemented");
}
@Override
public List<String> listDirectory(String path) throws AgentException {
String command = "ls " + path;
ChannelExec channelExec = null;
try {
channelExec = (ChannelExec)session.openChannel("exec");
StandardOutReader stdOutReader = new StandardOutReader();
channelExec.setCommand(command);
InputStream out = channelExec.getInputStream();
InputStream err = channelExec.getErrStream();
channelExec.connect();
stdOutReader.readStdOutFromStream(out);
stdOutReader.readStdErrFromStream(err);
if (stdOutReader.getStdError().contains("ls:")) {
throw new AgentException(stdOutReader.getStdError());
}
return Arrays.asList(stdOutReader.getStdOut().split("\n"));
} catch (JSchException e) {
logger.error("Unable to retrieve command output. Command - " + command +
" on server - " + session.getHost() + ":" + session.getPort() +
" connecting user name - "
+ session.getUserName(), e);
throw new AgentException("Unable to retrieve command output. Command - " + command +
" on server - " + session.getHost() + ":" + session.getPort() +
" connecting user name - "
+ session.getUserName(), e);
} catch (IOException e) {
logger.error("Error while handling streams", e);
throw new AgentException("Error while handling streams", e);
} finally {
if (channelExec != null) {
channelExec.disconnect();
}
}
}
@Override
public Boolean doesFileExist(String filePath) throws AgentException {
String command = "ls " + filePath;
ChannelExec channelExec = null;
try {
channelExec = (ChannelExec)session.openChannel("exec");
StandardOutReader stdOutReader = new StandardOutReader();
channelExec.setCommand(command);
InputStream out = channelExec.getInputStream();
InputStream err = channelExec.getErrStream();
channelExec.connect();
stdOutReader.readStdOutFromStream(out);
stdOutReader.readStdErrFromStream(err);
if (stdOutReader.getStdError().contains("ls:")) {
logger.info("Invalid file path " + filePath + ". stderr : " + stdOutReader.getStdError());
return false;
} else {
String[] potentialFiles = stdOutReader.getStdOut().split("\n");
if (potentialFiles.length > 1) {
logger.info("More than one file matching to given path " + filePath);
return false;
} else if (potentialFiles.length == 0) {
logger.info("No file found for given path " + filePath);
return false;
} else {
if (potentialFiles[0].trim().equals(filePath)) {
return true;
} else {
logger.info("Returned file name " + potentialFiles[0].trim() + " does not match with given name " + filePath);
return false;
}
}
}
} catch (JSchException e) {
logger.error("Unable to retrieve command output. Command - " + command +
" on server - " + session.getHost() + ":" + session.getPort() +
" connecting user name - "
+ session.getUserName(), e);
throw new AgentException("Unable to retrieve command output. Command - " + command +
" on server - " + session.getHost() + ":" + session.getPort() +
" connecting user name - "
+ session.getUserName(), e);
} catch (IOException e) {
logger.error("Error while handling streams", e);
throw new AgentException("Error while handling streams", e);
} finally {
if (channelExec != null) {
channelExec.disconnect();
}
}
}
@Override
public List<String> getFileNameFromExtension(String fileName, String parentPath) throws AgentException {
throw new AgentException("Operation not implemented");
}
@Override
public FileMetadata getFileMetadata(String remoteFile) throws AgentException {
throw new AgentException("Operation not implemented");
}
private static class DefaultUserInfo implements UserInfo, UIKeyboardInteractive {
private String userName;
private String password;
private String passphrase;
DefaultUserInfo(String userName, String password, String passphrase) {
this.userName = userName;
this.password = password;
this.passphrase = passphrase;
}
@Override
public String getPassphrase() {
return passphrase;
}
@Override
public String getPassword() {
return password;
}
@Override
public boolean promptPassword(String s) {
return true;
}
@Override
public boolean promptPassphrase(String s) {
return false;
}
@Override
public boolean promptYesNo(String s) {
return false;
}
@Override
public void showMessage(String s) {
}
@Override
public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
return new String[0];
}
}
class SftpUserInfo implements UserInfo {
String password = null;
public SftpUserInfo(String password) {
this.password = password;
}
@Override
public String getPassphrase() {
return null;
}
@Override
public String getPassword() {
return password;
}
public void setPassword(String passwd) {
password = passwd;
}
@Override
public boolean promptPassphrase(String message) {
return false;
}
@Override
public boolean promptPassword(String message) {
return false;
}
@Override
public boolean promptYesNo(String message) {
return true;
}
@Override
public void showMessage(String message) {
}
}
private static 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) {
StringBuilder sb = new StringBuilder();
int c;
do {
c = in.read();
sb.append((char) c);
}
while (c != '\n');
//FIXME: Redundant
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;
}
}
| 626 |
0 | Create_ds/airavata/modules/airavata-helix/agent-impl/ssh-agent/src/main/java/org/apache/airavata/helix/agent | Create_ds/airavata/modules/airavata-helix/agent-impl/ssh-agent/src/main/java/org/apache/airavata/helix/agent/ssh/SshAdaptorParams.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.helix.agent.ssh;
import org.apache.airavata.agents.api.AdaptorParams;
import java.io.*;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class SshAdaptorParams extends AdaptorParams implements Serializable {
private int port = 22;
private String hostName;
private String userName;
private String password;
private byte[] publicKey;
private byte[] privateKey;
private String passphrase;
private String knownHostsFilePath;
private boolean strictHostKeyChecking;
public int getPort() {
return port;
}
public SshAdaptorParams setPort(int port) {
this.port = port;
return this;
}
public String getHostName() {
return hostName;
}
public SshAdaptorParams setHostName(String hostName) {
this.hostName = hostName;
return this;
}
public String getUserName() {
return userName;
}
public SshAdaptorParams setUserName(String userName) {
this.userName = userName;
return this;
}
public String getPassword() {
return password;
}
public SshAdaptorParams setPassword(String password) {
this.password = password;
return this;
}
public byte[] getPublicKey() {
return publicKey;
}
public SshAdaptorParams setPublicKey(byte[] publicKey) {
this.publicKey = publicKey;
return this;
}
public byte[] getPrivateKey() {
return privateKey;
}
public SshAdaptorParams setPrivateKey(byte[] privateKey) {
this.privateKey = privateKey;
return this;
}
public String getPassphrase() {
return passphrase;
}
public SshAdaptorParams setPassphrase(String passphrase) {
this.passphrase = passphrase;
return this;
}
public String getKnownHostsFilePath() {
return knownHostsFilePath;
}
public SshAdaptorParams setKnownHostsFilePath(String knownHostsFilePath) {
this.knownHostsFilePath = knownHostsFilePath;
return this;
}
public boolean isStrictHostKeyChecking() {
return strictHostKeyChecking;
}
public SshAdaptorParams setStrictHostKeyChecking(boolean strictHostKeyChecking) {
this.strictHostKeyChecking = strictHostKeyChecking;
return this;
}
public static void main(String args[]) throws IOException {
SshAdaptorParams params = new SshAdaptorParams();
params.setUserName("dimuthu");
params.setPassword("upe");
params.setHostName("localhost");
params.writeToFile(new File("/tmp/ssh-param.json"));
}
}
| 627 |
0 | Create_ds/airavata/modules/airavata-helix/agent-impl/ssh-agent/src/main/java/org/apache/airavata/helix/agent | Create_ds/airavata/modules/airavata-helix/agent-impl/ssh-agent/src/main/java/org/apache/airavata/helix/agent/ssh/StandardOutReader.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.helix.agent.ssh;
import com.jcraft.jsch.Channel;
import org.apache.airavata.agents.api.CommandOutput;
import org.apache.commons.io.IOUtils;
import java.io.*;
/**
* TODO: Class level comments please
*
* @author dimuthu
* @since 1.0.0-SNAPSHOT
*/
public class StandardOutReader implements CommandOutput {
private String stdOut;
private String stdError;
private Integer exitCode;
@Override
public String getStdOut() {
return this.stdOut;
}
@Override
public String getStdError() {
return this.stdError;
}
@Override
public Integer getExitCode() {
return this.exitCode;
}
public void readStdOutFromStream(InputStream is) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
this.stdOut = writer.toString();
}
public void readStdErrFromStream(InputStream is) throws IOException {
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
this.stdError = writer.toString();
}
public void setExitCode(Integer exitCode) {
this.exitCode = exitCode;
}
}
| 628 |
0 | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix/adaptor/SSHJStorageAdaptor.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.helix.adaptor;
import org.apache.airavata.agents.api.AgentException;
import org.apache.airavata.agents.api.AgentUtils;
import org.apache.airavata.agents.api.CommandOutput;
import org.apache.airavata.agents.api.StorageResourceAdaptor;
import org.apache.airavata.model.appcatalog.storageresource.StorageResourceDescription;
import org.apache.airavata.model.credential.store.SSHCredential;
import org.apache.airavata.model.data.movement.DataMovementInterface;
import org.apache.airavata.model.data.movement.DataMovementProtocol;
import org.apache.airavata.model.data.movement.SCPDataMovement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
public class SSHJStorageAdaptor extends SSHJAgentAdaptor implements StorageResourceAdaptor {
private final static Logger logger = LoggerFactory.getLogger(SSHJAgentAdaptor.class);
@Override
public void init(String storageResourceId, String gatewayId, String loginUser, String token) throws AgentException {
try {
logger.info("Initializing Storage Resource SCP Adaptor for storage resource : "+ storageResourceId + ", gateway : " +
gatewayId +", user " + loginUser + ", token : " + token);
StorageResourceDescription storageResourceDescription = AgentUtils.getRegistryServiceClient().getStorageResource(storageResourceId);
logger.info("Fetching data movement interfaces for storage resource " + storageResourceId);
Optional<DataMovementInterface> dmInterfaceOp = storageResourceDescription.getDataMovementInterfaces()
.stream().filter(iface -> iface.getDataMovementProtocol() == DataMovementProtocol.SCP).findFirst();
DataMovementInterface scpInterface = dmInterfaceOp
.orElseThrow(() -> new AgentException("Could not find a SCP interface for storage resource " + storageResourceId));
SCPDataMovement scpDataMovement = AgentUtils.getRegistryServiceClient().getSCPDataMovement(scpInterface.getDataMovementInterfaceId());
logger.info("Fetching credentials for cred store token " + token);
SSHCredential sshCredential = AgentUtils.getCredentialClient().getSSHCredential(token, gatewayId);
if (sshCredential == null) {
throw new AgentException("Null credential for token " + token);
}
logger.info("Description for token : " + token + " : " + sshCredential.getDescription());
String alternateHostName = scpDataMovement.getAlternativeSCPHostName();
String selectedHostName = (alternateHostName == null || "".equals(alternateHostName))?
storageResourceDescription.getHostName() : alternateHostName;
int selectedPort = scpDataMovement.getSshPort() == 0 ? 22 : scpDataMovement.getSshPort();
createPoolingSSHJClient(loginUser, selectedHostName, selectedPort, sshCredential.getPublicKey(),
sshCredential.getPrivateKey(), sshCredential.getPassphrase());
} catch (Exception e) {
logger.error("Error while initializing ssh agent for storage resource " + storageResourceId + " to token " + token, e);
throw new AgentException("Error while initializing ssh agent for storage resource " + storageResourceId + " to token " + token, e);
}
}
@Override
public void uploadFile(String localFile, String remoteFile) throws AgentException {
super.uploadFile(localFile, remoteFile);
}
@Override
public void downloadFile(String remoteFile, String localFile) throws AgentException {
super.downloadFile(remoteFile, localFile);
}
@Override
public CommandOutput executeCommand(String command, String workingDirectory) throws AgentException {
return super.executeCommand(command, workingDirectory);
}
}
| 629 |
0 | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix/adaptor/SSHJAgentAdaptor.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.helix.adaptor;
import com.google.common.collect.Lists;
import net.schmizz.keepalive.KeepAliveProvider;
import net.schmizz.sshj.DefaultConfig;
import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.sftp.*;
import net.schmizz.sshj.userauth.keyprovider.KeyProvider;
import net.schmizz.sshj.userauth.method.AuthKeyboardInteractive;
import net.schmizz.sshj.userauth.method.AuthMethod;
import net.schmizz.sshj.userauth.method.AuthPublickey;
import net.schmizz.sshj.userauth.method.ChallengeResponseProvider;
import net.schmizz.sshj.userauth.password.PasswordFinder;
import net.schmizz.sshj.userauth.password.PasswordUtils;
import net.schmizz.sshj.userauth.password.Resource;
import net.schmizz.sshj.xfer.FilePermission;
import net.schmizz.sshj.xfer.LocalDestFile;
import net.schmizz.sshj.xfer.LocalFileFilter;
import net.schmizz.sshj.xfer.LocalSourceFile;
import org.apache.airavata.agents.api.*;
import org.apache.airavata.helix.adaptor.wrapper.SCPFileTransferWrapper;
import org.apache.airavata.helix.adaptor.wrapper.SFTPClientWrapper;
import org.apache.airavata.helix.adaptor.wrapper.SessionWrapper;
import org.apache.airavata.helix.agent.ssh.StandardOutReader;
import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription;
import org.apache.airavata.model.appcatalog.computeresource.JobSubmissionInterface;
import org.apache.airavata.model.appcatalog.computeresource.JobSubmissionProtocol;
import org.apache.airavata.model.appcatalog.computeresource.SSHJobSubmission;
import org.apache.airavata.model.credential.store.SSHCredential;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class SSHJAgentAdaptor implements AgentAdaptor {
private final static Logger logger = LoggerFactory.getLogger(SSHJAgentAdaptor.class);
private PoolingSSHJClient sshjClient;
protected void createPoolingSSHJClient(String user, String host, int port, String publicKey, String privateKey, String passphrase) throws IOException {
DefaultConfig defaultConfig = new DefaultConfig();
defaultConfig.setKeepAliveProvider(KeepAliveProvider.KEEP_ALIVE);
sshjClient = new PoolingSSHJClient(defaultConfig, host, port == 0 ? 22 : port);
sshjClient.addHostKeyVerifier((h, p, key) -> true);
sshjClient.setMaxSessionsForConnection(1);
PasswordFinder passwordFinder = passphrase != null ? PasswordUtils.createOneOff(passphrase.toCharArray()) : null;
KeyProvider keyProvider = sshjClient.loadKeys(privateKey, publicKey, passwordFinder);
final List<AuthMethod> am = new LinkedList<>();
am.add(new AuthPublickey(keyProvider));
am.add(new AuthKeyboardInteractive(new ChallengeResponseProvider() {
@Override
public List<String> getSubmethods() {
return new ArrayList<>();
}
@Override
public void init(Resource resource, String name, String instruction) {
}
@Override
public char[] getResponse(String prompt, boolean echo) {
return new char[0];
}
@Override
public boolean shouldRetry() {
return false;
}
}));
sshjClient.auth(user, am);
}
public void init(String user, String host, int port, String publicKey, String privateKey, String passphrase) throws AgentException {
try {
createPoolingSSHJClient(user, host, port, publicKey, privateKey, passphrase);
} catch (IOException e) {
logger.error("Error while initializing sshj agent for user " + user + " host " + host + " for key starting with " + publicKey.substring(0,10), e);
throw new AgentException("Error while initializing sshj agent for user " + user + " host " + host + " for key starting with " + publicKey.substring(0,10), e);
}
}
@Override
public void init(String computeResource, String gatewayId, String userId, String token) throws AgentException {
try {
logger.info("Initializing Compute Resource SSH Adaptor for compute resource : "+ computeResource + ", gateway : " +
gatewayId +", user " + userId + ", token : " + token);
ComputeResourceDescription computeResourceDescription = AgentUtils.getRegistryServiceClient().getComputeResource(computeResource);
logger.info("Fetching job submission interfaces for compute resource " + computeResource);
Optional<JobSubmissionInterface> jobSubmissionInterfaceOp = computeResourceDescription.getJobSubmissionInterfaces()
.stream().filter(iface -> iface.getJobSubmissionProtocol() == JobSubmissionProtocol.SSH).findFirst();
JobSubmissionInterface sshInterface = jobSubmissionInterfaceOp
.orElseThrow(() -> new AgentException("Could not find a SSH interface for compute resource " + computeResource));
SSHJobSubmission sshJobSubmission = AgentUtils.getRegistryServiceClient().getSSHJobSubmission(sshInterface.getJobSubmissionInterfaceId());
logger.info("Fetching credentials for cred store token " + token);
SSHCredential sshCredential = AgentUtils.getCredentialClient().getSSHCredential(token, gatewayId);
if (sshCredential == null) {
throw new AgentException("Null credential for token " + token);
}
logger.info("Description for token : " + token + " : " + sshCredential.getDescription());
String alternateHostName = sshJobSubmission.getAlternativeSSHHostName();
String selectedHostName = (alternateHostName == null || "".equals(alternateHostName))?
computeResourceDescription.getHostName() : alternateHostName;
int selectedPort = sshJobSubmission.getSshPort() == 0 ? 22 : sshJobSubmission.getSshPort();
logger.info("Using user {}, Host {}, Port {} to create ssh client for compute resource {}",
userId, selectedHostName, selectedPort, computeResource);
createPoolingSSHJClient(userId, selectedHostName, selectedPort,
sshCredential.getPublicKey(), sshCredential.getPrivateKey(), sshCredential.getPassphrase());
} catch (Exception e) {
logger.error("Error while initializing ssh agent for compute resource " + computeResource + " to token " + token, e);
throw new AgentException("Error while initializing ssh agent for compute resource " + computeResource + " to token " + token, e);
}
}
@Override
public void destroy() {
try {
if (sshjClient != null) {
sshjClient.disconnect();
sshjClient.close();
}
} catch (IOException e) {
logger.warn("Failed to stop sshj client for host " + sshjClient.getHost() + " and user " +
sshjClient.getUsername() + " due to : " + e.getMessage());
// ignore
}
}
@Override
public CommandOutput executeCommand(String command, String workingDirectory) throws AgentException {
SessionWrapper session = null;
try {
session = sshjClient.startSessionWrapper();
Session.Command exec = session.exec((workingDirectory != null ? "cd " + workingDirectory + "; " : "") + command);
StandardOutReader standardOutReader = new StandardOutReader();
try {
standardOutReader.readStdOutFromStream(exec.getInputStream());
standardOutReader.readStdErrFromStream(exec.getErrorStream());
} finally {
exec.close(); // closing the channel before getting the exit status
standardOutReader.setExitCode(Optional.ofNullable(exec.getExitStatus()).orElseThrow(() -> new Exception("Exit status received as null")));
}
return standardOutReader;
} catch (Exception e) {
if (e instanceof ConnectionException) {
Optional.ofNullable(session).ifPresent(ft -> ft.setErrored(true));
}
throw new AgentException(e);
} finally {
Optional.ofNullable(session).ifPresent(ss -> {
try {
ss.close();
} catch (IOException e) {
//Ignore
}
});
}
}
@Override
public void createDirectory(String path) throws AgentException {
createDirectory(path, false);
}
@Override
public void createDirectory(String path, boolean recursive) throws AgentException {
SFTPClientWrapper sftpClient = null;
try {
sftpClient = sshjClient.newSFTPClientWrapper();
if (recursive) {
sftpClient.mkdirs(path);
} else {
sftpClient.mkdir(path);
}
} catch (Exception e) {
if (e instanceof ConnectionException) {
Optional.ofNullable(sftpClient).ifPresent(ft -> ft.setErrored(true));
}
throw new AgentException(e);
} finally {
Optional.ofNullable(sftpClient).ifPresent(client -> {
try {
client.close();
} catch (IOException e) {
//Ignore
}
});
}
}
@Override
public void uploadFile(String localFile, String remoteFile) throws AgentException {
SCPFileTransferWrapper fileTransfer = null;
try {
fileTransfer = sshjClient.newSCPFileTransferWrapper();
fileTransfer.upload(localFile, remoteFile);
} catch (Exception e) {
if (e instanceof ConnectionException) {
Optional.ofNullable(fileTransfer).ifPresent(ft -> ft.setErrored(true));
}
throw new AgentException(e);
} finally {
Optional.ofNullable(fileTransfer).ifPresent(scpFileTransferWrapper -> {
try {
scpFileTransferWrapper.close();
} catch (IOException e) {
//Ignore
}
});
}
}
@Override
public void uploadFile(InputStream localInStream, FileMetadata metadata, String remoteFile) throws AgentException {
SCPFileTransferWrapper fileTransfer = null;
try {
fileTransfer = sshjClient.newSCPFileTransferWrapper();
fileTransfer.upload(new LocalSourceFile() {
@Override
public String getName() {
return metadata.getName();
}
@Override
public long getLength() {
return metadata.getSize();
}
@Override
public InputStream getInputStream() throws IOException {
return localInStream;
}
@Override
public int getPermissions() throws IOException {
return 420; //metadata.getPermissions();
}
@Override
public boolean isFile() {
return true;
}
@Override
public boolean isDirectory() {
return false;
}
@Override
public Iterable<? extends LocalSourceFile> getChildren(LocalFileFilter filter) throws IOException {
return null;
}
@Override
public boolean providesAtimeMtime() {
return false;
}
@Override
public long getLastAccessTime() throws IOException {
return 0;
}
@Override
public long getLastModifiedTime() throws IOException {
return 0;
}
}, remoteFile);
} catch (Exception e) {
if (e instanceof ConnectionException) {
Optional.ofNullable(fileTransfer).ifPresent(ft -> ft.setErrored(true));
}
throw new AgentException(e);
} finally {
Optional.ofNullable(fileTransfer).ifPresent(scpFileTransferWrapper -> {
try {
scpFileTransferWrapper.close();
} catch (IOException e) {
//Ignore
}
});
}
}
@Override
public void downloadFile(String remoteFile, String localFile) throws AgentException {
SCPFileTransferWrapper fileTransfer = null;
try {
fileTransfer = sshjClient.newSCPFileTransferWrapper();
fileTransfer.download(remoteFile, localFile);
} catch (Exception e) {
if (e instanceof ConnectionException) {
Optional.ofNullable(fileTransfer).ifPresent(ft -> ft.setErrored(true));
}
throw new AgentException(e);
} finally {
Optional.ofNullable(fileTransfer).ifPresent(scpFileTransferWrapper -> {
try {
scpFileTransferWrapper.close();
} catch (IOException e) {
//Ignore
}
});
}
}
@Override
public void downloadFile(String remoteFile, OutputStream localOutStream, FileMetadata metadata) throws AgentException {
SCPFileTransferWrapper fileTransfer = null;
try {
fileTransfer = sshjClient.newSCPFileTransferWrapper();
fileTransfer.download(remoteFile, new LocalDestFile() {
@Override
public OutputStream getOutputStream() throws IOException {
return localOutStream;
}
@Override
public LocalDestFile getChild(String name) {
return null;
}
@Override
public LocalDestFile getTargetFile(String filename) throws IOException {
return this;
}
@Override
public LocalDestFile getTargetDirectory(String dirname) throws IOException {
return null;
}
@Override
public void setPermissions(int perms) throws IOException {
}
@Override
public void setLastAccessedTime(long t) throws IOException {
}
@Override
public void setLastModifiedTime(long t) throws IOException {
}
});
} catch (Exception e) {
if (e instanceof ConnectionException) {
Optional.ofNullable(fileTransfer).ifPresent(ft -> ft.setErrored(true));
}
throw new AgentException(e);
} finally {
Optional.ofNullable(fileTransfer).ifPresent(scpFileTransferWrapper -> {
try {
scpFileTransferWrapper.close();
} catch (IOException e) {
//Ignore
}
});
}
}
@Override
public List<String> listDirectory(String path) throws AgentException {
SFTPClientWrapper sftpClient = null;
try {
sftpClient = sshjClient.newSFTPClientWrapper();
List<RemoteResourceInfo> ls = sftpClient.ls(path);
return ls.stream().map(RemoteResourceInfo::getName).collect(Collectors.toList());
} catch (Exception e) {
if (e instanceof ConnectionException) {
Optional.ofNullable(sftpClient).ifPresent(ft -> ft.setErrored(true));
}
throw new AgentException(e);
} finally {
Optional.ofNullable(sftpClient).ifPresent(client -> {
try {
client.close();
} catch (IOException e) {
//Ignore
}
});
}
}
@Override
public Boolean doesFileExist(String filePath) throws AgentException {
SFTPClientWrapper sftpClient = null;
try {
sftpClient = sshjClient.newSFTPClientWrapper();
return sftpClient.statExistence(filePath) != null;
} catch (Exception e) {
if (e instanceof ConnectionException) {
Optional.ofNullable(sftpClient).ifPresent(ft -> ft.setErrored(true));
}
throw new AgentException(e);
} finally {
Optional.ofNullable(sftpClient).ifPresent(client -> {
try {
client.close();
} catch (IOException e) {
//Ignore
}
});
}
}
@Override
public List<String> getFileNameFromExtension(String fileName, String parentPath) throws AgentException {
/*try (SFTPClient sftpClient = sshjClient.newSFTPClientWrapper()) {
List<RemoteResourceInfo> ls = sftpClient.ls(parentPath, resource -> isMatch(resource.getName(), fileName));
return ls.stream().map(RemoteResourceInfo::getPath).collect(Collectors.toList());
} catch (Exception e) {
throw new AgentException(e);
}*/
/*
if (fileName.endsWith("*")) {
throw new AgentException("Wildcards that ends with * does not support for security reasons. Specify an extension");
}
*/
CommandOutput commandOutput = executeCommand("ls " + fileName, parentPath); // This has a risk of returning folders also
String[] filesTmp = commandOutput.getStdOut().split("\n");
List<String> files = new ArrayList<>();
for (String f: filesTmp) {
if (!f.isEmpty()) {
files.add(f);
}
}
return files;
}
@Override
public FileMetadata getFileMetadata(String remoteFile) throws AgentException {
SFTPClientWrapper sftpClient = null;
try {
sftpClient = sshjClient.newSFTPClientWrapper();
FileAttributes stat = sftpClient.stat(remoteFile);
FileMetadata metadata = new FileMetadata();
metadata.setName(new File(remoteFile).getName());
metadata.setSize(stat.getSize());
metadata.setPermissions(FilePermission.toMask(stat.getPermissions()));
return metadata;
} catch (Exception e) {
if (e instanceof ConnectionException) {
Optional.ofNullable(sftpClient).ifPresent(ft -> ft.setErrored(true));
}
throw new AgentException(e);
} finally {
Optional.ofNullable(sftpClient).ifPresent(scpFileTransferWrapper -> {
try {
scpFileTransferWrapper.close();
} catch (IOException e) {
//Ignore
}
});
}
}
private boolean isMatch(String s, String p) {
int i = 0;
int j = 0;
int starIndex = -1;
int iIndex = -1;
while (i < s.length()) {
if (j < p.length() && (p.charAt(j) == '?' || p.charAt(j) == s.charAt(i))) {
++i;
++j;
} else if (j < p.length() && p.charAt(j) == '*') {
starIndex = j;
iIndex = i;
j++;
} else if (starIndex != -1) {
j = starIndex + 1;
i = iIndex+1;
iIndex++;
} else {
return false;
}
}
while (j < p.length() && p.charAt(j) == '*') {
++j;
}
return j == p.length();
}
}
| 630 |
0 | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix/adaptor/PoolingSSHJClient.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.helix.adaptor;
import net.schmizz.sshj.Config;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.DisconnectReason;
import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.sftp.RemoteFile;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.DisconnectListener;
import net.schmizz.sshj.transport.TransportException;
import net.schmizz.sshj.transport.verification.HostKeyVerifier;
import net.schmizz.sshj.userauth.UserAuthException;
import net.schmizz.sshj.userauth.method.AuthMethod;
import org.apache.airavata.helix.adaptor.wrapper.SCPFileTransferWrapper;
import org.apache.airavata.helix.adaptor.wrapper.SFTPClientWrapper;
import org.apache.airavata.helix.adaptor.wrapper.SSHClientWrapper;
import org.apache.airavata.helix.adaptor.wrapper.SessionWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Collectors;
/**
* This class will keep a pool of {@link SSHClient} and scale them according to the number of SSH requests.
* This pool is MaxSessions per connection aware and thread safe. It is intelligent to decide the number of connections
* that it should create and number of sessions should be used in each created connection to avoid possible connection
* refusals from the server side.
*/
public class PoolingSSHJClient extends SSHClient {
private final static Logger logger = LoggerFactory.getLogger(PoolingSSHJClient.class);
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Map<SSHClientWrapper, SSHClientInfo> clientInfoMap = new HashMap<>();
private HostKeyVerifier hostKeyVerifier;
private String username;
private List<AuthMethod> authMethods;
private Config config;
private String host;
private int port;
private int maxSessionsForConnection = 10;
private long maxConnectionIdleTimeMS = 10 * 60 * 1000;
public void addHostKeyVerifier(HostKeyVerifier verifier) {
this.hostKeyVerifier = verifier;
}
public void auth(String username, List<AuthMethod> methods) throws UserAuthException, TransportException {
this.username = username;
this.authMethods = methods;
}
public PoolingSSHJClient(Config config, String host, int port) {
this.config = config;
this.host = host;
this.port = port;
ScheduledExecutorService poolMonitoringService = Executors.newSingleThreadScheduledExecutor(r -> {
Thread thread = new Thread(r, "SSH-Pool-Monitor-" + host + "-" + port);
thread.setDaemon(true);
return thread;
});
poolMonitoringService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
removeStaleConnections();
}
}, 10, maxConnectionIdleTimeMS * 2, TimeUnit.MILLISECONDS);
}
////////////////// client specific operations ///////
private SSHClientWrapper newClientWithSessionValidation() throws IOException {
SSHClientWrapper newClient = createNewSSHClient();
SSHClientInfo info = new SSHClientInfo(1, System.currentTimeMillis(), clientInfoMap.size());
clientInfoMap.put(newClient, info);
/* if this is the very first connection that is created to the compute host, fetch the MaxSessions
* value form SSHD config file in order to tune the pool
*/
logger.info("Fetching max sessions for the connection of " + host);
try (SFTPClient sftpClient = newClient.newSFTPClient()) {
RemoteFile remoteFile = sftpClient.open("/etc/ssh/sshd_config");
byte[] readContent = new byte[(int) remoteFile.length()];
remoteFile.read(0, readContent, 0, readContent.length);
if (logger.isTraceEnabled()) {
logger.trace("SSHD config file content : " + new String(readContent));
}
String[] lines = new String(readContent).split("\n");
for (String line : lines) {
if (line.trim().startsWith("MaxSessions")) {
String[] splits = line.split(" ");
if (splits.length == 2) {
int sessionCount = Integer.parseInt(splits[1]);
logger.info("Max session count is : " + sessionCount + " for " + host);
setMaxSessionsForConnection(sessionCount);
}
break;
}
}
} catch (Exception e) {
logger.warn("Failed to fetch max session count for " + host + ". Continuing with default value 1. " + e.getMessage() );
}
return newClient;
}
private SSHClientWrapper leaseSSHClient() throws Exception {
lock.writeLock().lock();
try {
if (clientInfoMap.isEmpty()) {
return newClientWithSessionValidation();
} else {
Optional<Map.Entry<SSHClientWrapper, SSHClientInfo>> minEntryOp = clientInfoMap.entrySet().stream().min(Comparator.comparing(entry -> entry.getValue().sessionCount));
if (minEntryOp.isPresent()) {
Map.Entry<SSHClientWrapper, SSHClientInfo> minEntry = minEntryOp.get();
// use the connection with least amount of sessions created.
logger.debug("Session count for selected connection {} is {}. Threshold {} for host {}",
minEntry.getValue().getClientId(), minEntry.getValue().getSessionCount(), maxSessionsForConnection, host);
if (minEntry.getValue().getSessionCount() >= maxSessionsForConnection) {
// if it exceeds the maximum session count, create a new connection
logger.debug("Connection with least amount of sessions exceeds the threshold. So creating a new connection. " +
"Current connection count {} for host {}", clientInfoMap.size(), host);
return newClientWithSessionValidation();
} else {
// otherwise reuse the same connetion
logger.debug("Reusing the same connection {} as it doesn't exceed the threshold for host {}", minEntry.getValue().getClientId(), host);
minEntry.getValue().setSessionCount(minEntry.getValue().getSessionCount() + 1);
minEntry.getValue().setLastAccessedTime(System.currentTimeMillis());
SSHClientWrapper sshClient = minEntry.getKey();
if (!sshClient.isConnected() || !sshClient.isAuthenticated() || sshClient.isErrored()) {
logger.warn("Client for host {} is not connected or not authenticated. Creating a new client", host);
removeDisconnectedClients(sshClient, true);
return newClientWithSessionValidation();
} else {
return sshClient;
}
}
} else {
throw new Exception("Failed to find a connection in the pool for host " + host);
}
}
} finally {
lock.writeLock().unlock();
}
}
private void removeDisconnectedClients(SSHClientWrapper client, boolean doDisconnect) {
lock.writeLock().lock();
if (doDisconnect) {
try {
client.disconnect();
} catch (Exception e) {
log.warn("Errored while disconnecting the client " + e.getMessage());
// Ignore
}
}
try {
if (clientInfoMap.containsKey(client)) {
logger.debug("Removing the disconnected connection {} for host {}", clientInfoMap.get(client).getClientId(), host);
clientInfoMap.remove(client);
}
} finally {
lock.writeLock().unlock();
}
}
private void untrackClosedSessions(SSHClientWrapper client, int sessionId) {
lock.writeLock().lock();
try {
if (clientInfoMap.containsKey(client)) {
logger.debug("Removing the session for connection {} for host {}", clientInfoMap.get(client).getClientId(), host);
SSHClientInfo sshClientInfo = clientInfoMap.get(client);
sshClientInfo.setSessionCount(sshClientInfo.getSessionCount() - 1);
}
} finally {
lock.writeLock().unlock();
}
}
private void removeStaleConnections() {
List<Map.Entry<SSHClientWrapper, SSHClientInfo>> entriesTobeRemoved;
lock.writeLock().lock();
logger.info("Current active connections for {} @ {} : {} are {}", username, host, port, clientInfoMap.size());
try {
entriesTobeRemoved = clientInfoMap.entrySet().stream().filter(entry ->
((entry.getValue().getSessionCount() == 0) &&
(entry.getValue().getLastAccessedTime() + maxConnectionIdleTimeMS < System.currentTimeMillis()))).collect(Collectors.toList());
entriesTobeRemoved.forEach(entry -> {
logger.info("Removing connection {} due to inactivity for host {}", entry.getValue().getClientId(), host);
clientInfoMap.remove(entry.getKey());
});
} finally {
lock.writeLock().unlock();
}
entriesTobeRemoved.forEach(entry -> {
try {
entry.getKey().disconnect();
} catch (IOException e) {
logger.warn("Failed to disconnect connection {} for host {}", entry.getValue().clientId, host);
}
});
}
private SSHClientWrapper createNewSSHClient() throws IOException {
SSHClientWrapper sshClient;
if (config != null) {
sshClient = new SSHClientWrapper(config);
} else {
sshClient = new SSHClientWrapper();
}
sshClient.getConnection().getTransport().setDisconnectListener(new DisconnectListener() {
@Override
public void notifyDisconnect(DisconnectReason reason, String message) {
logger.warn("Connection disconnected " + message + " due to " + reason.name());
removeDisconnectedClients(sshClient, false);
}
});
if (hostKeyVerifier != null) {
sshClient.addHostKeyVerifier(hostKeyVerifier);
}
sshClient.connect(host, port);
sshClient.getConnection().getKeepAlive().setKeepAliveInterval(5); //send keep alive signal every 5sec
if (authMethods != null) {
sshClient.auth(username, authMethods);
}
return sshClient;
}
public SessionWrapper startSessionWrapper() throws Exception {
final SSHClientWrapper sshClient = leaseSSHClient();
try {
return new SessionWrapper(sshClient.startSession(), (id) -> untrackClosedSessions(sshClient, id), sshClient);
} catch (Exception e) {
if (sshClient != null) {
// If it is a ConnectionExceptions, explicitly invalidate the client
if (e instanceof ConnectionException) {
sshClient.setErrored(true);
}
untrackClosedSessions(sshClient, -1);
}
throw e;
}
}
public SCPFileTransferWrapper newSCPFileTransferWrapper() throws Exception {
final SSHClientWrapper sshClient = leaseSSHClient();
try {
return new SCPFileTransferWrapper(sshClient.newSCPFileTransfer(), (id) -> untrackClosedSessions(sshClient, id), sshClient);
} catch (Exception e) {
if (sshClient != null) {
// If it is a ConnectionExceptions, explicitly invalidate the client
if (e instanceof ConnectionException) {
sshClient.setErrored(true);
}
untrackClosedSessions(sshClient, -1);
}
throw e;
}
}
public SFTPClientWrapper newSFTPClientWrapper() throws Exception {
final SSHClientWrapper sshClient = leaseSSHClient();
try {
return new SFTPClientWrapper(sshClient.newSFTPClient(), (id) -> untrackClosedSessions(sshClient, id), sshClient);
} catch (Exception e) {
if (sshClient != null) {
// If it is a ConnectionExceptions, explicitly invalidate the client
if (e instanceof ConnectionException) {
sshClient.setErrored(true);
}
untrackClosedSessions(sshClient, -1);
}
throw e;
}
}
public class SSHClientInfo {
private int sessionCount;
private long lastAccessedTime;
private int clientId;
public SSHClientInfo(int sessionCount, long lastAccessedTime, int clientId) {
this.sessionCount = sessionCount;
this.lastAccessedTime = lastAccessedTime;
this.clientId = clientId;
}
public int getSessionCount() {
return sessionCount;
}
public SSHClientInfo setSessionCount(int sessionCount) {
this.sessionCount = sessionCount;
return this;
}
public long getLastAccessedTime() {
return lastAccessedTime;
}
public SSHClientInfo setLastAccessedTime(long lastAccessedTime) {
this.lastAccessedTime = lastAccessedTime;
return this;
}
public int getClientId() {
return clientId;
}
public void setClientId(int clientId) {
this.clientId = clientId;
}
}
public HostKeyVerifier getHostKeyVerifier() {
return hostKeyVerifier;
}
public PoolingSSHJClient setHostKeyVerifier(HostKeyVerifier hostKeyVerifier) {
this.hostKeyVerifier = hostKeyVerifier;
return this;
}
public String getUsername() {
return username;
}
public PoolingSSHJClient setUsername(String username) {
this.username = username;
return this;
}
public Config getConfig() {
return config;
}
public PoolingSSHJClient setConfig(Config config) {
this.config = config;
return this;
}
public String getHost() {
return host;
}
public PoolingSSHJClient setHost(String host) {
this.host = host;
return this;
}
public int getPort() {
return port;
}
public PoolingSSHJClient setPort(int port) {
this.port = port;
return this;
}
public int getMaxSessionsForConnection() {
return maxSessionsForConnection;
}
public PoolingSSHJClient setMaxSessionsForConnection(int maxSessionsForConnection) {
this.maxSessionsForConnection = maxSessionsForConnection;
return this;
}
public Map<SSHClientWrapper, SSHClientInfo> getClientInfoMap() {
return clientInfoMap;
}
}
| 631 |
0 | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix/adaptor | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix/adaptor/wrapper/SCPFileTransferWrapper.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.helix.adaptor.wrapper;
import net.schmizz.sshj.xfer.FileTransfer;
import net.schmizz.sshj.xfer.LocalDestFile;
import net.schmizz.sshj.xfer.LocalSourceFile;
import net.schmizz.sshj.xfer.TransferListener;
import net.schmizz.sshj.xfer.scp.SCPFileTransfer;
import java.io.Closeable;
import java.io.IOException;
import java.util.function.Consumer;
public class SCPFileTransferWrapper implements FileTransfer, Closeable {
private SCPFileTransfer scpFileTransfer;
private Consumer<Integer> onCloseFunction;
private SSHClientWrapper originalSSHClient;
public SCPFileTransferWrapper(SCPFileTransfer scpFileTransfer, Consumer<Integer> onCloseFunction, SSHClientWrapper originalSSHClient) {
this.scpFileTransfer = scpFileTransfer;
this.onCloseFunction = onCloseFunction;
this.originalSSHClient = originalSSHClient;
}
@Override
public void upload(String localPath, String remotePath) throws IOException {
scpFileTransfer.upload(localPath, remotePath);
}
@Override
public void download(String remotePath, String localPath) throws IOException {
scpFileTransfer.download(remotePath, localPath);
}
@Override
public void upload(LocalSourceFile localFile, String remotePath) throws IOException {
scpFileTransfer.upload(localFile, remotePath);
}
@Override
public void download(String remotePath, LocalDestFile localFile) throws IOException {
scpFileTransfer.download(remotePath, localFile);
}
@Override
public TransferListener getTransferListener() {
return scpFileTransfer.getTransferListener();
}
@Override
public void setTransferListener(TransferListener listener) {
scpFileTransfer.setTransferListener(listener);
}
@Override
public void close() throws IOException {
onCloseFunction.accept(-1);
}
public boolean isErrored() {
return originalSSHClient.isErrored();
}
public void setErrored(boolean errored) {
this.originalSSHClient.setErrored(errored);
}
}
| 632 |
0 | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix/adaptor | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix/adaptor/wrapper/SSHClientWrapper.java | package org.apache.airavata.helix.adaptor.wrapper;
import net.schmizz.sshj.Config;
import net.schmizz.sshj.SSHClient;
public class SSHClientWrapper extends SSHClient {
public SSHClientWrapper() {
super();
}
public SSHClientWrapper(Config config) {
super(config);
}
private boolean errored = false;
public boolean isErrored() {
return errored;
}
public void setErrored(boolean errored) {
this.errored = errored;
}
}
| 633 |
0 | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix/adaptor | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix/adaptor/wrapper/SFTPClientWrapper.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.helix.adaptor.wrapper;
import net.schmizz.sshj.sftp.SFTPClient;
import java.io.IOException;
import java.util.function.Consumer;
public class SFTPClientWrapper extends SFTPClient {
private Consumer<Integer> onCloseFunction;
private SSHClientWrapper originalSSHClient;
public SFTPClientWrapper(SFTPClient sftpClient, Consumer<Integer> onCloseFunction, SSHClientWrapper originalSSHClient) {
super(sftpClient.getSFTPEngine());
this.onCloseFunction = onCloseFunction;
this.originalSSHClient = originalSSHClient;
}
@Override
public void close() throws IOException {
onCloseFunction.accept(-1);
super.close();
}
public boolean isErrored() {
return originalSSHClient.isErrored();
}
public void setErrored(boolean errored) {
this.originalSSHClient.setErrored(errored);
}
}
| 634 |
0 | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix/adaptor | Create_ds/airavata/modules/airavata-helix/agent-impl/sshj-agent/src/main/java/org/apache/airavata/helix/adaptor/wrapper/SessionWrapper.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.helix.adaptor.wrapper;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.Message;
import net.schmizz.sshj.common.SSHException;
import net.schmizz.sshj.common.SSHPacket;
import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.connection.channel.direct.PTYMode;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.transport.TransportException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
public class SessionWrapper implements Session {
private Session session;
private Consumer<Integer> onCloseFunction;
private SSHClientWrapper originalSSHClient;
public SessionWrapper(Session session, Consumer<Integer> onCloseFunction, SSHClientWrapper originalSSHClient) {
this.session = session;
this.onCloseFunction = onCloseFunction;
this.originalSSHClient = originalSSHClient;
}
@Override
public void allocateDefaultPTY() throws ConnectionException, TransportException {
session.allocateDefaultPTY();
}
@Override
public void allocatePTY(String term, int cols, int rows, int width, int height, Map<PTYMode, Integer> modes) throws ConnectionException, TransportException {
session.allocatePTY(term, cols, rows, width, height, modes);
}
@Override
public Command exec(String command) throws ConnectionException, TransportException {
return session.exec(command);
}
@Override
public void reqX11Forwarding(String authProto, String authCookie, int screen) throws ConnectionException, TransportException {
session.reqX11Forwarding(authProto, authCookie, screen);
}
@Override
public void setEnvVar(String name, String value) throws ConnectionException, TransportException {
session.setEnvVar(name, value);
}
@Override
public Shell startShell() throws ConnectionException, TransportException {
return session.startShell();
}
@Override
public Subsystem startSubsystem(String name) throws ConnectionException, TransportException {
return session.startSubsystem(name);
}
@Override
public void close() throws TransportException, ConnectionException {
onCloseFunction.accept(getID());
session.close();
}
@Override
public boolean getAutoExpand() {
return session.getAutoExpand();
}
@Override
public int getID() {
return session.getID();
}
@Override
public InputStream getInputStream() {
return session.getInputStream();
}
@Override
public int getLocalMaxPacketSize() {
return session.getLocalMaxPacketSize();
}
@Override
public long getLocalWinSize() {
return session.getLocalWinSize();
}
@Override
public OutputStream getOutputStream() {
return session.getOutputStream();
}
@Override
public int getRecipient() {
return session.getRecipient();
}
@Override
public Charset getRemoteCharset() {
return session.getRemoteCharset();
}
@Override
public int getRemoteMaxPacketSize() {
return session.getRemoteMaxPacketSize();
}
@Override
public long getRemoteWinSize() {
return session.getRemoteWinSize();
}
@Override
public String getType() {
return session.getType();
}
@Override
public boolean isOpen() {
return session.isOpen();
}
@Override
public void setAutoExpand(boolean autoExpand) {
session.setAutoExpand(autoExpand);
}
@Override
public void join() throws ConnectionException {
session.join();
}
@Override
public void join(long timeout, TimeUnit unit) throws ConnectionException {
session.join(timeout, unit);
}
@Override
public boolean isEOF() {
return session.isEOF();
}
@Override
public LoggerFactory getLoggerFactory() {
return session.getLoggerFactory();
}
@Override
public void notifyError(SSHException error) {
session.notifyError(error);
}
@Override
public void handle(Message msg, SSHPacket buf) throws SSHException {
session.handle(msg, buf);
}
public boolean isErrored() {
return originalSSHClient.isErrored();
}
public void setErrored(boolean errored) {
this.originalSSHClient.setErrored(errored);
}
}
| 635 |
0 | Create_ds/airavata/modules/server/src/main/java/org/apache/airavata | Create_ds/airavata/modules/server/src/main/java/org/apache/airavata/server/ServerMain.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.server;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.*;
import org.apache.airavata.common.utils.ApplicationSettings.ShutdownStrategy;
import org.apache.airavata.common.utils.IServer.ServerStatus;
import org.apache.airavata.common.utils.StringUtil.CommandLineParameters;
import org.apache.airavata.patform.monitoring.MonitoringServer;
import org.apache.commons.cli.ParseException;
import org.apache.zookeeper.server.ServerCnxnFactory;
import org.slf4j.ILoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ServerMain {
private static List<IServer> servers;
private static final String SERVERS_KEY="servers";
private final static Logger logger = LoggerFactory.getLogger(ServerMain.class);
private static boolean serversLoaded=false;
private static final String stopFileNamePrefix = "server_stop";
private static long serverPID=-1;
private static final String serverStartedFileNamePrefix = "server_start";
private static boolean systemShutDown=false;
private static String STOP_COMMAND_STR = "stop";
private static final String ALL_IN_ONE = "all";
private static final String API_ORCH = "api-orch";
private static final String EXECUTION = "execution";
// server names
private static final String API_SERVER = "apiserver";
private static final String CREDENTIAL_STORE = "credentialstore";
private static final String REGISTRY_SERVER = "regserver";
private static final String SHARING_SERVER = "sharing_server";
private static final String GFAC_SERVER = "gfac";
private static final String ORCHESTRATOR = "orchestrator";
private static final String PROFILE_SERVICE = "profile_service";
private static final String DB_EVENT_MANAGER = "db_event_manager";
private static ServerCnxnFactory cnxnFactory;
// private static boolean shutdownHookCalledBefore=false;
static{
servers = new ArrayList<IServer>();
}
private static void loadServers(String serverNames) {
try {
if (serverNames != null) {
List<String> serversList = handleServerDependencies(serverNames);
for (String serverString : serversList) {
serverString = serverString.trim();
String serverClassName = ServerSettings.getSetting(serverString);
Class<?> classInstance;
try {
classInstance = ServerMain.class
.getClassLoader().loadClass(
serverClassName);
servers.add((IServer) classInstance.newInstance());
} catch (ClassNotFoundException e) {
logger.error("Error while locating server implementation \"" + serverString + "\"!!!", e);
} catch (InstantiationException e) {
logger.error("Error while initiating server instance \"" + serverString + "\"!!!", e);
} catch (IllegalAccessException e) {
logger.error("Error while initiating server instance \"" + serverString + "\"!!!", e);
} catch (ClassCastException e) {
logger.error("Invalid server \"" + serverString + "\"!!!", e);
}
}
} else {
logger.warn("No server name specify to start, use -h command line option to view help menu ...");
}
} catch (ApplicationSettingsException e) {
logger.error("Error while retrieving server list!!!",e);
}
serversLoaded=true;
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
setSystemShutDown(true);
stopAllServers();
}
});
}
private static List<String> handleServerDependencies(String serverNames) {
List<String> serverList = new ArrayList<>(Arrays.asList(serverNames.split(",")));
if (serverList.indexOf(ALL_IN_ONE) > -1) {
serverList.clear();
serverList.add(DB_EVENT_MANAGER); // DB Event Manager should start before everything
serverList.add(REGISTRY_SERVER); // registry server should start before everything else
serverList.add(CREDENTIAL_STORE); // credential store should start before api server
serverList.add(SHARING_SERVER);
serverList.add(API_SERVER);
serverList.add(ORCHESTRATOR);
serverList.add(GFAC_SERVER);
serverList.add(PROFILE_SERVICE);
} else if (serverList.indexOf(API_ORCH) > -1) {
serverList.clear();
serverList.add(DB_EVENT_MANAGER); // DB Event Manager should start before everything
serverList.add(REGISTRY_SERVER); // registry server should start before everything else
serverList.add(CREDENTIAL_STORE); // credential store should start before api server
serverList.add(SHARING_SERVER);
serverList.add(API_SERVER);
serverList.add(ORCHESTRATOR);
serverList.add(PROFILE_SERVICE);
} else if (serverList.indexOf(EXECUTION) > -1) {
serverList.clear();
serverList.add(GFAC_SERVER);
} else {
// registry server should start before everything
int regPos = serverList.indexOf(REGISTRY_SERVER);
if (regPos > 0) {
String temp = serverList.get(0);
serverList.set(0, serverList.get(regPos));
serverList.set(regPos, temp);
}
// credential store should start before api server
int credPos = serverList.indexOf(CREDENTIAL_STORE);
int apiPos = serverList.indexOf(API_SERVER);
if (credPos >= 0 && apiPos >= 0 && (credPos > apiPos)) {
String temp = serverList.get(apiPos);
serverList.set(apiPos, serverList.get(credPos));
serverList.set(credPos, temp);
}
}
return serverList;
}
// private static void addSecondaryShutdownHook(){
// Runtime.getRuntime().addShutdownHook(new Thread(){
// @Override
// public void run() {
// System.out.print("Graceful shutdown attempt is still active. Do you want to exit instead? (y/n)");
// String command=System.console().readLine().trim().toLowerCase();
// if (command.equals("yes") || command.equals("y")){
// System.exit(1);
// }
// }
// });
// }
public static void main(String args[]) throws IOException, AiravataException, ParseException {
ServerSettings.mergeSettingsCommandLineArgs(args);
ServerSettings.setServerRoles(ApplicationSettings.getSetting(SERVERS_KEY, "all").split(","));
if (ServerSettings.getBooleanSetting("api.server.monitoring.enabled")) {
MonitoringServer monitoringServer = new MonitoringServer(
ServerSettings.getSetting("api.server.monitoring.host"),
ServerSettings.getIntSetting("api.server.monitoring.port"));
monitoringServer.start();
Runtime.getRuntime().addShutdownHook(new Thread(monitoringServer::stop));
}
CommandLineParameters commandLineParameters = StringUtil.getCommandLineParser(args);
if (commandLineParameters.getArguments().contains(STOP_COMMAND_STR)){
performServerStopRequest(commandLineParameters);
} else {
performServerStart(args);
}
}
private static void performServerStart(String[] args) {
setServerStarted();
logger.info("Airavata server instance starting...");
for (String string : args) {
logger.info("Server Arguments: " + string);
}
String serverNames;
try {
serverNames = ApplicationSettings.getSetting(SERVERS_KEY);
startAllServers(serverNames);
} catch (ApplicationSettingsException e1) {
logger.error("Error finding servers property");
}
while(!hasStopRequested()){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
stopAllServers();
}
}
if (hasStopRequested()){
ServerSettings.setStopAllThreads(true);
stopAllServers();
ShutdownStrategy shutdownStrategy;
try {
shutdownStrategy = ServerSettings.getShutdownStrategy();
} catch (Exception e) {
String strategies="";
for(ShutdownStrategy s:ShutdownStrategy.values()){
strategies+="/"+s.toString();
}
logger.warn(e.getMessage());
logger.warn("Valid shutdown options are : "+strategies.substring(1));
shutdownStrategy=ShutdownStrategy.SELF_TERMINATE;
}
if (shutdownStrategy==ShutdownStrategy.SELF_TERMINATE) {
System.exit(0);
}
}
}
private static void performServerStopRequest(
CommandLineParameters commandLineParameters) throws IOException {
// deleteOldStartRecords();
String serverIndexOption = "serverIndex";
if (commandLineParameters.getParameters().containsKey(serverIndexOption)){
serverPID=Integer.parseInt(commandLineParameters.getParameters().get(serverIndexOption));
}
if (isServerRunning()) {
logger.info("Requesting airavata server"+(serverPID==-1? "(s)":" instance "+serverPID)+" to stop...");
requestStop();
while(isServerRunning()){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
logger.info("Server"+(serverPID==-1? "(s)":" instance "+serverPID)+" stopped!!!");
}else{
logger.error("Server"+(serverPID==-1? "":" instance "+serverPID)+" is not running!!!");
}
if (ServerSettings.isEmbeddedZK()) {
cnxnFactory.shutdown();
}
}
@SuppressWarnings("resource")
private static void requestStop() throws IOException {
File file = new File(getServerStopFileName());
file.createNewFile();
new RandomAccessFile(file, "rw").getChannel().lock();
file.deleteOnExit();
}
private static boolean hasStopRequested(){
return isSystemShutDown() || new File(getServerStopFileName()).exists() || new File(stopFileNamePrefix).exists();
}
private static String getServerStopFileName() {
return stopFileNamePrefix;
}
private static void deleteOldStopRequests(){
File[] files = new File(".").listFiles();
for (File file : files) {
if (file.getName().contains(stopFileNamePrefix)){
file.delete();
}
}
}
// private static void deleteOldStartRecords(){
// File[] files = new File(".").listFiles();
// for (File file : files) {
// if (file.getName().contains(serverStartedFileNamePrefix)){
// try {
// new FileOutputStream(file);
// file.delete();
// } catch (Exception e) {
// //file is locked which means there's an active process using it
// }
// }
// }
// }
private static boolean isServerRunning(){
if (serverPID==-1){
String[] files = new File(".").list();
for (String file : files) {
if (file.contains(serverStartedFileNamePrefix)){
return true;
}
}
return false;
}else{
return new File(getServerStartedFileName()).exists();
}
}
@SuppressWarnings({ "resource" })
private static void setServerStarted(){
try {
serverPID = getPID();
deleteOldStopRequests();
File serverStartedFile = null;
serverStartedFile = new File(getServerStartedFileName());
serverStartedFile.createNewFile();
serverStartedFile.deleteOnExit();
new RandomAccessFile(serverStartedFile,"rw").getChannel().lock();
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
private static String getServerStartedFileName() {
return new File(new File(System.getenv("AIRAVATA_HOME"),"bin"),serverStartedFileNamePrefix+"_"+Long.toString(serverPID)).toString();
}
public static void stopAllServers() {
//stopping should be done in reverse order of starting the servers
for(int i=servers.size()-1;i>=0;i--){
try {
servers.get(i).stop();
waitForServerToStop(servers.get(i),null);
} catch (Exception e) {
logger.error("Server Stop Error:",e);
}
}
}
public static void startAllServers(String serversNames) {
if (!serversLoaded){
loadServers(serversNames);
}
for (IServer server : servers) {
try {
server.configure();
server.start();
waitForServerToStart(server,null);
} catch (Exception e) {
logger.error("Server Start Error:",e);
}
}
}
private static final int SERVER_STATUS_CHANGE_WAIT_INTERVAL=500;
private static void waitForServerToStart(IServer server,Integer maxWait) throws Exception {
int count=0;
// if (server.getStatus()==ServerStatus.STARTING) {
// logger.info("Waiting for " + server.getName() + " to start...");
// }
while(server.getStatus()==ServerStatus.STARTING && (maxWait==null || count<maxWait)){
Thread.sleep(SERVER_STATUS_CHANGE_WAIT_INTERVAL);
count+=SERVER_STATUS_CHANGE_WAIT_INTERVAL;
}
if (server.getStatus()!= ServerStatus.STARTED){
logger.error("The "+server.getName()+" did not start!!!");
}
}
private static void waitForServerToStop(IServer server,Integer maxWait) throws Exception {
int count=0;
if (server.getStatus()==ServerStatus.STOPING) {
logger.info("Waiting for " + server.getName() + " to stop...");
}
//we are doing hasStopRequested() check because while we are stuck in the loop to stop there could be a forceStop request
while(server.getStatus()==ServerStatus.STOPING && (maxWait==null || count<maxWait)){
Thread.sleep(SERVER_STATUS_CHANGE_WAIT_INTERVAL);
count+=SERVER_STATUS_CHANGE_WAIT_INTERVAL;
}
if (server.getStatus()!=ServerStatus.STOPPED){
logger.error("Error stopping the "+server.getName()+"!!!");
}
}
private static boolean isSystemShutDown() {
return systemShutDown;
}
private static void setSystemShutDown(boolean systemShutDown) {
ServerMain.systemShutDown = systemShutDown;
}
// private static int getPID(){
// try {
// java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory
// .getRuntimeMXBean();
// java.lang.reflect.Field jvm = runtime.getClass()
// .getDeclaredField("jvm");
// jvm.setAccessible(true);
// sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm
// .get(runtime);
// java.lang.reflect.Method pid_method = mgmt.getClass()
// .getDeclaredMethod("getProcessId");
// pid_method.setAccessible(true);
//
// int pid = (Integer) pid_method.invoke(mgmt);
// return pid;
// } catch (Exception e) {
// return -1;
// }
// }
//getPID from ProcessHandle JDK 9 and onwards
private static long getPID () {
try {
return ProcessHandle.current().pid();
} catch (Exception e) {
return -1;
}
}
} | 636 |
0 | Create_ds/airavata/modules/ide-integration/src/main/java/org/apache/airavata/ide | Create_ds/airavata/modules/ide-integration/src/main/java/org/apache/airavata/ide/integration/JobEngineStarter.java | package org.apache.airavata.ide.integration;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.helix.core.AbstractTask;
import org.apache.airavata.helix.impl.controller.HelixController;
import org.apache.airavata.helix.impl.participant.GlobalParticipant;
import org.apache.airavata.helix.impl.workflow.PostWorkflowManager;
import org.apache.airavata.helix.impl.workflow.PreWorkflowManager;
import org.apache.airavata.monitor.email.EmailBasedMonitor;
import org.apache.helix.manager.zk.ZKHelixAdmin;
import org.apache.helix.manager.zk.ZNRecordSerializer;
import org.apache.helix.manager.zk.ZkClient;
import java.util.ArrayList;
public class JobEngineStarter {
public static void main(String args[]) throws Exception {
ZkClient zkClient = new ZkClient(ServerSettings.getZookeeperConnection(), ZkClient.DEFAULT_SESSION_TIMEOUT,
ZkClient.DEFAULT_CONNECTION_TIMEOUT, new ZNRecordSerializer());
ZKHelixAdmin zkHelixAdmin = new ZKHelixAdmin(zkClient);
zkHelixAdmin.addCluster(ServerSettings.getSetting("helix.cluster.name"), true);
System.out.println("Starting Helix Controller .......");
// Starting helix controller
HelixController controller = new HelixController();
controller.startServer();
ArrayList<Class<? extends AbstractTask>> taskClasses = new ArrayList<>();
for (String taskClassName : GlobalParticipant.TASK_CLASS_NAMES) {
taskClasses.add(Class.forName(taskClassName).asSubclass(AbstractTask.class));
}
System.out.println("Starting Helix Participant .......");
// Starting helix participant
GlobalParticipant participant = new GlobalParticipant(taskClasses, null);
participant.startServer();
System.out.println("Starting Pre Workflow Manager .......");
PreWorkflowManager preWorkflowManager = new PreWorkflowManager();
preWorkflowManager.startServer();
System.out.println("Starting Post Workflow Manager .......");
PostWorkflowManager postWorkflowManager = new PostWorkflowManager();
postWorkflowManager.startServer();
}
}
| 637 |
0 | Create_ds/airavata/modules/ide-integration/src/main/java/org/apache/airavata/ide | Create_ds/airavata/modules/ide-integration/src/main/java/org/apache/airavata/ide/integration/APIServerStarter.java | package org.apache.airavata.ide.integration;
import org.apache.airavata.api.server.AiravataAPIServer;
import org.apache.airavata.credential.store.server.CredentialStoreServer;
import org.apache.airavata.db.event.manager.DBEventManagerRunner;
import org.apache.airavata.orchestrator.server.OrchestratorServer;
import org.apache.airavata.registry.api.service.RegistryAPIServer;
import org.apache.airavata.service.profile.server.ProfileServiceServer;
import org.apache.airavata.sharing.registry.server.SharingRegistryServer;
public class APIServerStarter {
public static void main(String args[]) throws Exception {
DBEventManagerRunner dbEventManagerRunner = new DBEventManagerRunner();
RegistryAPIServer registryAPIServer = new RegistryAPIServer();
CredentialStoreServer credentialStoreServer = new CredentialStoreServer();
SharingRegistryServer sharingRegistryServer = new SharingRegistryServer();
AiravataAPIServer airavataAPIServer = new AiravataAPIServer();
OrchestratorServer orchestratorServer = new OrchestratorServer();
ProfileServiceServer profileServiceServer = new ProfileServiceServer();
dbEventManagerRunner.start();
registryAPIServer.start();
credentialStoreServer.start();
sharingRegistryServer.start();
airavataAPIServer.start();
orchestratorServer.start();
profileServiceServer.start();
}
}
| 638 |
0 | Create_ds/airavata/modules/ide-integration/src/main/java/org/apache/airavata/ide | Create_ds/airavata/modules/ide-integration/src/main/java/org/apache/airavata/ide/integration/JobMonitorStarter.java | package org.apache.airavata.ide.integration;
import org.apache.airavata.monitor.email.EmailBasedMonitor;
public class JobMonitorStarter {
public static void main(String args[]) throws Exception {
EmailBasedMonitor emailBasedMonitor = new EmailBasedMonitor();
emailBasedMonitor.startServer();
}
}
| 639 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/AmberSanderBR2.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Amber Application on BR2**********
* Created by Eroma on 9/12/14.
* The script generates Amber application execution on BR2
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/23/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class AmberSanderBR2 extends UserLogin {
private WebDriver driver;
private String subUrl;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testAmberSanderBR2() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
waitTime (200);
driver.findElement(By.id("experiment-name")).sendKeys(expName +"AmberSander-BR2");
driver.findElement(By.id("experiment-description")).clear();
waitTime (200);
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Amber_Sander");
waitTime (200);
driver.findElement(By.name("continue")).click();
driver.findElement(By.id("Heat-Restart-File")).sendKeys(ExpFileReadUtils.AMBER_INPUT1);
waitTime (200);
driver.findElement(By.id("Parameter-Topology-File")).sendKeys(ExpFileReadUtils.AMBER_INPUT2);
waitTime (200);
driver.findElement(By.id("Production-Control-File")).sendKeys(ExpFileReadUtils.AMBER_INPUT3);
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("bigred2.uits.iu.edu");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).clear();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 640 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/GaussianGordon.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Gaussian Application on Gordon**********
* Created by Eroma on 9/16/14.
* The script generates NwChem application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class GaussianGordon extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String path = null;
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
path = ExpFileReadUtils.readProperty("local.path");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testGaussianGordon() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "Gaussian-Gordon");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime (200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Gaussian");
waitTime (200);
driver.findElement(By.name("continue")).click();
waitTime (200);
driver.findElement(By.id("Gaussian-Input-File")).sendKeys(ExpFileReadUtils.GAUSSIAN_INPUT2);
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("gordon.sdsc.edu");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).clear();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 641 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/SearchProjectExp.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Search for Project which has Experiments executed**********
* Created by Eroma on 9/16/14.
* The script will search for a project which will list all experiments created; can view the experiment status
* project-name is read from exp.properties file
* Changed by Eroma to read the base URL and sub URL from exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class SearchProjectExp extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String projectName;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
projectName = ExpFileReadUtils.readProperty("project.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testSearchProjectExp() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Project")).click();
driver.findElement(By.id("browse")).click();
new Select(driver.findElement(By.id("search-key"))).selectByVisibleText("Project Name");
driver.findElement(By.id("search-value")).clear();
driver.findElement(By.id("search-value")).sendKeys(projectName);
driver.findElement(By.name("search")).click();
try {
assertTrue(isElementPresent(By.cssSelector("td")));
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
assertEquals(projectName, driver.findElement(By.cssSelector("td")).getText());
} catch (Error e) {
verificationErrors.append(e.toString());
}
driver.findElement(By.linkText("View")).click();
waitTime (30000);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 642 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/AmberSanderComet.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Amber Application on Comet**********
* Created by Eroma on 9/16/14.
* The script generates Amber application execution on Trestles
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/23/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class AmberSanderComet extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testAmberSanderComet() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
waitTime (200);
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "AmberSander-Comet");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime (200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Amber_Sander");
waitTime (200);
driver.findElement(By.name("continue")).click();
waitTime (200);
driver.findElement(By.id("Heat-Restart-File")).sendKeys(ExpFileReadUtils.AMBER_INPUT1);
waitTime (200);
driver.findElement(By.id("Parameter-Topology-File")).sendKeys(ExpFileReadUtils.AMBER_INPUT2);
waitTime (200);
driver.findElement(By.id("Production-Control-File")).sendKeys(ExpFileReadUtils.AMBER_INPUT3);
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("comet.sdsc.edu");
waitTime (200);
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).clear();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 643 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/GaussianComet.java | package org.apache.airavata.pga.tests;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.fail;
/*
**********Executing Gaussian Application on Comet**********
* Created by Eroma on 9/16/14.
* The script generates NwChem application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class GaussianComet extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String path = null;
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
path = ExpFileReadUtils.readProperty("local.path");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testGaussianComet() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "Gaussian-Comet");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime (200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Gaussian");
waitTime (200);
driver.findElement(By.name("continue")).click();
waitTime (200);
driver.findElement(By.id("Gaussian-Input-File")).sendKeys(ExpFileReadUtils.GAUSSIAN_INPUT1);
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("comet.sdsc.edu");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("compute");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 644 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/NwChemStampede.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing NwChem Application on Stampede**********
* Created by Eroma on 9/16/14.
* The script generates NwChem application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class NwChemStampede extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testNwChemStampede() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "NwChem-Stampede");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime (200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("NWChem");
waitTime (200);
driver.findElement(By.name("continue")).click();
waitTime (200);
driver.findElement(By.id("Water-Molecule-Input")).sendKeys(ExpFileReadUtils.NWCHEM_INPUT1);
waitTime (200);
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("stampede.tacc.xsede.org");
waitTime (500);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("development");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).clear();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 645 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/AutoDockBR2.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Amber Application on BR2**********
* Created by Eroma on 9/12/14.
* The script generates Amber application execution on BR2
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/23/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class AutoDockBR2 extends UserLogin {
private WebDriver driver;
private String subUrl;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testAutoDockBR2() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
waitTime (200);
driver.findElement(By.id("experiment-name")).sendKeys(expName +"AutoDock-BR2");
driver.findElement(By.id("experiment-description")).clear();
waitTime (200);
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("AutoDock");
waitTime (200);
driver.findElement(By.name("continue")).click();
driver.findElement(By.id("Autodock-Input")).sendKeys(ExpFileReadUtils.AUTODOCK_INPUT1);
waitTime (200);
driver.findElement(By.id("Autodock-Data")).sendKeys(ExpFileReadUtils.AUTODOCK_INPUT2);
waitTime (200);
driver.findElement(By.id("HSG1-Maps-FLD")).sendKeys(ExpFileReadUtils.AUTODOCK_INPUT3);
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("bigred2.uits.iu.edu");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).clear();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 646 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/GromacsStampede.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Gromacs Application on Stampede**********
* Created by Eroma on 9/16/14.
* The script generates Gromacs application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class GromacsStampede extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String path = null;
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
path = ExpFileReadUtils.readProperty("local.path");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testGromacsStampede() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "Gromacs-Stampede");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime (200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Gromacs");
waitTime (200);
driver.findElement(By.name("continue")).click();
waitTime (200);
driver.findElement(By.id("Portable-Input-Binary-File")).sendKeys(ExpFileReadUtils.GROMACS_INPUT1);
waitTime (200);
driver.findElement(By.id("GROMOS-Coordinate-file")).sendKeys(ExpFileReadUtils.GROMACS_INPUT2);
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("stampede.tacc.xsede.org");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("development");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 647 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/PhastaPStampede.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Phasta_P Application on Stampede**********
* Created by Eroma on 10/21/14.
* The script generates Phasta application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class PhastaPStampede extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testPhastaPStampede() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "PhastaP-Stampede");
waitTime(200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime(200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Phasta_P");
waitTime (200);
driver.findElement(By.name("continue")).click();
driver.findElement(By.id("Parasolid-Geometric-Model")).sendKeys(ExpFileReadUtils.PHASTA_INPUT1);
driver.findElement(By.id("Problem-Definition")).sendKeys(ExpFileReadUtils.PHASTA_INPUT2);
driver.findElement(By.id("Mesh-Description-file")).sendKeys(ExpFileReadUtils.PHASTA_INPUT3);
driver.findElement(By.id("Solver-Input-Paramaters")).sendKeys(ExpFileReadUtils.PHASTA_INPUT4);
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("stampede.tacc.xsede.org");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).clear();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
/*driver.findElement(By.cssSelector("span.glyphicon.glyphicon-refresh")).click();
waitTime(200);*/
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 648 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/TrinityStampede.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Trinity Application on Stampede**********
* Created by Eroma on 9/16/14.
* The script generates Trinity application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class TrinityStampede extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testTrinityStampede() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "Trinity-Stampede");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime(200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime(200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Trinity");
waitTime(200);
driver.findElement(By.name("continue")).click();
waitTime(200);
driver.findElement(By.id("Seq_Type")).clear();
driver.findElement(By.id("Seq_Type")).sendKeys("fq");
waitTime(200);
driver.findElement(By.id("JM")).clear();
driver.findElement(By.id("JM")).sendKeys("2G");
waitTime(200);
driver.findElement(By.id("RNA-Seq-Left-Input")).sendKeys(ExpFileReadUtils.TRINITY_INPUT1);
waitTime(200);
driver.findElement(By.id("RNA-Seq-Right-Input")).sendKeys(ExpFileReadUtils.TRINITY_INPUT2);
waitTime (200);
driver.findElement(By.id("SS-Lib-Type")).clear();
driver.findElement(By.id("SS-Lib-Type")).sendKeys("RF");
waitTime (200);
driver.findElement(By.id("CPU")).clear();
driver.findElement(By.id("CPU")).sendKeys("4");
waitTime (200);
driver.findElement(By.id("Max-HeapSpace")).clear();
driver.findElement(By.id("Max-HeapSpace")).sendKeys("2G");
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("stampede.tacc.xsede.org");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 649 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/UserLogout.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
/*
**********User Logout from PHP-Reference-Gateway**********
* Created by Eroma on 9/12/14.
* User logout from the to PHP-Reference-Gateway
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
*/
public class UserLogout extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testUserLogout() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Log out")).click();
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
}
| 650 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/GamessGordon.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Gamess Application on Gordon**********
* Created by Eroma on 9/16/14.
* The script generates Trinity application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class GamessGordon extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String path = null;
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
path = ExpFileReadUtils.readProperty("local.path");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testGamessGordon() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "Gamess-Gordon");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime(200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime(200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Gamess");
waitTime(200);
driver.findElement(By.name("continue")).click();
waitTime(200);
driver.findElement(By.id("Gamess-Input-File")).sendKeys(ExpFileReadUtils.GAMESS_INPUT1);
waitTime(200);
driver.findElement(By.id("Gamess-Version")).sendKeys("00");
waitTime (200);
driver.findElement(By.id("PPN")).clear();
driver.findElement(By.id("PPN")).sendKeys("4");
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("gordon.sdsc.edu");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).clear();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 651 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/RunAllTests.java | package org.apache.airavata.pga.tests;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.junit.Before;
import org.junit.Test;
/*
**********Executing All Tests on Airavata Applications**********
* Created by Eroma on 4/26/15.
* The script is to execute all aApplication experiments as a bundle.
* Updated to work with Latest PGA by Eroma 08/05/2015.
*/
public class RunAllTests extends UserLogin {
@Before
public void setUp() throws Exception {}
@Test
public void runAll() throws Exception {
System.out.println("============== Running all tests ==================");
long startTime = System.nanoTime();
System.out.println("Starting CreateModifySearchProject ...");
CreateModifySearchProject t0 = new CreateModifySearchProject();
t0.setUp();
t0.testCreateModifySearchProject();
t0.tearDown();
System.out.println("CreateModifySearchProject - Done");
/*System.out.println("Starting AmberSanderBR2 ...");
AmberSanderBR2 t1 = new AmberSanderBR2();
t1.setUp();
t1.testAmberSanderBR2();
t1.tearDown();
System.out.println("AmberSanderBR2 - Done");*/
System.out.println("Starting AmberSanderComet ...");
AmberSanderComet t2 = new AmberSanderComet();
t2.setUp();
t2.testAmberSanderComet();
t2.tearDown();
System.out.println("AmberSanderComet - Done");
System.out.println("Starting AmberSanderStampede ...");
AmberSanderStampede t3 = new AmberSanderStampede();
t3.setUp();
t3.testAmberSanderStampede();
t3.tearDown();
System.out.println("AmberSanderStampede - Done");
/*System.out.println("Starting AutoDockBR2 ...");
AutoDockBR2 t4 = new AutoDockBR2();
t4.setUp();
t4.testAutoDockBR2();
t4.tearDown();
System.out.println("AutoDockBR2 - Done");
System.out.println("Starting EchoBR2 ...");
EchoBR2 t5 = new EchoBR2();
t5.setUp();
t5.testEchoBR2();
t5.tearDown();
System.out.println("EchoBR2 - Done");*/
System.out.println("Starting EchoComet...");
EchoComet t6 = new EchoComet();
t6.setUp();
t6.testEchoComet();
t6.tearDown();
System.out.println("EchoTrestles - Done");
System.out.println("Starting EchoStampede ...");
EchoStampede t7 = new EchoStampede();
t7.setUp();
t7.testEchoStampede();
t7.tearDown();
System.out.println("EchoStampede - Done");
System.out.println("Starting EspressoStampede ...");
EspressoStampede t8 = new EspressoStampede();
t8.setUp();
t8.testEspressoStampede();
t8.tearDown();
System.out.println("EspressoStampede - Done");
System.out.println("Starting GamessGordon ...");
GamessGordon t9 = new GamessGordon();
t9.setUp();
t9.testGamessGordon();
t9.tearDown();
System.out.println("GamessGordon - Done");
System.out.println("Starting GaussianGordon ...");
GaussianGordon t10 = new GaussianGordon();
t10.setUp();
t10.testGaussianGordon();
t10.tearDown();
System.out.println("GaussianGordon - Done");
System.out.println("Starting GromacsStampede ...");
GromacsStampede t11 = new GromacsStampede();
t11.setUp();
t11.testGromacsStampede();
t11.tearDown();
System.out.println("GromacsStampede - Done");
System.out.println("Starting LammpsComet ...");
LammpsComet t12 = new LammpsComet();
t12.setUp();
t12.testLammpsComet();
t12.tearDown();
System.out.println("LammpsComet - Done");
System.out.println("Starting LammpsStampede ...");
LammpsStampede t13 = new LammpsStampede();
t13.setUp();
t13.testLammpsStampede();
t13.tearDown();
System.out.println("LammpsStampede - Done");
System.out.println("Starting NwChemComet ...");
NwChemComet t14 = new NwChemComet();
t14.setUp();
t14.testNwChemComet();
t14.tearDown();
System.out.println("NwChemComet - Done");
System.out.println("Starting NwChemStampede ...");
NwChemStampede t15 = new NwChemStampede();
t15.setUp();
t15.testNwChemStampede();
t15.tearDown();
System.out.println("NwChemStampede - Done");
System.out.println("Starting PhastaPStampede ...");
PhastaPStampede t16 = new PhastaPStampede();
t16.setUp();
t16.testPhastaPStampede();
t16.tearDown();
System.out.println("PhastaPStampede - Done");
System.out.println("Starting TinkerMonteStampede ...");
TinkerMonteStampede t17 = new TinkerMonteStampede();
t17.setUp();
t17.testTinkerMonteStampede();
t17.tearDown();
System.out.println("TinkerMonteStampede - Done");
/*System.out.println("Starting TrinityStampede ...");
TrinityStampede t18 = new TrinityStampede();
t18.setUp();
t18.testTrinityStampede();
t18.tearDown();
System.out.println("TrinityStampede - Done");*/
System.out.println("Starting WRFStampede ...");
WRFStampede t19 = new WRFStampede();
t19.setUp();
t19.testWRFStampede();
t19.tearDown();
System.out.println("WRFStampede - Done");
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("Time to execute Experiment Tests "
+ " : " + (duration / 1000000000)/60 + " minutes.");
System.out.println("==================== Done =========================");
}
}
| 652 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/AmberSanderStampede.java | package org.apache.airavata.pga.tests;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.*;
/*
**********Executing Amber Application on Stampede**********
* Created by Eroma on 9/15/14.
* The script generates Amber application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/23/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class AmberSanderStampede extends UserLogin {
private WebDriver driver;
private String subUrl;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testAmberSanderStampede() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "AmberSander-Stampede");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime (200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Amber_Sander");
waitTime (200);
driver.findElement(By.name("continue")).click();
waitTime (200);
driver.findElement(By.id("Heat-Restart-File")).sendKeys(ExpFileReadUtils.AMBER_INPUT1);
waitTime (200);
driver.findElement(By.id("Parameter-Topology-File")).sendKeys(ExpFileReadUtils.AMBER_INPUT2);
waitTime (200);
driver.findElement(By.id("Production-Control-File")).sendKeys(ExpFileReadUtils.AMBER_INPUT3);
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("stampede.tacc.xsede.org");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).clear();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 653 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/EchoComet.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Echo Application on Comet**********
* Created by Eroma on 9/16/14.
* The script generates Echo application execution on Trestles
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/23/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class EchoComet extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testEchoComet() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "Echo-Comet");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime (200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Echo");
waitTime (200);
driver.findElement(By.name("continue")).click();
waitTime (200);
driver.findElement(By.id("Input-to-Echo")).sendKeys("Echo Test");
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("comet.sdsc.edu");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 654 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/LammpsStampede.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Lammps Application on Stampede**********
* Created by Eroma on 9/16/14.
* The script generates Lammps application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class LammpsStampede extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String path = null;
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
path = ExpFileReadUtils.readProperty("local.path");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testLammpsStampede() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "Lammps-Stampede");
waitTime(200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime(200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime(200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Lammps");
waitTime(200);
driver.findElement(By.name("continue")).click();
waitTime(200);
driver.findElement(By.id("Friction-Simulation-Input")).sendKeys(ExpFileReadUtils.LAMMPS_INPUT1);
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("stampede.tacc.xsede.org");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
//driver.findElement(By.cssSelector("span.glyphicon.glyphicon-refresh")).click();
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 655 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/EchoBR2.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Echo Application on BR2**********
* Created by Airavata on 9/16/14.
* The script generates Echo application execution on BR2
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/23/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class EchoBR2 extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testEchoBR2() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "Echo-BR2");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime (200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Echo");
waitTime (200);
driver.findElement(By.name("continue")).click();
waitTime (200);
driver.findElement(By.id("Input_to_Echo")).clear();
driver.findElement(By.id("Input_to_Echo")).sendKeys("Echo Test");
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("bigred2.uits.iu.edu");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 656 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/EchoStampede.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Echo Application on Stampede**********
* Created by Eroma on 9/16/14.
* The script generates Echo application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/23/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class EchoStampede extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testEchoStampede() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
waitTime (200);
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "Echo-Stampede");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime (200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Echo");
waitTime (200);
driver.findElement(By.name("continue")).click();
waitTime (200);
driver.findElement(By.id("Input-to-Echo")).sendKeys("Echo Test");
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("stampede.tacc.xsede.org");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 657 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/EspressoStampede.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Espresso Application on Stampede**********
* Created by Eroma on 9/16/14.
* The script generates Espresso application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class EspressoStampede extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String path = null;
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
path = ExpFileReadUtils.readProperty("local.path");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testEspressoStampede() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
waitTime (200);
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "Espresso-Stampede");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime (200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Quantum Espresso");
waitTime (200);
driver.findElement(By.name("continue")).click();
waitTime (200);
driver.findElement(By.id("AI-Pseudopotential-file")).sendKeys(ExpFileReadUtils.ESPRESSO_INPUT2);
waitTime (200);
driver.findElement(By.id("AI-Primitive-Cell")).sendKeys(ExpFileReadUtils.ESPRESSO_INPUT1);
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("stampede.tacc.xsede.org");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 658 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/ExpLoadTest.java | package org.apache.airavata.pga.tests;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.junit.Before;
import org.junit.Test;
/*
**********Executing Load Tests on Airavata Applications**********
* Created by Eroma on 4/26/15.
* The script to be used in load testing using PGA gateway
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class ExpLoadTest extends UserLogin {
@Before
public void setUp() throws Exception {}
@Test
public void runAll() throws Exception {
System.out.println("============== Running all tests ==================");
long startTime = System.nanoTime();
int iterations1 = 1;
for (int i=0; i < iterations1; ++i) {
System.out.println("Starting AmberSanderBR2 iteration ...");
AmberSanderBR2 t1 = new AmberSanderBR2();
t1.setUp();
t1.testAmberSanderBR2();
t1.tearDown();
System.out.println("AmberSanderBR2 iteration - Done");
System.out.println("Starting AmberSanderStampede ...");
AmberSanderStampede t2 = new AmberSanderStampede();
t2.setUp();
t2.testAmberSanderStampede();
t2.tearDown();
System.out.println("AmberSanderStampede - Done");
System.out.println("Starting AmberSanderComet ...");
AmberSanderComet t3 = new AmberSanderComet();
t3.setUp();
t3.testAmberSanderComet();
t3.tearDown();
System.out.println("AmberSanderComet - Done");
System.out.println("Starting AutoDockBR2 ...");
AutoDockBR2 t4 = new AutoDockBR2();
t4.setUp();
t4.testAutoDockBR2();
t4.tearDown();
System.out.println("AutoDockBR2 - Done");
System.out.println("Starting EchoBR2 ...");
EchoBR2 t5 = new EchoBR2();
t5.setUp();
t5.testEchoBR2();
t5.tearDown();
System.out.println("EchoBR2 - Done");
System.out.println("Starting EchoStampede ...");
EchoStampede t6 = new EchoStampede();
t6.setUp();
t6.testEchoStampede();
t6.tearDown();
System.out.println("EchoStampede - Done");
System.out.println("Starting EchoComet ...");
EchoComet t7 = new EchoComet();
t7.setUp();
t7.testEchoComet();
t7.tearDown();
System.out.println("EchoComet - Done");
System.out.println("Starting EspressoStampede ...");
EspressoStampede t8 = new EspressoStampede();
t8.setUp();
t8.testEspressoStampede();
t8.tearDown();
System.out.println("EspressoStampede - Done");
System.out.println("Starting GamessGordon ...");
GamessGordon t9 = new GamessGordon();
t9.setUp();
t9.testGamessGordon();
t9.tearDown();
System.out.println("GamessGordon - Done");
System.out.println("Starting GaussianComet ...");
GaussianComet t10 = new GaussianComet();
t10.setUp();
t10.testGaussianComet();
t10.tearDown();
System.out.println("GaussianComet - Done");
System.out.println("Starting GaussianGordon ...");
GaussianGordon t11 = new GaussianGordon();
t11.setUp();
t11.testGaussianGordon();
t11.tearDown();
System.out.println("GaussianGordon - Done");
System.out.println("Starting GromacsStampede ...");
GromacsStampede t12 = new GromacsStampede();
t12.setUp();
t12.testGromacsStampede();
t12.tearDown();
System.out.println("GromacsStampede - Done");
System.out.println("Starting LammpsStampede ...");
LammpsStampede t13 = new LammpsStampede();
t13.setUp();
t13.testLammpsStampede();
t13.tearDown();
System.out.println("LammpsStampede - Done");
System.out.println("Starting LammpsComet ...");
LammpsComet t14 = new LammpsComet();
t14.setUp();
t14.testLammpsComet();
t14.tearDown();
System.out.println("LammpsComet - Done");
System.out.println("Starting NwChemStampede ...");
NwChemStampede t15 = new NwChemStampede();
t15.setUp();
t15.testNwChemStampede();
t15.tearDown();
System.out.println("NwChemStampede - Done");
System.out.println("Starting NwChemComet ...");
NwChemComet t16 = new NwChemComet();
t16.setUp();
t16.testNwChemComet();
t16.tearDown();
System.out.println("NwChemComet - Done");
System.out.println("Starting PhastaPStampede ...");
PhastaPStampede t17 = new PhastaPStampede();
t17.setUp();
t17.testPhastaPStampede();
t17.tearDown();
System.out.println("PhastaPStampede - Done");
System.out.println("Starting TinkerMonteStampede ...");
TinkerMonteStampede t18 = new TinkerMonteStampede();
t18.setUp();
t18.testTinkerMonteStampede();
t18.tearDown();
System.out.println("TinkerMonteStampede - Done");
/*System.out.println("Starting TrinityStampede ...");
TrinityStampede t19 = new TrinityStampede();
t19.setUp();
t19.testTrinityStampede();
t19.tearDown();
System.out.println("TrinityStampede - Done");*/
System.out.println("Starting WRFStampede ...");
WRFStampede t20 = new WRFStampede();
t20.setUp();
t20.testWRFStampede();
t20.tearDown();
System.out.println("WRFStampede - Done");
}
long endTime = System.nanoTime();
long duration = (endTime - startTime);
System.out.println("Time to execute All Experiments "
+ " : " + (duration / 1000000000)/60 + " minutes.");
System.out.println("==================== Done =========================");
}
}
| 659 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/NwChemComet.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing NwChem Application on Comet**********
* Created by Eroma on 3/13/15.
* The script generates NwChem application execution on Trestles
* experiment-name and experiment-description are read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class NwChemComet extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testNwChemComet() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "NwChem-Comet");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime (200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime (200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("NWChem");
waitTime (200);
driver.findElement(By.name("continue")).click();
waitTime (200);
driver.findElement(By.id("Water-Molecule-Input")).sendKeys(ExpFileReadUtils.NWCHEM_INPUT1);
waitTime (200);
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("comet.sdsc.edu");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("shared");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 660 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/TinkerMonteStampede.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing TinkerMonte Application on Stampede**********
* Created by Eroma on 9/16/14.
* The script generates Trinity application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class TinkerMonteStampede extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testTinkerMonteStampede() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "TinkerMonte-Stampede");
waitTime (200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime(200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime(200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Tinker_Monte");
waitTime(200);
driver.findElement(By.name("continue")).click();
waitTime(200);
driver.findElement(By.id("xyzf")).sendKeys(ExpFileReadUtils.TINKER_INPUT1);
waitTime(200);
driver.findElement(By.id("keyf")).sendKeys(ExpFileReadUtils.TINKER_INPUT2);
waitTime (200);
driver.findElement(By.id("stps")).clear();
driver.findElement(By.id("stps")).sendKeys("20000");
waitTime (200);
driver.findElement(By.id("Ctc")).clear();
driver.findElement(By.id("Ctc")).sendKeys("C");
waitTime (200);
driver.findElement(By.id("stpsZ")).clear();
driver.findElement(By.id("stpsZ")).sendKeys("3.0");
waitTime (200);
driver.findElement(By.id("temp")).clear();
driver.findElement(By.id("temp")).sendKeys("298");
waitTime (200);
driver.findElement(By.id("Rconv")).clear();
driver.findElement(By.id("Rconv")).sendKeys("0.01");
waitTime (200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("stampede.tacc.xsede.org");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).clear();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 661 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/LammpsComet.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing Lammps Application on Comet**********
* Created by Eroma on 9/16/14.
* The script generates Lammps application execution on Trestles
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class LammpsComet extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String path = null;
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
path = ExpFileReadUtils.readProperty("local.path");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testLammpsComet() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "Lammps-Comet");
waitTime(200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime(200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime(200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("Lammps");
waitTime(200);
driver.findElement(By.name("continue")).click();
waitTime(200);
driver.findElement(By.id("Friction-Simulation-Input")).sendKeys(ExpFileReadUtils.LAMMPS_INPUT1);
waitTime(200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("comet.sdsc.edu");
waitTime(200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("gpu");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).clear();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
//driver.findElement(By.cssSelector("span.glyphicon.glyphicon-refresh")).click();
// waitTime(1000);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 662 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/CreateUserLogin.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class CreateUserLogin {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testCreateUserLogin() throws Exception {
String username = null;
String password = null;
try {
username = ExpFileReadUtils.readProperty("pga.username");
password = ExpFileReadUtils.readProperty("pga.password");
} catch (Exception e) {
throw new RuntimeException(e);
}
if (username == null || username.trim().equals("")
|| password == null || password.trim().equals(""))
throw new RuntimeException("PGS user name or password in exp.properties file is invalid !");
username = username.trim();
password = password.trim();
driver.get(baseUrl);
driver.findElement(By.linkText("Create account")).click();
driver.findElement(By.id("username")).sendKeys(username);
waitTime(500);
driver.findElement(By.id("password")).sendKeys(password);
waitTime(500);
driver.findElement(By.id("confirm_password")).sendKeys(password);
waitTime(500);
driver.findElement(By.id("email")).sendKeys("pgauser@gmail.com");
waitTime(500);
driver.findElement(By.id("first_name")).sendKeys("PGA");
waitTime(500);
driver.findElement(By.id("last_name")).sendKeys("User");
waitTime(500);
driver.findElement(By.name("Submit")).click();
waitTime(5000);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 663 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/CreateModifySearchProject.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
//import static org.testng.Assert.fail;
/*
**********Create, Modify & Search Project**********
* Created by Airavata on 9/12/14.
* The script creates, modifies and searches for the created Project
* project-name and project-description are read from the exp.properties file
* Modified by Eroma on 10/23/14. Base URL & Sub URL to be read from the exp.properties file
*/
public class CreateModifySearchProject extends UserLogin {
private WebDriver driver;
private String subUrl;
private String baseUrl;
private String projectDescription;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
projectDescription = ExpFileReadUtils.readProperty("project.description");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testCreateModifySearchProject() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Project")).click();
driver.findElement(By.id("create")).click();
driver.findElement(By.id("project-name")).clear();
driver.findElement(By.id("project-name")).sendKeys(ExpFileReadUtils.readProperty("project.name"));
waitTime (500);
driver.findElement(By.id("project-description")).clear();
driver.findElement(By.id("project-description")).sendKeys(projectDescription);
waitTime (500);
driver.findElement(By.name("save")).click();
waitTime(750);
driver.findElement(By.cssSelector("span.glyphicon.glyphicon-pencil")).click();
driver.findElement(By.id("project-description")).clear();
driver.findElement(By.id("project-description")).sendKeys(projectDescription + "_MODIFIED_2015");
waitTime(500);
driver.findElement(By.name("save")).click();
waitTime(500);
driver.findElement(By.linkText("Project")).click();
driver.findElement(By.id("browse")).click();
waitTime(500);
driver.findElement(By.id("search-value")).clear();
driver.findElement(By.id("search-value")).sendKeys(ExpFileReadUtils.readProperty("project.name"));
waitTime(500);
driver.findElement(By.name("search")).click();
driver.findElement(By.linkText("View")).click();
waitTime(500);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
throw new Exception(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 664 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/WRFStampede.java | package org.apache.airavata.pga.tests;
import java.util.concurrent.TimeUnit;
import org.apache.airavata.pga.tests.utils.UserLogin;
import org.apache.airavata.pga.tests.utils.ExpFileReadUtils;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
/*
**********Executing WRF Application on Stampede**********
* Created by Airavata on 9/16/14.
* The script generates WRF application execution on Stampede
* experiment-name and experiment-description are read from the exp.properties file
* Modified by Eroma on 10/27/14. Base URL & Sub URL to be read from the exp.properties file
* Updated to work with Latest PGA by Eroma 08/05/2015
*/
public class WRFStampede extends UserLogin {
private WebDriver driver;
private String baseUrl;
private String subUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private String expName = null;
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = ExpFileReadUtils.readProperty("base.url");
subUrl = ExpFileReadUtils.readProperty("sub.url");
expName = ExpFileReadUtils.readProperty("experiment.name");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testWRFStampede() throws Exception {
driver.get(baseUrl + subUrl);
authenticate(driver);
driver.findElement(By.linkText("Experiment")).click();
driver.findElement(By.xpath("(//a[contains(text(),'Create')])[2]")).click();
driver.findElement(By.id("experiment-name")).clear();
driver.findElement(By.id("experiment-name")).sendKeys(expName + "WRF-Stampede");
waitTime(200);
driver.findElement(By.id("experiment-description")).clear();
driver.findElement(By.id("experiment-description")).sendKeys("Test Experiment");
waitTime(200);
new Select(driver.findElement(By.id("project"))).selectByVisibleText(ExpFileReadUtils.readProperty("project.name"));
waitTime(200);
new Select(driver.findElement(By.id("application"))).selectByVisibleText("WRF");
waitTime(200);
driver.findElement(By.name("continue")).click();
waitTime(200);
driver.findElement(By.id("Configuration-Namelist-file")).sendKeys(ExpFileReadUtils.WRF_INPUT1);
waitTime(200);
driver.findElement(By.id("WRF-Initial-Conditions")).sendKeys(ExpFileReadUtils.WRF_INPUT2);
waitTime(200);
driver.findElement(By.id("WRF-Boundary-file")).sendKeys(ExpFileReadUtils.WRF_INPUT3);
waitTime(200);
new Select(driver.findElement(By.id("compute-resource"))).selectByVisibleText("stampede.tacc.xsede.org");
waitTime (200);
new Select(driver.findElement(By.id("select-queue"))).selectByVisibleText("normal");
waitTime (200);
driver.findElement(By.id("node-count")).clear();
driver.findElement(By.id("node-count")).sendKeys("1");
driver.findElement(By.id("cpu-count")).clear();
driver.findElement(By.id("cpu-count")).sendKeys("16");
driver.findElement(By.id("wall-time")).clear();
driver.findElement(By.id("wall-time")).sendKeys("30");
driver.findElement(By.id("memory-count")).clear();
driver.findElement(By.id("memory-count")).sendKeys("0");
driver.findElement(By.id("enableEmail")).click();
driver.findElement(By.id("emailAddresses")).sendKeys(ExpFileReadUtils.readProperty("email1"));
driver.findElement(By.xpath("(//button[@type='button'])[2]")).click();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).clear();
driver.findElement(By.xpath("(//input[@name='emailAddresses[]'])[2]")).sendKeys(ExpFileReadUtils.readProperty("email2"));
waitTime (200);
driver.findElement(By.name("launch")).click();
waitTime (200);
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
| 665 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/utils/UserLogin.java | package org.apache.airavata.pga.tests.utils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
/*
**********User Login to PHP-Reference-Gateway**********
* Created by Eroma on 9/12/14.
* User Login in to PHP-Reference-Gateway. This class is called by all other test classes to login into the gateway.
* Enter your Username & Pwd in this script
*/
public abstract class UserLogin {
public void authenticate(WebDriver driver){
String username = null;
String password = null;
try {
username = ExpFileReadUtils.readProperty("pga.username");
password = ExpFileReadUtils.readProperty("pga.password");
} catch (Exception e) {
throw new RuntimeException(e);
}
if (username == null || username.trim().equals("")
|| password == null || password.trim().equals(""))
throw new RuntimeException("PGS user name or password in exp.properties file is invalid !");
username = username.trim();
password = password.trim();
driver.findElement(By.linkText("Log in")).click();
waitTime (500);
driver.findElement(By.name("username")).clear();
waitTime (500);
driver.findElement(By.name("username")).sendKeys(username);
waitTime (500);
driver.findElement(By.name("password")).sendKeys(password);
waitTime (500);
driver.findElement(By.name("Submit")).click();
}
private void waitTime(int i) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 666 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/utils/CurrentDateTime.java | package org.apache.airavata.pga.tests.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by Eroma on 11/24/14.
*/
public class CurrentDateTime {
private static final String DATE_PATTERN = "-MM-dd_HH-mm-ss";
public static String getTodayDate() {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_PATTERN);
return simpleDateFormat.format(date);
}
}
| 667 |
0 | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests | Create_ds/airavata/modules/ide-integration/src/main/containers/pga/airavata-php-gateway/app/tests/selenium/src/test/java/org/apache/airavata/pga/tests/utils/ExpFileReadUtils.java | package org.apache.airavata.pga.tests.utils;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;
/*
**********Reading Utilities File**********
* Created by Airavata on 9/15/14.
*/
public class ExpFileReadUtils {
public static String readProperty (String propertyName) throws Exception{
Properties prop = new Properties();
InputStream input = null;
try{
String filename = "exp.properties";
input = ExpFileReadUtils.class.getClassLoader().getResourceAsStream(filename);
if(input==null){
throw new Exception("Unable to read the file..");
}
//load a properties file from class path, inside static method
prop.load(input);
Enumeration e = prop.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + " -- " + prop.getProperty(key));
}
return prop.getProperty(propertyName);
}catch (Exception e){
throw new Exception("Error while reading file..", e);
}
}
public static String AMBER_INPUT1 = getLocalPath() + "/AMBER_FILES/02_Heat.rst";
public static String AMBER_INPUT2 = getLocalPath() + "/AMBER_FILES/prmtop";
public static String AMBER_INPUT3 = getLocalPath() + "/AMBER_FILES/03_Prod.in";
public static String AUTODOCK_INPUT1 = getLocalPath() + "AUTODOCK_FILES/ind.dpf";
public static String AUTODOCK_INPUT2 = getLocalPath() + "AUTODOCK_FILES/AD4_parameters.dat";
public static String AUTODOCK_INPUT3 = getLocalPath() + "AUTODOCK_FILES/hsg1.maps.fld";
public static String ESPRESSO_INPUT1 = getLocalPath() + "/ESPRESSO_FILES/Al.sample.in";
public static String ESPRESSO_INPUT2 = getLocalPath() + "/ESPRESSO_FILES/Al.pz-vbc.UPF";
public static String GAMESS_INPUT1 = getLocalPath() + "/GAMES_FILES/exam02.inp";
public static String GAUSSIAN_INPUT1 = getLocalPath() + "/GAUSSIAN_FILES/Gaussian.com";
public static String GAUSSIAN_INPUT2 = getLocalPath() + "/GAUSSIAN_FILES/pxylene.com";
public static String GROMACS_INPUT1 = getLocalPath() + "/GROMMACS_FILES/pdb1y6l-EM-vacuum.gro";
public static String GROMACS_INPUT2 = getLocalPath() + "/GROMMACS_FILES/pdb1y6l-EM-vacuum.gro.tpr";
public static String LAMMPS_INPUT1 = getLocalPath() + "/LAMMPS_FILES/in.friction";
public static String NWCHEM_INPUT1 = getLocalPath() + "/NWCHEM_FILES/water.nw";
public static String PHASTA_INPUT1 = getLocalPath() + "/PHASTA_FILES/geom.xmt_txt";
public static String PHASTA_INPUT2 = getLocalPath() + "/PHASTA_FILES/geom.smd";
public static String PHASTA_INPUT3 = getLocalPath() + "/PHASTA_FILES/geom.sms";
public static String PHASTA_INPUT4 = getLocalPath() + "/PHASTA_FILES/solver.inp";
public static String TINKER_INPUT1 = getLocalPath() + "/TINKER_FILES/cpentene.xyz";
public static String TINKER_INPUT2 = getLocalPath() + "/TINKER_FILES/cpentene.key";
public static String TRINITY_INPUT1 = getLocalPath() + "/TRINITY_FILES/reads.left.fq";
public static String TRINITY_INPUT2 = getLocalPath() + "/TRINITY_FILES/reads.right.fq";
public static String WRF_INPUT1 = getLocalPath() + "/WRF_FILES/namelist.input";
public static String WRF_INPUT2 = getLocalPath() + "/WRF_FILES/wrfbdy_d01";
public static String WRF_INPUT3 = getLocalPath() + "/WRF_FILES/wrfinput_d01";
public static String getLocalPath() {
try {
return ExpFileReadUtils.readProperty("local.path");
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
| 668 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/test/java/org/apache/airavata/sharing | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/test/java/org/apache/airavata/sharing/registry/CipresTest.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.sharing.registry;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.sharing.registry.models.*;
import org.apache.airavata.sharing.registry.service.cpi.SharingRegistryService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSSLTransportFactory;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import java.util.ArrayList;
import java.util.Arrays;
public class CipresTest {
public static void main(String[] args) throws InterruptedException, TException, ApplicationSettingsException {
System.out.println("Hello World!");
//should use the correct host name and port here
String serverHost = "wb-airavata.scigap.org";
int serverPort = 7878;
TTransport transport = null;
TProtocol protocol = null;
try {
SharingRegistryService.Client sharingServiceClient;
//Non Secure Client
// transport = new TSocket(serverHost, serverPort);
// transport.open();
// protocol = new TBinaryProtocol(transport);
// sharingServiceClient= new SharingRegistryService.Client(protocol);
//TLS enabled client
TSSLTransportFactory.TSSLTransportParameters params =
new TSSLTransportFactory.TSSLTransportParameters();
params.setKeyStore(ServerSettings.getKeyStorePath(), ServerSettings.getKeyStorePassword());
params.setTrustStore(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
transport = TSSLTransportFactory.getClientSocket(serverHost, serverPort, 10000, params);
protocol = new TBinaryProtocol(transport);
sharingServiceClient = new SharingRegistryService.Client(protocol);
try {
sharingServiceClient.deleteDomain("test-domain");
} catch (SharingRegistryException sre1) {
System.out.println("deleteDomain failed" + sre1.getMessage() + "\n");
}
Domain domain = new Domain();
//has to be one word
domain.setName("test-domain");
//optional
domain.setDescription("test domain description");
//domain id will be same as domain name
String domainId = sharingServiceClient.createDomain(domain);
System.out.println("After domain creation...\n");
User user1 = new User();
String userName1 = "test-user-1";
String userId1 = "test-user-1";
//required
user1.setUserId(userId1);
//required
user1.setUserName(userName1);
//required
user1.setDomainId(domainId);
//required
user1.setFirstName("John");
//required
user1.setLastName("Doe");
//required
user1.setEmail("john.doe@abc.com");
//optional - this should be bytes of the users image icon
//byte[] icon = new byte[10];
//user1.setIcon(icon);
sharingServiceClient.createUser(user1);
User user2 = new User();
String userName2 = "test-user-2";
String userId2 = "test-user-2";
//required
user2.setUserId(userId2);
//required
user2.setUserName(userName2);
//required
user2.setDomainId(domainId);
//required
user2.setFirstName("John");
//required
user2.setLastName("Doe");
//required
user2.setEmail("john.doe@abc.com");
//optional - this should be bytes of the users image icon
//byte[] icon = new byte[20];
//user2.setIcon(icon);
sharingServiceClient.createUser(user2);
User user3 = new User();
String userName3 = "test-user-3";
String userId3 = "test-user-3";
//required
user3.setUserId(userId3);
//required
user3.setUserName(userName3);
//required
user3.setDomainId(domainId);
//required
user3.setFirstName("John");
//required
user3.setLastName("Doe");
//required
user3.setEmail("john.doe@abc.com");
//optional - this should be bytes of the users image icon
//byte[] icon = new byte[30];
//user3.setIcon(icon);
sharingServiceClient.createUser(user3);
System.out.println("After user creation...\n");
UserGroup userGroup1 = new UserGroup();
//required
userGroup1.setGroupId("test-group-1");
//required
userGroup1.setDomainId(domainId);
//required
userGroup1.setName("test-group-1");
//optional
//userGroup1.setDescription("test group description");
//required
userGroup1.setOwnerId("test-user-1");
//required
userGroup1.setGroupType(GroupType.USER_LEVEL_GROUP);
sharingServiceClient.createGroup(userGroup1);
//Similarly create another group "userGroup2" with the owner being "test-user-2".
UserGroup userGroup2 = new UserGroup();
//required
userGroup2.setGroupId("test-group-2");
//required
userGroup2.setDomainId(domainId);
//required
userGroup2.setName("test-group-2");
//optional
//userGroup2.setDescription("test group description");
//required
userGroup2.setOwnerId("test-user-2");
//required
userGroup2.setGroupType(GroupType.USER_LEVEL_GROUP);
sharingServiceClient.createGroup(userGroup2);
System.out.println("After group creation...\n");
sharingServiceClient.addUsersToGroup(domainId, Arrays.asList("test-user-3"), "test-group-2");
System.out.println("After adding user to group...\n");
sharingServiceClient.addChildGroupsToParentGroup(domainId, Arrays.asList("test-group-2"), "test-group-1");
PermissionType permissionType1 = new PermissionType();
//required
permissionType1.setPermissionTypeId("READ");
//required
permissionType1.setDomainId(domainId);
//required
permissionType1.setName("READ");
//optional
permissionType1.setDescription("READ description");
sharingServiceClient.createPermissionType(permissionType1);
PermissionType permissionType2 = new PermissionType();
permissionType2.setPermissionTypeId("WRITE");
permissionType2.setDomainId(domainId);
permissionType2.setName("WRITE");
permissionType2.setDescription("WRITE description");
sharingServiceClient.createPermissionType(permissionType2);
PermissionType permissionType3 = new PermissionType();
permissionType3.setPermissionTypeId("CLONE");
permissionType3.setDomainId(domainId);
permissionType3.setName("CLONE");
permissionType3.setDescription("CLONE description");
sharingServiceClient.createPermissionType(permissionType3);
System.out.println("After adding groups to parent group...\n");
EntityType entityType1 = new EntityType();
//required
entityType1.setEntityTypeId("PROJECT");
//required
entityType1.setDomainId(domainId);
//required
entityType1.setName("PROJECT");
//optional
entityType1.setDescription("PROJECT entity type description");
sharingServiceClient.createEntityType(entityType1);
EntityType entityType2 = new EntityType();
entityType2.setEntityTypeId("EXPERIMENT");
entityType2.setDomainId(domainId);
entityType2.setName("EXPERIMENT");
entityType2.setDescription("EXPERIMENT entity type");
sharingServiceClient.createEntityType(entityType2);
EntityType entityType3 = new EntityType();
entityType3.setEntityTypeId("FILE");
entityType3.setDomainId(domainId);
entityType3.setName("FILE");
entityType3.setDescription("FILE entity type");
sharingServiceClient.createEntityType(entityType3);
System.out.println("After project entity creation...\n");
Entity entity1 = new Entity();
//required
entity1.setEntityId("test-project-1");
//required
entity1.setDomainId(domainId);
//required
entity1.setEntityTypeId("PROJECT");
//required
entity1.setOwnerId("test-user-1");
//required
entity1.setName("test-project-1");
//optional
entity1.setDescription("test project 1 description");
//optional
entity1.setFullText("test project 1 stampede gaussian seagrid");
//optional - If not set this will be default to current system time
entity1.setOriginalEntityCreationTime(System.currentTimeMillis());
sharingServiceClient.createEntity(entity1);
System.out.println("After currentTimeMillis()...\n");
Entity entity2 = new Entity();
entity2.setEntityId("test-experiment-1");
entity2.setDomainId(domainId);
entity2.setEntityTypeId("EXPERIMENT");
entity2.setOwnerId("test-user-1");
entity2.setName("test-experiment-1");
entity2.setDescription("test experiment 1 description");
entity2.setParentEntityId("test-project-1");
entity2.setFullText("test experiment 1 benzene");
System.out.println("Before sharingServiceClient.createEntity entity2...\n");
sharingServiceClient.createEntity(entity2);
System.out.println("After sharingServiceClient.createEntity entity2...\n");
Entity entity3 = new Entity();
entity3.setEntityId("test-experiment-2");
entity3.setDomainId(domainId);
entity3.setEntityTypeId("EXPERIMENT");
entity3.setOwnerId("test-user-1");
entity3.setName("test-experiment-2");
entity3.setDescription("test experiment 2 description");
entity3.setParentEntityId("test-project-1");
entity3.setFullText("test experiment 1 3-methyl 1-butanol stampede");
sharingServiceClient.createEntity(entity3);
System.out.println("After sharingServiceClient.createEntity entity3...\n");
Entity entity4 = new Entity();
entity4.setEntityId("test-file-1");
entity4.setDomainId(domainId);
entity4.setEntityTypeId("FILE");
entity4.setOwnerId("test-user-1");
entity4.setName("test-file-1");
entity4.setDescription("test file 1 description");
entity4.setParentEntityId("test-experiment-2");
entity4.setFullText("test input file 1 for experiment 2");
sharingServiceClient.createEntity(entity4);
System.out.println("After sharingServiceClient.createEntity entity4...\n");
System.out.println("After test entity creation...\n");
//shared with cascading permissions
//System.out.println("Before shareEntityWithUsers WRITE...\n");
//sharingServiceClient.shareEntityWithUsers(domainId, "test-project-1", Arrays.asList("test-user-2"), "WRITE", true);
System.out.println("Before shareEntityWithGroups READ...\n");
long time = System.currentTimeMillis();
sharingServiceClient.shareEntityWithGroups(domainId, "test-experiment-2", Arrays.asList("test-group-2"), "READ", true);
System.out.println("Time for sharing " + (System.currentTimeMillis() - time));
//shared with non cascading permissions
System.out.println("Before shareEntityWithGroups CLONE...\n");
time = System.currentTimeMillis();
sharingServiceClient.shareEntityWithGroups(domainId, "test-experiment-2", Arrays.asList("test-group-2"), "CLONE", false);
System.out.println("Time for sharing " + (System.currentTimeMillis() - time));
//test-project-1 is explicitly shared with test-user-2 with WRITE permission
System.out.println("Before userHasAccess 1...\n");
System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-project-1", "WRITE"));
//test-user-2 has WRITE permission to test-experiment-1 and test-experiment-2 indirectly
System.out.println("Before userHasAccess 2...\n");
System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-experiment-1", "WRITE"));
System.out.println("Before userHasAccess 3...\n");
System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-experiment-2", "WRITE"));
//test-user-2 does not have READ permission to test-experiment-1 and test-experiment-2
System.out.println("Before userHasAccess 4...\n");
System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-experiment-1", "READ"));
System.out.println(domainId + " test-user-2 " + " test-experiment-2 " + " READ ");
System.out.println("Before userHasAccess 5...\n");
System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-experiment-2", "READ"));
//test-user-3 does not have READ permission to test-project-1
System.out.println("Before userHasAccess 6...\n");
System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-project-1", "READ"));
//test-experiment-2 is shared with test-group-2 with READ permission. Therefore test-user-3 has READ permission
System.out.println("Before userHasAccess 7...\n");
System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-experiment-2", "READ"));
//test-user-3 does not have WRITE permission to test-experiment-2
System.out.println("Before userHasAccess 8...\n");
System.out.println(sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-experiment-2", "WRITE"));
//test-user-3 has CLONE permission to test-experiment-2
System.out.println("Before userHasAccess 9...\n");
System.out.println((sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-experiment-2", "CLONE")));
//test-user-3 does not have CLONE permission to test-file-1
System.out.println("Before userHasAccess 10...\n");
System.out.println((sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-file-1", "CLONE")));
System.out.println("After cascading permissions...\n");
ArrayList<SearchCriteria> filters = new ArrayList<>();
//ArrayList<SearchCriteria> filters = new List<>();
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setSearchCondition(SearchCondition.LIKE);
searchCriteria.setValue("experiment stampede methyl");
//searchCriteria.setValue("stampede");
//searchCriteria.setSearchField(EntitySearchField.NAME);
searchCriteria.setSearchField(EntitySearchField.FULL_TEXT);
filters.add(searchCriteria);
searchCriteria = new SearchCriteria();
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue("READ");
searchCriteria.setSearchField(EntitySearchField.PERMISSION_TYPE_ID);
filters.add(searchCriteria);
System.out.println(sharingServiceClient.searchEntities(domainId, "test-user-2", filters, 0, -1).size());
System.out.println(sharingServiceClient.searchEntities(domainId, "test-user-2", filters, 0, -1));
System.out.println("After searchEntities...\n");
//System.out.println("After searchEntities...\n");
User userA = new User();
String userNameA = "UserA";
String userIdA = "UserA";
//required
userA.setUserId(userIdA);
//required
userA.setUserName(userNameA);
//required
userA.setDomainId(domainId);
//required
userA.setFirstName("User");
//required
userA.setLastName("A");
//required
userA.setEmail("user.a@example.com");
//optional - this should be bytes of the users image icon
//byte[] icon = new byte[10];
//userA.setIcon(icon);
sharingServiceClient.createUser(userA);
User userB = new User();
String userNameB = "UserB";
String userIdB = "UserB";
//required
userB.setUserId(userIdB);
//required
userB.setUserName(userNameB);
//required
userB.setDomainId(domainId);
//required
userB.setFirstName("User");
//required
userB.setLastName("B");
//required
userB.setEmail("user.b@example.com");
//optional - this should be bytes of the users image icon
//byte[] icon = new byte[10];
//userB.setIcon(icon);
sharingServiceClient.createUser(userB);
User userC = new User();
String userNameC = "UserC";
String userIdC = "UserC";
//required
userC.setUserId(userIdC);
//required
userC.setUserName(userNameC);
//required
userC.setDomainId(domainId);
//required
userC.setFirstName("User");
//required
userC.setLastName("C");
//required
userC.setEmail("user.c@example.com");
//optional - this should be bytes of the users image icon
//byte[] icon = new byte[10];
//userC.setIcon(icon);
sharingServiceClient.createUser(userC);
User userD = new User();
String userNameD = "UserD";
String userIdD = "UserD";
//required
userD.setUserId(userIdD);
//required
userD.setUserName(userNameD);
//required
userD.setDomainId(domainId);
//required
userD.setFirstName("User");
//required
userD.setLastName("D");
//required
userD.setEmail("user.d@example.com");
//optional - this should be bytes of the users image icon
//byte[] icon = new byte[10];
//userD.setIcon(icon);
sharingServiceClient.createUser(userD);
System.out.println("After user creation...\n");
UserGroup Group1 = new UserGroup();
//required
Group1.setGroupId("Group1");
//required
Group1.setDomainId(domainId);
//required
Group1.setName("Group1");
//optional
//userGroup1.setDescription("test group description");
//required
Group1.setOwnerId("UserA");
//required
Group1.setGroupType(GroupType.USER_LEVEL_GROUP);
sharingServiceClient.createGroup(Group1);
System.out.println("After Group1 creation...\n");
sharingServiceClient.addUsersToGroup(domainId, Arrays.asList("UserB"), "Group1");
sharingServiceClient.addUsersToGroup(domainId, Arrays.asList("UserC"), "Group1");
sharingServiceClient.addUsersToGroup(domainId, Arrays.asList("UserD"), "Group1");
System.out.println("After adding users to Group1 creation...\n");
EntityType entityTypeFolder = new EntityType();
//required
entityTypeFolder.setEntityTypeId("FOLDER");
//required
entityTypeFolder.setDomainId(domainId);
//required
entityTypeFolder.setName("FOLDER");
//optional
//entityTypeFolder.setDescription("PROJECT entity type description");
sharingServiceClient.createEntityType(entityTypeFolder);
System.out.println("After creating FOLDER entity type...\n");
EntityType entityTypeInputData = new EntityType();
//required
entityTypeInputData.setEntityTypeId("INPUTDATA");
//required
entityTypeInputData.setDomainId(domainId);
//required
entityTypeInputData.setName("INPUTDATA");
//optional
//entityTypeFolder.setDescription("PROJECT entity type description");
sharingServiceClient.createEntityType(entityTypeInputData);
System.out.println("After creating INPUTDATA entity type...\n");
Entity entityB1 = new Entity();
//required
entityB1.setEntityId("UserBProject1");
//required
entityB1.setDomainId(domainId);
//required
entityB1.setEntityTypeId("PROJECT");
//required
entityB1.setOwnerId("UserB");
//required
entityB1.setName("UserBProject1");
//optional
entityB1.setDescription("User B's Project 1");
//optional
entityB1.setFullText("test project 1");
//optional - If not set this will be default to current system time
entityB1.setOriginalEntityCreationTime(System.currentTimeMillis());
sharingServiceClient.createEntity(entityB1);
System.out.println("After creating UserBProject1 ...\n");
Entity entityC1 = new Entity();
//required
entityC1.setEntityId("UserCProject2");
//required
entityC1.setDomainId(domainId);
//required
entityC1.setEntityTypeId("PROJECT");
//required
entityC1.setOwnerId("UserC");
//required
entityC1.setName("UserCProject2");
//optional
entityC1.setDescription("User C's Project 2");
//optional
entityC1.setFullText("test project 2");
//optional - If not set this will be default to current system time
entityC1.setOriginalEntityCreationTime(System.currentTimeMillis());
sharingServiceClient.createEntity(entityC1);
System.out.println("After creating UserCProject2 ...\n");
Entity entityF1 = new Entity();
entityF1.setEntityId("Folder1");
entityF1.setDomainId(domainId);
entityF1.setEntityTypeId("FOLDER");
entityF1.setOwnerId("UserB");
entityF1.setName("UserBFolder1");
entityF1.setDescription("UserB's Folder 1");
entityF1.setParentEntityId("UserBProject1");
entityF1.setFullText("test experiment 1 ethidium");
sharingServiceClient.createEntity(entityF1);
System.out.println("After creating Folder1 ...\n");
Entity entityD1 = new Entity();
entityD1.setEntityId("Data1");
entityD1.setDomainId(domainId);
entityD1.setEntityTypeId("INPUTDATA");
entityD1.setOwnerId("UserB");
entityD1.setName("UserBData1");
entityD1.setDescription("UserB's Data 1");
entityD1.setParentEntityId("Folder1");
entityD1.setFullText("Data 1 for User B Folder 1");
sharingServiceClient.createEntity(entityD1);
System.out.println("After creating Data1 ...\n");
Entity entityF2 = new Entity();
entityF2.setEntityId("Folder2");
entityF2.setDomainId(domainId);
entityF2.setEntityTypeId("FOLDER");
entityF2.setOwnerId("UserC");
entityF2.setName("UserCFolder2");
entityF2.setDescription("UserC's Folder 2");
entityF2.setParentEntityId("UserCProject2");
entityF2.setFullText("test experiment 2 ethidium");
sharingServiceClient.createEntity(entityF2);
System.out.println("After creating Folder2 ...\n");
Entity entityD2 = new Entity();
entityD2.setEntityId("Data2");
entityD2.setDomainId(domainId);
entityD2.setEntityTypeId("INPUTDATA");
entityD2.setOwnerId("UserC");
entityD2.setName("UserCData2");
entityD2.setDescription("UserC's Data 2");
entityD2.setParentEntityId("Folder2");
entityD2.setFullText("Data 2 for User C Folder 1");
sharingServiceClient.createEntity(entityD2);
System.out.println("After creating Data2 ...\n");
//sharingServiceClient.shareEntityWithGroups(domainId, "test-experiment-2", Arrays.asList("test-group-2"), "READ", true);
time = System.currentTimeMillis();
sharingServiceClient.shareEntityWithGroups(domainId, "Folder1", Arrays.asList("Group1"), "READ", true);
System.out.println("Time for sharing " + (System.currentTimeMillis() - time));
System.out.println("After READ sharing UserBFolder1 with Group1 ...\n");
//sharingServiceClient.shareEntityWithGroups(domainId, "Folder2", Arrays.asList("Group1"), "READ", true);
//System.out.println("After READ sharing UserCFolder2 with Group1 ...\n");
Entity entityD3 = new Entity();
entityD3.setEntityId("Data3");
entityD3.setDomainId(domainId);
entityD3.setEntityTypeId("INPUTDATA");
entityD3.setOwnerId("UserC");
entityD3.setName("UserCData3");
entityD3.setDescription("UserC's Data 3");
entityD3.setParentEntityId("Folder2");
entityD3.setFullText("Data 3 for User C Folder 2");
sharingServiceClient.createEntity(entityD3);
System.out.println("After creating Data3 ...\n");
System.out.println("Does UserC have READ access to Data1 ...\n");
System.out.println(sharingServiceClient.userHasAccess(domainId, "UserC", "Data1", "READ"));
System.out.println("Does UserC have READ access to Data2 ...\n");
System.out.println(sharingServiceClient.userHasAccess(domainId, "UserC", "Data2", "READ"));
System.out.println("Does UserC have READ access to Data3 ...\n");
System.out.println(sharingServiceClient.userHasAccess(domainId, "UserC", "Data3", "READ"));
System.out.println("Does UserB have READ access to Data3 ...\n");
System.out.println(sharingServiceClient.userHasAccess(domainId, "UserB", "Data3", "READ"));
ArrayList<SearchCriteria> sharedfilters = new ArrayList<>();
searchCriteria = new SearchCriteria();
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue("READ");
searchCriteria.setSearchField(EntitySearchField.PERMISSION_TYPE_ID);
sharedfilters.add(searchCriteria);
System.out.println("items READable by UserC ...\n");
System.out.println(sharingServiceClient.searchEntities(domainId, "UserC", sharedfilters, 0, -1).size());
System.out.println(sharingServiceClient.searchEntities(domainId, "UserC", sharedfilters, 0, -1));
searchCriteria = new SearchCriteria();
//searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setSearchCondition(SearchCondition.NOT);
searchCriteria.setValue("UserC");
searchCriteria.setSearchField(EntitySearchField.OWNER_ID);
sharedfilters.add(searchCriteria);
System.out.println("items READable, and not owned by UserC by UserC ...\n");
System.out.println(sharingServiceClient.searchEntities(domainId, "UserC", sharedfilters, 0, -1).size());
System.out.println(sharingServiceClient.searchEntities(domainId, "UserC", sharedfilters, 0, -1));
System.out.println("After searchEntities 2...\n");
System.out.println(sharingServiceClient.searchEntities(domainId, "UserC", sharedfilters, 0, -1).size());
System.out.println(sharingServiceClient.searchEntities(domainId, "UserC", sharedfilters, 0, -1));
System.out.println("After searchEntities 2...\n");
sharingServiceClient.removeUsersFromGroup(domainId, Arrays.asList("UserD"), "Group1");
System.out.println("After removing UserD from Group1 ...\n");
sharingServiceClient.deleteGroup(domainId, "Group1");
System.out.println("After deleting Group1 ...\n");
System.out.println("End of try clause...\n");
} catch (TTransportException ex1) {
System.out.println("TTransportException...\n");
System.out.println(ex1);
System.out.println(ex1.getCause());
ex1.printStackTrace();
System.out.println(ex1.getMessage());
} catch (SharingRegistryException ex2) {
System.out.println("SharingRegistryException...\n");
System.out.println(ex2.getMessage());
} catch (TException ex3) {
System.out.println("TException...\n");
System.out.println(ex3.getMessage());
} finally {
System.out.println("In finally...\n");
transport.close();
}
}
}
| 669 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/test/java/org/apache/airavata/sharing | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/test/java/org/apache/airavata/sharing/registry/SharingRegistryServerHandlerTest.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.sharing.registry;
import org.junit.Assert;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.sharing.registry.db.utils.SharingRegistryDBInitConfig;
import org.apache.airavata.sharing.registry.models.*;
import org.apache.airavata.sharing.registry.server.SharingRegistryServerHandler;
import org.apache.thrift.TException;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharingRegistryServerHandlerTest {
private final static Logger logger = LoggerFactory.getLogger(SharingRegistryServerHandlerTest.class);
@Test
public void test() throws TException, ApplicationSettingsException {
SharingRegistryDBInitConfig sharingRegistryDBInitConfig = new SharingRegistryDBInitConfig();
sharingRegistryDBInitConfig.setDBInitScriptPrefix("sharing-registry");
SharingRegistryServerHandler sharingRegistryServerHandler = new SharingRegistryServerHandler(sharingRegistryDBInitConfig);
//Creating domain
Domain domain = new Domain();
String domainId = "test-domain."+System.currentTimeMillis();
domain.setDomainId(domainId);
domain.setName(domainId);
domain.setDescription("test domain description");
domain.setCreatedTime(System.currentTimeMillis());
domain.setUpdatedTime(System.currentTimeMillis());
Assert.assertNotNull(sharingRegistryServerHandler.createDomain(domain));
Assert.assertTrue(sharingRegistryServerHandler.getDomains(0, 10).size() > 0);
//Creating users
User user1 = new User();
String userName1 = "test-user-1." + System.currentTimeMillis();
String userId1 = domainId + ":" + userName1;
user1.setUserId(userId1);
user1.setUserName(userName1);
user1.setDomainId(domainId);
user1.setCreatedTime(System.currentTimeMillis());
user1.setUpdatedTime(System.currentTimeMillis());
Assert.assertNotNull(sharingRegistryServerHandler.createUser(user1));
User user2 = new User();
String userName2 = "test-user-2." + System.currentTimeMillis();
String userId2 = domainId + ":" + userName2;
user2.setUserId(userId2);
user2.setUserName(userName2);
user2.setDomainId(domainId);
user2.setCreatedTime(System.currentTimeMillis());
user2.setUpdatedTime(System.currentTimeMillis());
Assert.assertNotNull(sharingRegistryServerHandler.createUser(user2));
User user3 = new User();
String userName3 = "test-user-3." + System.currentTimeMillis();
String userId3 = domainId + ":" + userName3;
user3.setUserId(userId3);
user3.setUserName(userName3);
user3.setDomainId(domainId);
user3.setCreatedTime(System.currentTimeMillis());
user3.setUpdatedTime(System.currentTimeMillis());
Assert.assertNotNull(sharingRegistryServerHandler.createUser(user3));
User user7 = new User();
String userName7 = "test-user-7." + System.currentTimeMillis();
String userId7 = domainId + ":" + userName7;
user7.setUserId(userId7);
user7.setUserName(userName7);
user7.setDomainId(domainId);
user7.setCreatedTime(System.currentTimeMillis());
user7.setUpdatedTime(System.currentTimeMillis());
Assert.assertNotNull(sharingRegistryServerHandler.createUser(user7));
Assert.assertTrue(sharingRegistryServerHandler.getUsers(domainId, 0, 10).size() > 0);
// Creating user groups
UserGroup userGroup1 = new UserGroup();
String groupName1 = "test-group-1." + System.currentTimeMillis();
String groupId1 = domainId + ":" + groupName1;
userGroup1.setGroupId(groupId1);
userGroup1.setDomainId(domainId);
userGroup1.setName(groupName1);
userGroup1.setDescription("test group description");
userGroup1.setOwnerId(userId1);
userGroup1.setGroupType(GroupType.USER_LEVEL_GROUP);
userGroup1.setGroupCardinality(GroupCardinality.MULTI_USER);
userGroup1.setCreatedTime(System.currentTimeMillis());
userGroup1.setUpdatedTime(System.currentTimeMillis());
Assert.assertNotNull(sharingRegistryServerHandler.createGroup(userGroup1));
Assert.assertEquals(1, sharingRegistryServerHandler.getAllMemberGroupsForUser(domainId, userId1).size());
UserGroup userGroup2 = new UserGroup();
String groupName2 = "test-group-2." + System.currentTimeMillis();
String groupId2 = domainId + ":" + groupName2;
userGroup2.setGroupId(groupId2);
userGroup2.setDomainId(domainId);
userGroup2.setName(groupName2);
userGroup2.setDescription("test group description");
userGroup2.setOwnerId(userId2);
userGroup2.setGroupType(GroupType.USER_LEVEL_GROUP);
userGroup2.setGroupCardinality(GroupCardinality.MULTI_USER);
userGroup2.setCreatedTime(System.currentTimeMillis());
userGroup2.setUpdatedTime(System.currentTimeMillis());
Assert.assertNotNull(sharingRegistryServerHandler.createGroup(userGroup2));
sharingRegistryServerHandler.addUsersToGroup(domainId, Arrays.asList(userId1), groupId1);
sharingRegistryServerHandler.addUsersToGroup(domainId, Arrays.asList(userId7), groupId1);
sharingRegistryServerHandler.addUsersToGroup(domainId, Arrays.asList(userId2, userId3), groupId2);
Assert.assertEquals(1, sharingRegistryServerHandler.getAllMemberGroupsForUser(domainId, userId3).size());
sharingRegistryServerHandler.addChildGroupsToParentGroup(domainId, Arrays.asList(groupId2), groupId1);
Assert.assertTrue(sharingRegistryServerHandler.getGroupMembersOfTypeGroup(domainId, groupId1, 0, 10).size() == 1);
Assert.assertTrue(sharingRegistryServerHandler.getGroupMembersOfTypeUser(domainId, groupId2, 0, 10).size() == 2);
// Group roles tests
// user has owner access
Assert.assertTrue(sharingRegistryServerHandler.hasOwnerAccess(domainId, groupId1, userId1));
// user has admin access
Assert.assertTrue(sharingRegistryServerHandler.addGroupAdmins(domainId, groupId1, Arrays.asList(userId7)));
Assert.assertTrue(sharingRegistryServerHandler.hasAdminAccess(domainId, groupId1, userId7));
Assert.assertTrue(sharingRegistryServerHandler.removeGroupAdmins(domainId, groupId1, Arrays.asList(userId7)));
Assert.assertFalse(sharingRegistryServerHandler.hasAdminAccess(domainId, groupId1, userId7));
// transfer group ownership
sharingRegistryServerHandler.addUsersToGroup(domainId, Arrays.asList(userId2), groupId1);
Assert.assertTrue(sharingRegistryServerHandler.transferGroupOwnership(domainId, groupId1, userId2));
Assert.assertTrue(sharingRegistryServerHandler.hasOwnerAccess(domainId, groupId1, userId2));
Assert.assertTrue(sharingRegistryServerHandler.transferGroupOwnership(domainId, groupId1, userId1));
Assert.assertFalse(sharingRegistryServerHandler.hasOwnerAccess(domainId, groupId1, userId2));
//Creating permission types
PermissionType permissionType1 = new PermissionType();
String permissionName1 = "READ";
permissionType1.setPermissionTypeId(domainId+":"+permissionName1);
permissionType1.setDomainId(domainId);
permissionType1.setName(permissionName1);
permissionType1.setDescription("READ description");
permissionType1.setCreatedTime(System.currentTimeMillis());
permissionType1.setUpdatedTime(System.currentTimeMillis());
String permissionTypeId1 = sharingRegistryServerHandler.createPermissionType(permissionType1);
Assert.assertNotNull(permissionTypeId1);
PermissionType permissionType2 = new PermissionType();
String permissionName2 = "WRITE";
permissionType2.setPermissionTypeId(domainId+":"+permissionName2);
permissionType2.setDomainId(domainId);
permissionType2.setName(permissionName2);
permissionType2.setDescription("WRITE description");
permissionType2.setCreatedTime(System.currentTimeMillis());
permissionType2.setUpdatedTime(System.currentTimeMillis());
String permissionTypeId2 = sharingRegistryServerHandler.createPermissionType(permissionType2);
Assert.assertNotNull(permissionTypeId2);
//Creating entity types
EntityType entityType1 = new EntityType();
String entityType1Name = "Project";
entityType1.setEntityTypeId(domainId+":"+entityType1Name);
entityType1.setDomainId(domainId);
entityType1.setName(entityType1Name);
entityType1.setDescription("test entity type");
entityType1.setCreatedTime(System.currentTimeMillis());
entityType1.setUpdatedTime(System.currentTimeMillis());
String entityTypeId1 = sharingRegistryServerHandler.createEntityType(entityType1);
Assert.assertNotNull(entityTypeId1);
EntityType entityType2 = new EntityType();
String entityType2Name = "Experiment";
entityType2.setEntityTypeId(domainId+":"+entityType2Name);
entityType2.setDomainId(domainId);
entityType2.setName(entityType2Name);
entityType2.setDescription("test entity type");
entityType2.setCreatedTime(System.currentTimeMillis());
entityType2.setUpdatedTime(System.currentTimeMillis());
String entityTypeId2 = sharingRegistryServerHandler.createEntityType(entityType2);
Assert.assertNotNull(entityTypeId2);
EntityType entityType3 = new EntityType();
String entityType3Name = "FileInput";
entityType3.setEntityTypeId(domainId+":"+entityType3Name);
entityType3.setDomainId(domainId);
entityType3.setName(entityType3Name);
entityType3.setDescription("file input type");
entityType3.setCreatedTime(System.currentTimeMillis());
entityType3.setUpdatedTime(System.currentTimeMillis());
String entityTypeId3 = sharingRegistryServerHandler.createEntityType(entityType3);
Assert.assertNotNull(entityTypeId3);
EntityType entityType4 = new EntityType();
String entityType4Name = "Application-Deployment";
entityType4.setEntityTypeId(domainId+":"+entityType4Name);
entityType4.setDomainId(domainId);
entityType4.setName(entityType4Name);
entityType4.setDescription("test entity type");
entityType4.setCreatedTime(System.currentTimeMillis());
entityType4.setUpdatedTime(System.currentTimeMillis());
String entityTypeId4 = sharingRegistryServerHandler.createEntityType(entityType4);
Assert.assertNotNull(entityTypeId4);
//Creating Entities
Entity entity1 = new Entity();
entity1.setEntityId(domainId+":Entity1");
entity1.setDomainId(domainId);
entity1.setEntityTypeId(entityTypeId1);
entity1.setOwnerId(userId1);
entity1.setName("Project name 1");
entity1.setDescription("Project description");
entity1.setFullText("Project name project description");
entity1.setCreatedTime(System.currentTimeMillis());
entity1.setUpdatedTime(System.currentTimeMillis());
String entityId1 = sharingRegistryServerHandler.createEntity(entity1);
Assert.assertNotNull(entityId1);
Entity entity2 = new Entity();
entity2.setEntityId(domainId+":Entity2");
entity2.setDomainId(domainId);
entity2.setEntityTypeId(entityTypeId2);
entity2.setOwnerId(userId1);
entity2.setName("Experiment name");
entity2.setDescription("Experiment description");
entity2.setParentEntityId(entityId1);
entity2.setFullText("Project name project description");
entity2.setCreatedTime(System.currentTimeMillis());
entity2.setUpdatedTime(System.currentTimeMillis());
String entityId2 = sharingRegistryServerHandler.createEntity(entity2);
Assert.assertNotNull(entityId2);
Entity entity3 = new Entity();
entity3.setEntityId(domainId+":Entity3");
entity3.setDomainId(domainId);
entity3.setEntityTypeId(entityTypeId2);
entity3.setOwnerId(userId1);
entity3.setName("Experiment name");
entity3.setDescription("Experiment description");
entity3.setParentEntityId(entityId1);
entity3.setFullText("Project name project description");
entity3.setCreatedTime(System.currentTimeMillis());
entity3.setUpdatedTime(System.currentTimeMillis());
String entityId3 = sharingRegistryServerHandler.createEntity(entity3);
Assert.assertNotNull(entityId3);
sharingRegistryServerHandler.shareEntityWithUsers(domainId, entityId1, Arrays.asList(userId2), permissionTypeId1, true);
sharingRegistryServerHandler.shareEntityWithGroups(domainId, entityId3, Arrays.asList(groupId2), permissionTypeId1, true);
Entity entity4 = new Entity();
entity4.setEntityId(domainId+":Entity4");
entity4.setDomainId(domainId);
entity4.setEntityTypeId(entityTypeId3);
entity4.setOwnerId(userId3);
entity4.setName("Input name");
entity4.setDescription("Input file description");
entity4.setParentEntityId(entityId3);
entity4.setFullText("Input File");
entity4.setCreatedTime(System.currentTimeMillis());
entity4.setUpdatedTime(System.currentTimeMillis());
String entityId4 = sharingRegistryServerHandler.createEntity(entity4);
Assert.assertNotNull(entityId4);
Assert.assertTrue(sharingRegistryServerHandler.userHasAccess(domainId, userId3, entityId4, permissionTypeId1));
Assert.assertTrue(sharingRegistryServerHandler.userHasAccess(domainId, userId2, entityId4, permissionTypeId1));
Assert.assertTrue(sharingRegistryServerHandler.userHasAccess(domainId, userId1, entityId4, permissionTypeId1));
Assert.assertFalse(sharingRegistryServerHandler.userHasAccess(domainId, userId3, entityId1, permissionTypeId1));
Entity entity5 = new Entity();
entity5.setEntityId(domainId+":Entity5");
entity5.setDomainId(domainId);
entity5.setEntityTypeId(entityTypeId4);
entity5.setOwnerId(userId1);
entity5.setName("App deployment name");
entity5.setDescription("App deployment description");
entity5.setFullText("App Deployment name app deployment description");
entity5.setCreatedTime(System.currentTimeMillis());
entity5.setUpdatedTime(System.currentTimeMillis());
String entityId5 = sharingRegistryServerHandler.createEntity(entity5);
Assert.assertNotNull(entityId5);
sharingRegistryServerHandler.shareEntityWithUsers(domainId, entityId5, Arrays.asList(userId2), permissionTypeId1, true);
sharingRegistryServerHandler.shareEntityWithGroups(domainId, entityId5, Arrays.asList(groupId2), permissionTypeId2, true);
Assert.assertTrue(sharingRegistryServerHandler.userHasAccess(domainId, userId3, entityId5, permissionTypeId2));
Assert.assertTrue(sharingRegistryServerHandler.userHasAccess(domainId, userId2, entityId5, permissionTypeId1));
Assert.assertFalse(sharingRegistryServerHandler.userHasAccess(domainId, userId3, entityId5, permissionTypeId1));
ArrayList<SearchCriteria> filters = new ArrayList<>();
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setSearchCondition(SearchCondition.LIKE);
searchCriteria.setValue("Input");
searchCriteria.setSearchField(EntitySearchField.NAME);
filters.add(searchCriteria);
searchCriteria = new SearchCriteria();
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue(entityTypeId3);
searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
filters.add(searchCriteria);
Assert.assertTrue(sharingRegistryServerHandler.searchEntities(domainId, userId1, filters, 0, -1).size() > 0);
Assert.assertNotNull(sharingRegistryServerHandler.getListOfSharedUsers(domainId, entityId1, permissionTypeId1));
Assert.assertNotNull(sharingRegistryServerHandler.getListOfSharedGroups(domainId, entityId1, permissionTypeId1));
Assert.assertTrue(sharingRegistryServerHandler.getListOfSharedUsers(domainId, entityId1, domainId + ":OWNER").size()==1);
// test changing parent - old INDIRECT_CASCADING permissions removed, new is added
// entityId2's parent is entityId1. entityId1 is shared with userId2
Assert.assertTrue(sharingRegistryServerHandler.userHasAccess(domainId, userId2, entityId1, permissionTypeId1));
Assert.assertTrue(sharingRegistryServerHandler.userHasAccess(domainId, userId2, entityId2, permissionTypeId1));
Assert.assertFalse(sharingRegistryServerHandler.userHasAccess(domainId, userId3, entityId2, permissionTypeId1));
// create a different parent entity
Entity entity6 = new Entity();
entity6.setEntityId(domainId+":Entity6");
entity6.setDomainId(domainId);
entity6.setEntityTypeId(entityTypeId1);
entity6.setOwnerId(userId1);
entity6.setName("Project name 2");
entity6.setDescription("Project description");
entity6.setFullText("Project name project description");
entity6.setCreatedTime(System.currentTimeMillis());
entity6.setUpdatedTime(System.currentTimeMillis());
String entityId6 = sharingRegistryServerHandler.createEntity(entity6);
Assert.assertNotNull(entityId6);
sharingRegistryServerHandler.shareEntityWithUsers(domainId, entityId6, Arrays.asList(userId3), permissionTypeId1, true);
Assert.assertTrue(sharingRegistryServerHandler.userHasAccess(domainId, userId3, entityId6, permissionTypeId1));
// Make sure entityId2 isn't shared with userId7 and then share it directly
Assert.assertFalse(sharingRegistryServerHandler.userHasAccess(domainId, userId7, entityId2, permissionTypeId1));
sharingRegistryServerHandler.shareEntityWithUsers(domainId, entityId2, Arrays.asList(userId7), permissionTypeId1, true);
Assert.assertTrue(sharingRegistryServerHandler.userHasAccess(domainId, userId7, entityId2, permissionTypeId1));
entity2.setParentEntityId(entityId6);
logger.debug("Updating entity2");
Assert.assertTrue(sharingRegistryServerHandler.updateEntity(entity2));
Entity entity2Updated = sharingRegistryServerHandler.getEntity(domainId, entityId2);
Assert.assertEquals(entityId6, entity2Updated.getParentEntityId());
// parent changed so entityId2 should now be shared with entityId6's shared users (userId3)
Assert.assertFalse(sharingRegistryServerHandler.userHasAccess(domainId, userId2, entityId2, permissionTypeId1));
Assert.assertTrue(sharingRegistryServerHandler.userHasAccess(domainId, userId3, entityId2, permissionTypeId1));
// entityId2 should still be shared with userId7 since that was directly shared
Assert.assertTrue(sharingRegistryServerHandler.userHasAccess(domainId, userId7, entityId2, permissionTypeId1));
Assert.assertEquals(Arrays.asList(user3), sharingRegistryServerHandler.getListOfDirectlySharedUsers(domainId, entityId6, permissionTypeId1));
Assert.assertEquals(Arrays.asList(user7), sharingRegistryServerHandler.getListOfDirectlySharedUsers(domainId, entityId2, permissionTypeId1));
List<User> entityId2SharedUsers = sharingRegistryServerHandler.getListOfSharedUsers(domainId, entityId2, permissionTypeId1);
Assert.assertEquals(2, entityId2SharedUsers.size());
Assert.assertTrue("user3 and user7 in shared users", entityId2SharedUsers.contains(user3) && entityId2SharedUsers.contains(user7));
Assert.assertEquals(1, sharingRegistryServerHandler.getListOfDirectlySharedGroups(domainId, entityId3, permissionTypeId1).size());
Assert.assertEquals(groupId2, sharingRegistryServerHandler.getListOfDirectlySharedGroups(domainId, entityId3, permissionTypeId1).get(0).getGroupId());
// Test that new users are added to initialUserGroupId
UserGroup initialUserGroup = new UserGroup();
String initialUserGroupName = "initial user group";
String initialUserGroupId = domainId + ":" + initialUserGroupName;
initialUserGroup.setGroupId(initialUserGroupId);
initialUserGroup.setDomainId(domainId);
initialUserGroup.setName(initialUserGroupName);
initialUserGroup.setDescription("initial user group desc");
initialUserGroup.setOwnerId(userId1);
initialUserGroup.setGroupType(GroupType.USER_LEVEL_GROUP);
initialUserGroup.setGroupCardinality(GroupCardinality.MULTI_USER);
initialUserGroup.setCreatedTime(System.currentTimeMillis());
initialUserGroup.setUpdatedTime(System.currentTimeMillis());
Assert.assertNotNull(sharingRegistryServerHandler.createGroup(initialUserGroup));
domain.setInitialUserGroupId(initialUserGroupId);
Assert.assertTrue(sharingRegistryServerHandler.updateDomain(domain));
Assert.assertEquals(initialUserGroupId, sharingRegistryServerHandler.getDomain(domain.getDomainId()).getInitialUserGroupId());
User user8 = new User();
String userName8 = "test-user-8." + System.currentTimeMillis();
String userId8 = domainId + ":" + userName8;
user8.setUserId(userId8);
user8.setUserName(userName8);
user8.setDomainId(domainId);
user8.setCreatedTime(System.currentTimeMillis());
user8.setUpdatedTime(System.currentTimeMillis());
Assert.assertNotNull(sharingRegistryServerHandler.createUser(user8));
List<UserGroup> user8Groups = sharingRegistryServerHandler.getAllMemberGroupsForUser(domain.getDomainId(), userId8);
Assert.assertFalse(user8Groups.isEmpty());
Assert.assertEquals(1, user8Groups.size());
Assert.assertEquals(initialUserGroupId, user8Groups.get(0).getGroupId());
}
}
| 670 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/test/java/org/apache/airavata/sharing | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/test/java/org/apache/airavata/sharing/registry/SharingRegistryServiceTest.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.sharing.registry;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.sharing.registry.models.*;
import org.apache.airavata.sharing.registry.server.SharingRegistryServer;
import org.apache.airavata.sharing.registry.service.cpi.SharingRegistryService;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSSLTransportFactory;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
public class SharingRegistryServiceTest {
private final static Logger logger = LoggerFactory.getLogger(SharingRegistryServiceTest.class);
@BeforeClass
public static void setUp() throws Exception {
SharingRegistryServer server = new SharingRegistryServer();
server.setTestMode(true);
server.start();
Thread.sleep(1000 * 2);
}
@Test
public void test() throws TException, InterruptedException, ApplicationSettingsException {
String serverHost = "localhost";
int serverPort = 7878;
SharingRegistryService.Client sharingServiceClient;
if (!ServerSettings.isSharingTLSEnabled()) {
TTransport transport = new TSocket(serverHost, serverPort);
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
sharingServiceClient = new SharingRegistryService.Client(protocol);
}else{
TSSLTransportFactory.TSSLTransportParameters params =
new TSSLTransportFactory.TSSLTransportParameters();
params.setKeyStore(ServerSettings.getKeyStorePath(), ServerSettings.getKeyStorePassword());
params.setTrustStore(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
TTransport transport = TSSLTransportFactory.getClientSocket(serverHost, serverPort, 10000, params);
TProtocol protocol = new TBinaryProtocol(transport);
sharingServiceClient = new SharingRegistryService.Client(protocol);
}
Domain domain = new Domain();
//has to be one word
domain.setName("test-domain" + Math.random());
//optional
domain.setDescription("test domain description");
String domainId = sharingServiceClient.createDomain(domain);
Assert.assertTrue(sharingServiceClient.isDomainExists(domainId));
User user1 = new User();
//required
user1.setUserId("test-user-1");
//required
user1.setUserName("test-user-1");
//required
user1.setDomainId(domainId);
//required
user1.setFirstName("John");
//required
user1.setLastName("Doe");
//required
user1.setEmail("john.doe@abc.com");
//optional - this should be bytes of the users image icon
//byte[] icon1 = new byte[10];
//user1.setIcon(icon1);
sharingServiceClient.createUser(user1);
Assert.assertTrue(sharingServiceClient.isUserExists(domainId, "test-user-1"));
User user2 = new User();
//required
user2.setUserId("test-user-2");
//required
user2.setUserName("test-user-2");
//required
user2.setDomainId(domainId);
//required
user2.setFirstName("John");
//required
user2.setLastName("Doe");
//required
user2.setEmail("john.doe@abc.com");
//optional - this should be bytes of the users image icon
//byte[] icon2 = new byte[10];
//user2.setIcon(icon2);
sharingServiceClient.createUser(user2);
User user3 = new User();
//required
user3.setUserId("test-user-3");
//required
user3.setUserName("test-user-3");
//required
user3.setDomainId(domainId);
//required
user3.setFirstName("John");
//required
user3.setLastName("Doe");
//required
user3.setEmail("john.doe@abc.com");
//optional - this should be bytes of the users image icon
//byte[] icon3 = new byte[10];
//user3.setIcon(icon3);
sharingServiceClient.createUser(user3);
User user7 = new User();
//required
user7.setUserId("test-user-7");
//required
user7.setUserName("test-user-7");
//required
user7.setDomainId(domainId);
//required
user7.setFirstName("John");
//required
user7.setLastName("Doe");
//required
user7.setEmail("john.doe@abc.com");
//optional - this should be bytes of the users image icon
//byte[] icon3 = new byte[10];
//user3.setIcon(icon3);
sharingServiceClient.createUser(user7);
// Test updates to user and how it affects the user's SINGLE_USER group
UserGroup singleUserGroupUser7 = sharingServiceClient.getGroup(domainId, user7.getUserId());
Assert.assertEquals(GroupCardinality.SINGLE_USER, singleUserGroupUser7.getGroupCardinality());
user7.setFirstName("Johnny");
sharingServiceClient.updatedUser(user7);
User updatedUser7 = sharingServiceClient.getUser(domainId, user7.getUserId());
Assert.assertEquals("Johnny", updatedUser7.getFirstName());
singleUserGroupUser7 = sharingServiceClient.getGroup(domainId, user7.getUserId());
Assert.assertEquals(GroupCardinality.SINGLE_USER, singleUserGroupUser7.getGroupCardinality());
UserGroup userGroup1 = new UserGroup();
//required
userGroup1.setGroupId("test-group-1");
//required
userGroup1.setDomainId(domainId);
//required
userGroup1.setName("test-group-1");
//optional
userGroup1.setDescription("test group description");
//required
userGroup1.setOwnerId("test-user-1");
//required
userGroup1.setGroupType(GroupType.USER_LEVEL_GROUP);
sharingServiceClient.createGroup(userGroup1);
userGroup1.setDescription("updated description");
sharingServiceClient.updateGroup(userGroup1);
Assert.assertTrue(sharingServiceClient.getGroup(domainId, userGroup1.getGroupId()).getDescription().equals("updated description"));
Assert.assertTrue(sharingServiceClient.isGroupExists(domainId, "test-group-1"));
UserGroup userGroup2 = new UserGroup();
//required
userGroup2.setGroupId("test-group-2");
//required
userGroup2.setDomainId(domainId);
//required
userGroup2.setName("test-group-2");
//optional
userGroup2.setDescription("test group description");
//required
userGroup2.setOwnerId("test-user-2");
//required
userGroup2.setGroupType(GroupType.USER_LEVEL_GROUP);
sharingServiceClient.createGroup(userGroup2);
sharingServiceClient.addUsersToGroup(domainId, Arrays.asList("test-user-3"), "test-group-2");
sharingServiceClient.addUsersToGroup(domainId, Arrays.asList("test-user-7"), "test-group-1");
sharingServiceClient.addChildGroupsToParentGroup(domainId, Arrays.asList("test-group-2"), "test-group-1");
//Group roles
Assert.assertTrue(sharingServiceClient.hasOwnerAccess(domainId, "test-group-1", "test-user-1"));
// user has admin access
Assert.assertTrue(sharingServiceClient.addGroupAdmins(domainId, "test-group-1", Arrays.asList("test-user-7")));
Assert.assertTrue(sharingServiceClient.hasAdminAccess(domainId, "test-group-1", "test-user-7"));
UserGroup getGroup = sharingServiceClient.getGroup(domainId, "test-group-1");
Assert.assertTrue(getGroup.getGroupAdmins().size() == 1);
Assert.assertTrue(sharingServiceClient.removeGroupAdmins(domainId, "test-group-1", Arrays.asList("test-user-7")));
Assert.assertFalse(sharingServiceClient.hasAdminAccess(domainId, "test-group-1", "test-user-7"));
// transfer group ownership
sharingServiceClient.addUsersToGroup(domainId, Arrays.asList("test-user-2"), "test-group-1");
Assert.assertTrue(sharingServiceClient.transferGroupOwnership(domainId, "test-group-1", "test-user-2"));
Assert.assertTrue(sharingServiceClient.hasOwnerAccess(domainId, "test-group-1", "test-user-2"));
Assert.assertTrue(sharingServiceClient.transferGroupOwnership(domainId, "test-group-1", "test-user-1"));
Assert.assertFalse(sharingServiceClient.hasOwnerAccess(domainId, "test-group-1", "test-user-2"));
PermissionType permissionType1 = new PermissionType();
//required
permissionType1.setPermissionTypeId("READ");
//required
permissionType1.setDomainId(domainId);
//required
permissionType1.setName("READ");
//optional
permissionType1.setDescription("READ description");
sharingServiceClient.createPermissionType(permissionType1);
Assert.assertTrue(sharingServiceClient.isPermissionExists(domainId, "READ"));
PermissionType permissionType2 = new PermissionType();
permissionType2.setPermissionTypeId("WRITE");
permissionType2.setDomainId(domainId);
permissionType2.setName("WRITE");
permissionType2.setDescription("WRITE description");
sharingServiceClient.createPermissionType(permissionType2);
PermissionType permissionType3 = new PermissionType();
permissionType3.setPermissionTypeId("CLONE");
permissionType3.setDomainId(domainId);
permissionType3.setName("CLONE");
permissionType3.setDescription("CLONE description");
sharingServiceClient.createPermissionType(permissionType3);
EntityType entityType1 = new EntityType();
//required
entityType1.setEntityTypeId("PROJECT");
//required
entityType1.setDomainId(domainId);
//required
entityType1.setName("PROJECT");
//optional
entityType1.setDescription("PROJECT entity type description");
sharingServiceClient.createEntityType(entityType1);
Assert.assertTrue(sharingServiceClient.isEntityTypeExists(domainId, "PROJECT"));
EntityType entityType2 = new EntityType();
entityType2.setEntityTypeId("EXPERIMENT");
entityType2.setDomainId(domainId);
entityType2.setName("EXPERIMENT");
entityType2.setDescription("EXPERIMENT entity type");
sharingServiceClient.createEntityType(entityType2);
EntityType entityType3 = new EntityType();
entityType3.setEntityTypeId("FILE");
entityType3.setDomainId(domainId);
entityType3.setName("FILE");
entityType3.setDescription("FILE entity type");
sharingServiceClient.createEntityType(entityType3);
//Creating entities
Entity entity1 = new Entity();
//required
entity1.setEntityId("test-project-1");
//required
entity1.setDomainId(domainId);
//required
entity1.setEntityTypeId("PROJECT");
//required
entity1.setOwnerId("test-user-1");
//required
entity1.setName("test-project-1");
//optional
entity1.setDescription("test project 1 description");
//optional
entity1.setFullText("test project 1 stampede gaussian seagrid");
//optional - If not set this will be default to current system time
entity1.setOriginalEntityCreationTime(System.currentTimeMillis());
sharingServiceClient.createEntity(entity1);
Assert.assertTrue(sharingServiceClient.isEntityExists(domainId, "test-project-1"));
Entity entity2 = new Entity();
entity2.setEntityId("test-experiment-1");
entity2.setDomainId(domainId);
entity2.setEntityTypeId("EXPERIMENT");
entity2.setOwnerId("test-user-1");
entity2.setName("test-experiment-1");
entity2.setDescription("test experiment 1 description");
entity2.setParentEntityId("test-project-1");
entity2.setFullText("test experiment 1 benzene");
sharingServiceClient.createEntity(entity2);
Entity entity3 = new Entity();
entity3.setEntityId("test-experiment-2");
entity3.setDomainId(domainId);
entity3.setEntityTypeId("EXPERIMENT");
entity3.setOwnerId("test-user-1");
entity3.setName("test-experiment-2");
entity3.setDescription("test experiment 2 description");
entity3.setParentEntityId("test-project-1");
entity3.setFullText("test experiment 1 3-methyl 1-butanol stampede");
sharingServiceClient.createEntity(entity3);
Entity entity4 = new Entity();
entity4.setEntityId("test-file-1");
entity4.setDomainId(domainId);
entity4.setEntityTypeId("FILE");
entity4.setOwnerId("test-user-1");
entity4.setName("test-file-1");
entity4.setDescription("test file 1 description");
entity4.setParentEntityId("test-experiment-2");
entity4.setFullText("test input file 1 for experiment 2");
sharingServiceClient.createEntity(entity4);
Assert.assertTrue(sharingServiceClient.getEntity(domainId, "test-project-1").getSharedCount() == 0);
sharingServiceClient.shareEntityWithUsers(domainId, "test-project-1", Arrays.asList("test-user-2"), "WRITE", true);
Assert.assertTrue(sharingServiceClient.getEntity(domainId, "test-project-1").getSharedCount() == 1);
ArrayList<SearchCriteria> filters = new ArrayList<>();
SearchCriteria searchCriteria = new SearchCriteria();
searchCriteria.setSearchField(EntitySearchField.SHARED_COUNT);
searchCriteria.setValue("1");
searchCriteria.setSearchCondition(SearchCondition.GTE);
filters.add(searchCriteria);
Assert.assertEquals(1, sharingServiceClient.searchEntities(domainId, "test-user-2", filters, 0, -1).size());
sharingServiceClient.revokeEntitySharingFromUsers(domainId, "test-project-1", Arrays.asList("test-user-2"), "WRITE");
Assert.assertTrue(sharingServiceClient.getEntity(domainId, "test-project-1").getSharedCount() == 0);
sharingServiceClient.shareEntityWithUsers(domainId, "test-project-1", Arrays.asList("test-user-2"), "WRITE", true);
sharingServiceClient.shareEntityWithGroups(domainId, "test-experiment-2", Arrays.asList("test-group-2"), "READ", true);
sharingServiceClient.shareEntityWithGroups(domainId, "test-experiment-2", Arrays.asList("test-group-2"), "CLONE", false);
//true
Assert.assertTrue(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-project-1", "WRITE"));
//true
Assert.assertTrue(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-experiment-1", "WRITE"));
//true
Assert.assertTrue(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-experiment-2", "WRITE"));
//false
Assert.assertFalse(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-experiment-1", "READ"));
//true
Assert.assertTrue(sharingServiceClient.userHasAccess(domainId, "test-user-2", "test-experiment-2", "READ"));
//false
Assert.assertFalse(sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-project-1", "READ"));
//true
Assert.assertTrue(sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-experiment-2", "READ"));
//false
Assert.assertFalse(sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-experiment-2", "WRITE"));
//true
Assert.assertTrue((sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-experiment-2", "CLONE")));
//false
Assert.assertFalse((sharingServiceClient.userHasAccess(domainId, "test-user-3", "test-file-1", "CLONE")));
filters = new ArrayList<>();
searchCriteria = new SearchCriteria();
searchCriteria.setSearchCondition(SearchCondition.FULL_TEXT);
searchCriteria.setValue("experiment");
searchCriteria.setSearchField(EntitySearchField.FULL_TEXT);
filters.add(searchCriteria);
searchCriteria = new SearchCriteria();
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue("EXPERIMENT");
searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID);
filters.add(searchCriteria);
searchCriteria = new SearchCriteria();
searchCriteria.setSearchCondition(SearchCondition.EQUAL);
searchCriteria.setValue("READ");
searchCriteria.setSearchField(EntitySearchField.PERMISSION_TYPE_ID);
filters.add(searchCriteria);
Assert.assertTrue(sharingServiceClient.searchEntities(domainId, "test-user-2", filters, 0, -1).size() == 1);
Entity persistedEntity = sharingServiceClient.searchEntities(
domainId, "test-user-2", filters, 0, -1).get(0);
Assert.assertEquals(entity3.getName(), persistedEntity.getName());
Assert.assertEquals(entity3.getDescription(), persistedEntity.getDescription());
Assert.assertEquals(entity3.getFullText(), persistedEntity.getFullText());
searchCriteria = new SearchCriteria();
searchCriteria.setSearchCondition(SearchCondition.NOT);
searchCriteria.setValue("test-user-1");
searchCriteria.setSearchField(EntitySearchField.OWNER_ID);
filters.add(searchCriteria);
Assert.assertTrue(sharingServiceClient.searchEntities(domainId, "test-user-2", filters, 0, -1).size() == 0);
}
}
| 671 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/server/SharingRegistryServerHandler.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.sharing.registry.server;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.DBInitializer;
import org.apache.airavata.sharing.registry.db.entities.*;
import org.apache.airavata.sharing.registry.db.repositories.*;
import org.apache.airavata.sharing.registry.db.utils.DBConstants;
import org.apache.airavata.sharing.registry.db.utils.SharingRegistryDBInitConfig;
import org.apache.airavata.sharing.registry.models.*;
import org.apache.airavata.sharing.registry.service.cpi.SharingRegistryService;
import org.apache.airavata.sharing.registry.service.cpi.sharing_cpiConstants;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
public class SharingRegistryServerHandler implements SharingRegistryService.Iface{
private final static Logger logger = LoggerFactory.getLogger(SharingRegistryServerHandler.class);
public static String OWNER_PERMISSION_NAME = "OWNER";
public SharingRegistryServerHandler() throws ApplicationSettingsException, TException {
this(new SharingRegistryDBInitConfig());
}
public SharingRegistryServerHandler(SharingRegistryDBInitConfig sharingRegistryDBInitConfig) throws ApplicationSettingsException, TException {
DBInitializer.initializeDB(sharingRegistryDBInitConfig);
}
@Override
public String getAPIVersion() throws TException {
return sharing_cpiConstants.SHARING_CPI_VERSION;
}
/**
* * Domain Operations
* *
*/
@Override
public String createDomain(Domain domain) throws SharingRegistryException, DuplicateEntryException, TException {
try{
if((new DomainRepository()).get(domain.getDomainId()) != null)
throw new DuplicateEntryException("There exist domain with given domain id");
domain.setCreatedTime(System.currentTimeMillis());
domain.setUpdatedTime(System.currentTimeMillis());
(new DomainRepository()).create(domain);
//create the global permission for the domain
PermissionType permissionType = new PermissionType();
permissionType.setPermissionTypeId(domain.getDomainId() + ":" + OWNER_PERMISSION_NAME);
permissionType.setDomainId(domain.getDomainId());
permissionType.setName(OWNER_PERMISSION_NAME);
permissionType.setDescription("GLOBAL permission to " + domain.getDomainId());
permissionType.setCreatedTime(System.currentTimeMillis());
permissionType.setUpdatedTime(System.currentTimeMillis());
(new PermissionTypeRepository()).create(permissionType);
return domain.getDomainId();
}catch (Throwable ex){
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean updateDomain(Domain domain) throws SharingRegistryException, TException {
try{
Domain oldDomain = (new DomainRepository()).get(domain.getDomainId());
domain.setCreatedTime(oldDomain.getCreatedTime());
domain.setUpdatedTime(System.currentTimeMillis());
domain = getUpdatedObject(oldDomain, domain);
(new DomainRepository()).update(domain);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
/**
* <p>API method to check Domain Exists</p>
*
* @param domainId
*/
@Override
public boolean isDomainExists(String domainId) throws SharingRegistryException, TException {
try{
return (new DomainRepository()).isExists(domainId);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean deleteDomain(String domainId) throws SharingRegistryException, TException {
try{
(new DomainRepository()).delete(domainId);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public Domain getDomain(String domainId) throws SharingRegistryException, TException {
try{
return (new DomainRepository()).get(domainId);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public List<Domain> getDomains(int offset, int limit) throws TException {
try{
return (new DomainRepository()).select(new HashMap<>(), offset, limit);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
/**
* * User Operations
* *
*/
@Override
public String createUser(User user) throws SharingRegistryException, DuplicateEntryException, TException {
try{
UserPK userPK = new UserPK();
userPK.setUserId(user.getUserId());
userPK.setDomainId(user.getDomainId());
if((new UserRepository()).get(userPK) != null)
throw new DuplicateEntryException("There exist user with given user id");
user.setCreatedTime(System.currentTimeMillis());
user.setUpdatedTime(System.currentTimeMillis());
(new UserRepository()).create(user);
UserGroup userGroup = new UserGroup();
userGroup.setGroupId(user.getUserId());
userGroup.setDomainId(user.getDomainId());
userGroup.setName(user.getUserName());
userGroup.setDescription("user " + user.getUserName() + " group");
userGroup.setOwnerId(user.getUserId());
userGroup.setGroupType(GroupType.USER_LEVEL_GROUP);
userGroup.setGroupCardinality(GroupCardinality.SINGLE_USER);
(new UserGroupRepository()).create(userGroup);
Domain domain = new DomainRepository().get(user.getDomainId());
if (domain.getInitialUserGroupId() != null) {
addUsersToGroup(user.getDomainId(), Collections.singletonList(user.getUserId()),
domain.getInitialUserGroupId());
}
return user.getUserId();
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean updatedUser(User user) throws SharingRegistryException, TException {
try{
UserPK userPK = new UserPK();
userPK.setUserId(user.getUserId());
userPK.setDomainId(user.getDomainId());
User oldUser = (new UserRepository()).get(userPK);
user.setCreatedTime(oldUser.getCreatedTime());
user.setUpdatedTime(System.currentTimeMillis());
user = getUpdatedObject(oldUser, user);
(new UserRepository()).update(user);
UserGroupPK userGroupPK = new UserGroupPK();
userGroupPK.setGroupId(user.getUserId());
userGroupPK.setDomainId(user.getDomainId());
UserGroup userGroup = (new UserGroupRepository()).get(userGroupPK);
userGroup.setName(user.getUserName());
userGroup.setDescription("user " + user.getUserName() + " group");
updateGroup(userGroup);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
/**
* <p>API method to check User Exists</p>
*
* @param userId
*/
@Override
public boolean isUserExists(String domainId, String userId) throws SharingRegistryException, TException {
try{
UserPK userPK = new UserPK();
userPK.setDomainId(domainId);
userPK.setUserId(userId);
return (new UserRepository()).isExists(userPK);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean deleteUser(String domainId, String userId) throws SharingRegistryException, TException {
try{
UserPK userPK = new UserPK();
userPK.setUserId(userId);
userPK.setDomainId(domainId);
(new UserRepository()).delete(userPK);
UserGroupPK userGroupPK = new UserGroupPK();
userGroupPK.setGroupId(userId);
userGroupPK.setDomainId(domainId);
(new UserGroupRepository()).delete(userGroupPK);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public User getUser(String domainId, String userId) throws SharingRegistryException, TException {
try{
UserPK userPK = new UserPK();
userPK.setUserId(userId);
userPK.setDomainId(domainId);
return (new UserRepository()).get(userPK);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public List<User> getUsers(String domain, int offset, int limit) throws SharingRegistryException, TException {
try{
HashMap<String, String> filters = new HashMap<>();
filters.put(DBConstants.UserTable.DOMAIN_ID, domain);
return (new UserRepository()).select(filters, offset, limit);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
/**
* * Group Operations
* *
*/
@Override
public String createGroup(UserGroup group) throws SharingRegistryException, TException {
try{
UserGroupPK userGroupPK = new UserGroupPK();
userGroupPK.setGroupId(group.getGroupId());
userGroupPK.setDomainId(group.getDomainId());
if((new UserGroupRepository()).get(userGroupPK) != null)
throw new SharingRegistryException("There exist group with given group id");
//Client created groups are always of type MULTI_USER
group.setGroupCardinality(GroupCardinality.MULTI_USER);
group.setCreatedTime(System.currentTimeMillis());
group.setUpdatedTime(System.currentTimeMillis());
//Add group admins once the group is created
group.unsetGroupAdmins();
(new UserGroupRepository()).create(group);
addUsersToGroup(group.getDomainId(), Arrays.asList(group.getOwnerId()), group.getGroupId());
return group.getGroupId();
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean updateGroup(UserGroup group) throws SharingRegistryException, TException {
try{
group.setUpdatedTime(System.currentTimeMillis());
UserGroupPK userGroupPK = new UserGroupPK();
userGroupPK.setGroupId(group.getGroupId());
userGroupPK.setDomainId(group.getDomainId());
UserGroup oldGroup = (new UserGroupRepository()).get(userGroupPK);
group.setGroupCardinality(oldGroup.getGroupCardinality());
group.setCreatedTime(oldGroup.getCreatedTime());
group = getUpdatedObject(oldGroup, group);
if(!group.getOwnerId().equals(oldGroup.getOwnerId()))
throw new SharingRegistryException("Group owner cannot be changed");
(new UserGroupRepository()).update(group);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
/**
* API method to check Group Exists
* @param domainId
* @param groupId
* @return
* @throws SharingRegistryException
* @throws TException
*/
@Override
public boolean isGroupExists(String domainId, String groupId) throws SharingRegistryException, TException {
try{
UserGroupPK userGroupPK = new UserGroupPK();
userGroupPK.setDomainId(domainId);
userGroupPK.setGroupId(groupId);
return (new UserGroupRepository()).isExists(userGroupPK);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean deleteGroup(String domainId, String groupId) throws SharingRegistryException, TException {
try{
UserGroupPK userGroupPK = new UserGroupPK();
userGroupPK.setGroupId(groupId);
userGroupPK.setDomainId(domainId);
(new UserGroupRepository()).delete(userGroupPK);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public UserGroup getGroup(String domainId, String groupId) throws SharingRegistryException, TException {
try{
UserGroupPK userGroupPK = new UserGroupPK();
userGroupPK.setGroupId(groupId);
userGroupPK.setDomainId(domainId);
return (new UserGroupRepository()).get(userGroupPK);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public List<UserGroup> getGroups(String domain, int offset, int limit) throws TException {
try{
HashMap<String, String> filters = new HashMap<>();
filters.put(DBConstants.UserGroupTable.DOMAIN_ID, domain);
// Only return groups with MULTI_USER cardinality which is the only type of cardinality allowed for client created groups
filters.put(DBConstants.UserGroupTable.GROUP_CARDINALITY, GroupCardinality.MULTI_USER.name());
return (new UserGroupRepository()).select(filters, offset, limit);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean addUsersToGroup(String domainId, List<String> userIds, String groupId) throws SharingRegistryException, TException {
try{
for(int i=0; i < userIds.size(); i++){
GroupMembership groupMembership = new GroupMembership();
groupMembership.setParentId(groupId);
groupMembership.setChildId(userIds.get(i));
groupMembership.setChildType(GroupChildType.USER);
groupMembership.setDomainId(domainId);
groupMembership.setCreatedTime(System.currentTimeMillis());
groupMembership.setUpdatedTime(System.currentTimeMillis());
(new GroupMembershipRepository()).create(groupMembership);
}
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean removeUsersFromGroup(String domainId, List<String> userIds, String groupId) throws SharingRegistryException, TException {
try{
for (String userId: userIds) {
if (hasOwnerAccess(domainId, groupId, userId)) {
throw new SharingRegistryException("List of User Ids contains Owner Id. Cannot remove owner from the group");
}
}
for(int i=0; i < userIds.size(); i++){
GroupMembershipPK groupMembershipPK = new GroupMembershipPK();
groupMembershipPK.setParentId(groupId);
groupMembershipPK.setChildId(userIds.get(i));
groupMembershipPK.setDomainId(domainId);
(new GroupMembershipRepository()).delete(groupMembershipPK);
}
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean transferGroupOwnership(String domainId, String groupId, String newOwnerId) throws SharingRegistryException, TException {
try {
List<User> groupUser = getGroupMembersOfTypeUser(domainId, groupId, 0, -1);
if (!isUserBelongsToGroup(groupUser, newOwnerId)) {
throw new SharingRegistryException("New group owner is not part of the group");
}
if (hasOwnerAccess(domainId, groupId, newOwnerId)) {
throw new DuplicateEntryException("User already the current owner of the group");
}
// remove the new owner as Admin if present
if (hasAdminAccess(domainId, groupId, newOwnerId)) {
removeGroupAdmins(domainId, groupId, Arrays.asList(newOwnerId));
}
UserGroupPK userGroupPK = new UserGroupPK();
userGroupPK.setGroupId(groupId);
userGroupPK.setDomainId(domainId);
UserGroup userGroup = (new UserGroupRepository()).get(userGroupPK);
UserGroup newUserGroup = new UserGroup();
newUserGroup.setUpdatedTime(System.currentTimeMillis());
newUserGroup.setOwnerId(newOwnerId);
newUserGroup.setGroupCardinality(GroupCardinality.MULTI_USER);
newUserGroup.setCreatedTime(userGroup.getCreatedTime());
newUserGroup = getUpdatedObject(userGroup, newUserGroup);
(new UserGroupRepository()).update(newUserGroup);
return true;
}
catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
private boolean isUserBelongsToGroup(List<User> groupUser, String newOwnerId) {
for (User user: groupUser) {
if (user.getUserId().equals(newOwnerId)) {
return true;
}
}
return false;
}
@Override
public boolean addGroupAdmins(String domainId, String groupId, List<String> adminIds) throws SharingRegistryException, TException {
try{
List<User> groupUser = getGroupMembersOfTypeUser(domainId, groupId, 0, -1);
for (String adminId: adminIds) {
if (! isUserBelongsToGroup(groupUser, adminId)) {
throw new SharingRegistryException("Admin not the user of the group. GroupId : "+ groupId + ", AdminId : "+ adminId);
}
GroupAdminPK groupAdminPK = new GroupAdminPK();
groupAdminPK.setGroupId(groupId);
groupAdminPK.setAdminId(adminId);
groupAdminPK.setDomainId(domainId);
if((new GroupAdminRepository()).get(groupAdminPK) != null)
throw new DuplicateEntryException("User already an admin for the group");
GroupAdmin admin = new GroupAdmin();
admin.setAdminId(adminId);
admin.setDomainId(domainId);
admin.setGroupId(groupId);
(new GroupAdminRepository()).create(admin);
}
return true;
}
catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean removeGroupAdmins(String domainId, String groupId, List<String> adminIds) throws SharingRegistryException, TException {
try {
for (String adminId: adminIds) {
GroupAdminPK groupAdminPK = new GroupAdminPK();
groupAdminPK.setAdminId(adminId);
groupAdminPK.setDomainId(domainId);
groupAdminPK.setGroupId(groupId);
(new GroupAdminRepository()).delete(groupAdminPK);
}
return true;
}
catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean hasAdminAccess(String domainId, String groupId, String adminId) throws SharingRegistryException, TException {
try{
GroupAdminPK groupAdminPK = new GroupAdminPK();
groupAdminPK.setGroupId(groupId);
groupAdminPK.setAdminId(adminId);
groupAdminPK.setDomainId(domainId);
if((new GroupAdminRepository()).get(groupAdminPK) != null)
return true;
return false;
}
catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean hasOwnerAccess(String domainId, String groupId, String ownerId) throws SharingRegistryException, TException {
try {
UserGroupPK userGroupPK = new UserGroupPK();
userGroupPK.setGroupId(groupId);
userGroupPK.setDomainId(domainId);
UserGroup getGroup = (new UserGroupRepository()).get(userGroupPK);
if(getGroup.getOwnerId().equals(ownerId))
return true;
return false;
}
catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public List<User> getGroupMembersOfTypeUser(String domainId, String groupId, int offset, int limit) throws SharingRegistryException, TException {
try{
//TODO limit offset
List<User> groupMemberUsers = (new GroupMembershipRepository()).getAllChildUsers(domainId, groupId);
return groupMemberUsers;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public List<UserGroup> getGroupMembersOfTypeGroup(String domainId, String groupId, int offset, int limit) throws SharingRegistryException, TException {
try{
//TODO limit offset
List<UserGroup> groupMemberGroups = (new GroupMembershipRepository()).getAllChildGroups(domainId, groupId);
return groupMemberGroups;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean addChildGroupsToParentGroup(String domainId, List<String> childIds, String groupId) throws SharingRegistryException, TException {
try{
for(String childId : childIds) {
//Todo check for cyclic dependencies
GroupMembership groupMembership = new GroupMembership();
groupMembership.setParentId(groupId);
groupMembership.setChildId(childId);
groupMembership.setChildType(GroupChildType.GROUP);
groupMembership.setDomainId(domainId);
groupMembership.setCreatedTime(System.currentTimeMillis());
groupMembership.setUpdatedTime(System.currentTimeMillis());
(new GroupMembershipRepository()).create(groupMembership);
}
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean removeChildGroupFromParentGroup(String domainId, String childId, String groupId) throws SharingRegistryException, TException {
try{
GroupMembershipPK groupMembershipPK = new GroupMembershipPK();
groupMembershipPK.setParentId(groupId);
groupMembershipPK.setChildId(childId);
groupMembershipPK.setDomainId(domainId);
(new GroupMembershipRepository()).delete(groupMembershipPK);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public List<UserGroup> getAllMemberGroupsForUser(String domainId, String userId) throws SharingRegistryException, TException {
try{
GroupMembershipRepository groupMembershipRepository = new GroupMembershipRepository();
return groupMembershipRepository.getAllMemberGroupsForUser(domainId, userId);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
/**
* * EntityType Operations
* *
*/
@Override
public String createEntityType(EntityType entityType) throws SharingRegistryException, DuplicateEntryException, TException {
try{
EntityTypePK entityTypePK = new EntityTypePK();
entityTypePK.setDomainId(entityType.getDomainId());
entityTypePK.setEntityTypeId(entityType.getEntityTypeId());
if((new EntityTypeRepository()).get(entityTypePK) != null)
throw new DuplicateEntryException("There exist EntityType with given EntityType id");
entityType.setCreatedTime(System.currentTimeMillis());
entityType.setUpdatedTime(System.currentTimeMillis());
(new EntityTypeRepository()).create(entityType);
return entityType.getEntityTypeId();
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean updateEntityType(EntityType entityType) throws SharingRegistryException, TException {
try{
entityType.setUpdatedTime(System.currentTimeMillis());
EntityTypePK entityTypePK = new EntityTypePK();
entityTypePK.setDomainId(entityType.getDomainId());
entityTypePK.setEntityTypeId(entityType.getEntityTypeId());
EntityType oldEntityType = (new EntityTypeRepository()).get(entityTypePK);
entityType.setCreatedTime(oldEntityType.getCreatedTime());
entityType = getUpdatedObject(oldEntityType, entityType);
(new EntityTypeRepository()).update(entityType);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
/**
* <p>API method to check EntityType Exists</p>
*
* @param entityTypeId
*/
@Override
public boolean isEntityTypeExists(String domainId, String entityTypeId) throws SharingRegistryException, TException {
try{
EntityTypePK entityTypePK = new EntityTypePK();
entityTypePK.setDomainId(domainId);
entityTypePK.setEntityTypeId(entityTypeId);
return (new EntityTypeRepository()).isExists(entityTypePK);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean deleteEntityType(String domainId, String entityTypeId) throws SharingRegistryException, TException {
try{
EntityTypePK entityTypePK = new EntityTypePK();
entityTypePK.setDomainId(domainId);
entityTypePK.setEntityTypeId(entityTypeId);
(new EntityTypeRepository()).delete(entityTypePK);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public EntityType getEntityType(String domainId, String entityTypeId) throws SharingRegistryException, TException {
try{
EntityTypePK entityTypePK = new EntityTypePK();
entityTypePK.setDomainId(domainId);
entityTypePK.setEntityTypeId(entityTypeId);
return (new EntityTypeRepository()).get(entityTypePK);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public List<EntityType> getEntityTypes(String domain, int offset, int limit) throws TException {
try{
HashMap<String, String> filters = new HashMap<>();
filters.put(DBConstants.EntityTypeTable.DOMAIN_ID, domain);
return (new EntityTypeRepository()).select(filters, offset, limit);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
/**
* * Permission Operations
* *
*/
@Override
public String createPermissionType(PermissionType permissionType) throws SharingRegistryException, DuplicateEntryException, TException {
try{
PermissionTypePK permissionTypePK = new PermissionTypePK();
permissionTypePK.setDomainId(permissionType.getDomainId());
permissionTypePK.setPermissionTypeId(permissionType.getPermissionTypeId());
if((new PermissionTypeRepository()).get(permissionTypePK) != null)
throw new DuplicateEntryException("There exist PermissionType with given PermissionType id");
permissionType.setCreatedTime(System.currentTimeMillis());
permissionType.setUpdatedTime(System.currentTimeMillis());
(new PermissionTypeRepository()).create(permissionType);
return permissionType.getPermissionTypeId();
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean updatePermissionType(PermissionType permissionType) throws SharingRegistryException, TException {
try{
permissionType.setUpdatedTime(System.currentTimeMillis());
PermissionTypePK permissionTypePK = new PermissionTypePK();
permissionTypePK.setDomainId(permissionType.getDomainId());
permissionTypePK.setPermissionTypeId(permissionType.getPermissionTypeId());
PermissionType oldPermissionType = (new PermissionTypeRepository()).get(permissionTypePK);
permissionType = getUpdatedObject(oldPermissionType, permissionType);
(new PermissionTypeRepository()).update(permissionType);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
/**
* <p>API method to check Permission Exists</p>
*
* @param permissionId
*/
@Override
public boolean isPermissionExists(String domainId, String permissionId) throws SharingRegistryException, TException {
try{
PermissionTypePK permissionTypePK = new PermissionTypePK();
permissionTypePK.setDomainId(domainId);
permissionTypePK.setPermissionTypeId(permissionId);
return (new PermissionTypeRepository()).isExists(permissionTypePK);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean deletePermissionType(String domainId, String permissionTypeId) throws SharingRegistryException, TException {
try{
PermissionTypePK permissionTypePK = new PermissionTypePK();
permissionTypePK.setDomainId(domainId);
permissionTypePK.setPermissionTypeId(permissionTypeId);
(new PermissionTypeRepository()).delete(permissionTypePK);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public PermissionType getPermissionType(String domainId, String permissionTypeId) throws SharingRegistryException, TException {
try{
PermissionTypePK permissionTypePK = new PermissionTypePK();
permissionTypePK.setDomainId(domainId);
permissionTypePK.setPermissionTypeId(permissionTypeId);
return (new PermissionTypeRepository()).get(permissionTypePK);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public List<PermissionType> getPermissionTypes(String domain, int offset, int limit) throws SharingRegistryException, TException {
try{
HashMap<String, String> filters = new HashMap<>();
filters.put(DBConstants.PermissionTypeTable.DOMAIN_ID, domain);
return (new PermissionTypeRepository()).select(filters, offset, limit);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
/**
* * Entity Operations
* *
*/
@Override
public String createEntity(Entity entity) throws SharingRegistryException, DuplicateEntryException, TException {
try{
EntityPK entityPK = new EntityPK();
entityPK.setDomainId(entity.getDomainId());
entityPK.setEntityId(entity.getEntityId());
if((new EntityRepository()).get(entityPK) != null)
throw new DuplicateEntryException("There exist Entity with given Entity id");
UserPK userPK = new UserPK();
userPK.setDomainId(entity.getDomainId());
userPK.setUserId(entity.getOwnerId());
if(!(new UserRepository()).isExists(userPK)){
//Todo this is for Airavata easy integration. Proper thing is to throw an exception here
User user = new User();
user.setUserId(entity.getOwnerId());
user.setDomainId(entity.getDomainId());
user.setUserName(user.getUserId().split("@")[0]);
createUser(user);
}
entity.setCreatedTime(System.currentTimeMillis());
entity.setUpdatedTime(System.currentTimeMillis());
if(entity.getOriginalEntityCreationTime()==0){
entity.setOriginalEntityCreationTime(entity.getCreatedTime());
}
(new EntityRepository()).create(entity);
//Assigning global permission for the owner
Sharing newSharing = new Sharing();
newSharing.setPermissionTypeId((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(entity.getDomainId()));
newSharing.setEntityId(entity.getEntityId());
newSharing.setGroupId(entity.getOwnerId());
newSharing.setSharingType(SharingType.DIRECT_CASCADING);
newSharing.setInheritedParentId(entity.getEntityId());
newSharing.setDomainId(entity.getDomainId());
newSharing.setCreatedTime(System.currentTimeMillis());
newSharing.setUpdatedTime(System.currentTimeMillis());
(new SharingRepository()).create(newSharing);
// creating records for inherited permissions
if (entity.getParentEntityId() != null && entity.getParentEntityId() != "") {
addCascadingPermissionsForEntity(entity);
}
return entity.getEntityId();
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
SharingRegistryException sharingRegistryException = new SharingRegistryException();
sharingRegistryException.setMessage(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
throw sharingRegistryException;
}
}
private void addCascadingPermissionsForEntity(Entity entity) throws SharingRegistryException {
Sharing newSharing;
List<Sharing> sharings = (new SharingRepository()).getCascadingPermissionsForEntity(entity.getDomainId(),
entity.getParentEntityId());
for (Sharing sharing : sharings) {
newSharing = new Sharing();
newSharing.setPermissionTypeId(sharing.getPermissionTypeId());
newSharing.setEntityId(entity.getEntityId());
newSharing.setGroupId(sharing.getGroupId());
newSharing.setInheritedParentId(sharing.getInheritedParentId());
newSharing.setSharingType(SharingType.INDIRECT_CASCADING);
newSharing.setDomainId(entity.getDomainId());
newSharing.setCreatedTime(System.currentTimeMillis());
newSharing.setUpdatedTime(System.currentTimeMillis());
(new SharingRepository()).create(newSharing);
}
}
@Override
public boolean updateEntity(Entity entity) throws SharingRegistryException, TException {
try{
//TODO Check for permission changes
entity.setUpdatedTime(System.currentTimeMillis());
EntityPK entityPK = new EntityPK();
entityPK.setDomainId(entity.getDomainId());
entityPK.setEntityId(entity.getEntityId());
Entity oldEntity = (new EntityRepository()).get(entityPK);
entity.setCreatedTime(oldEntity.getCreatedTime());
// check if parent entity changed and re-add inherited permissions
if (!Objects.equals(oldEntity.getParentEntityId(), entity.getParentEntityId())) {
logger.debug("Parent entity changed for {}, updating inherited permissions", entity.getEntityId());
if (oldEntity.getParentEntityId() != null && oldEntity.getParentEntityId() != "") {
logger.debug("Removing inherited permissions from {} that were inherited from parent {}", entity.getEntityId(), oldEntity.getParentEntityId());
(new SharingRepository()).removeAllIndirectCascadingPermissionsForEntity(entity.getDomainId(), entity.getEntityId());
}
if (entity.getParentEntityId() != null && entity.getParentEntityId() != "") {
// re-add INDIRECT_CASCADING permissions
logger.debug("Adding inherited permissions to {} that are inherited from parent {}", entity.getEntityId(), entity.getParentEntityId());
addCascadingPermissionsForEntity(entity);
}
}
entity = getUpdatedObject(oldEntity, entity);
entity.setSharedCount((new SharingRepository()).getSharedCount(entity.getDomainId(), entity.getEntityId()));
(new EntityRepository()).update(entity);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
/**
* <p>API method to check Entity Exists</p>
*
* @param entityId
*/
@Override
public boolean isEntityExists(String domainId, String entityId) throws SharingRegistryException, TException {
try{
EntityPK entityPK = new EntityPK();
entityPK.setDomainId(domainId);
entityPK.setEntityId(entityId);
return (new EntityRepository()).isExists(entityPK);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean deleteEntity(String domainId, String entityId) throws SharingRegistryException, TException {
try{
//TODO Check for permission changes
EntityPK entityPK = new EntityPK();
entityPK.setDomainId(domainId);
entityPK.setEntityId(entityId);
(new EntityRepository()).delete(entityPK);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public Entity getEntity(String domainId, String entityId) throws SharingRegistryException, TException {
try{
EntityPK entityPK = new EntityPK();
entityPK.setDomainId(domainId);
entityPK.setEntityId(entityId);
return (new EntityRepository()).get(entityPK);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public List<Entity> searchEntities(String domainId, String userId, List<SearchCriteria> filters,
int offset, int limit) throws SharingRegistryException, TException {
try{
List<String> groupIds = new ArrayList<>();
groupIds.add(userId);
(new GroupMembershipRepository()).getAllParentMembershipsForChild(domainId, userId).stream().forEach(gm -> groupIds.add(gm.getParentId()));
return (new EntityRepository()).searchEntities(domainId, groupIds, filters, offset, limit);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public List<User> getListOfSharedUsers(String domainId, String entityId, String permissionTypeId) throws SharingRegistryException, TException {
try{
return (new UserRepository()).getAccessibleUsers(domainId, entityId, permissionTypeId);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public List<User> getListOfDirectlySharedUsers(String domainId, String entityId, String permissionTypeId)
throws SharingRegistryException, TException {
try{
return (new UserRepository()).getDirectlyAccessibleUsers(domainId, entityId, permissionTypeId);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
SharingRegistryException sharingRegistryException = new SharingRegistryException();
sharingRegistryException.setMessage(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
throw sharingRegistryException;
}
}
@Override
public List<UserGroup> getListOfSharedGroups(String domainId, String entityId, String permissionTypeId) throws SharingRegistryException, TException {
try{
return (new UserGroupRepository()).getAccessibleGroups(domainId, entityId, permissionTypeId);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public List<UserGroup> getListOfDirectlySharedGroups(String domainId, String entityId, String permissionTypeId)
throws SharingRegistryException, TException {
try{
return (new UserGroupRepository()).getDirectlyAccessibleGroups(domainId, entityId, permissionTypeId);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
SharingRegistryException sharingRegistryException = new SharingRegistryException();
sharingRegistryException.setMessage(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
throw sharingRegistryException;
}
}
/**
* Sharing Entity with Users and Groups
* @param domainId
* @param entityId
* @param userList
* @param permissionTypeId
* @param cascadePermission
* @return
* @throws SharingRegistryException
* @throws TException
*/
@Override
public boolean shareEntityWithUsers(String domainId, String entityId, List<String> userList, String permissionTypeId, boolean cascadePermission) throws SharingRegistryException, TException {
try{
return shareEntity(domainId, entityId, userList, permissionTypeId, cascadePermission);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean shareEntityWithGroups(String domainId, String entityId, List<String> groupList, String permissionTypeId, boolean cascadePermission) throws SharingRegistryException, TException {
try{
return shareEntity(domainId, entityId, groupList, permissionTypeId, cascadePermission);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
private boolean shareEntity(String domainId, String entityId, List<String> groupOrUserList, String permissionTypeId, boolean cascadePermission) throws SharingRegistryException, TException {
try{
if(permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))){
throw new SharingRegistryException(OWNER_PERMISSION_NAME + " permission cannot be assigned or removed");
}
List<Sharing> sharings = new ArrayList<>();
//Adding permission for the specified users/groups for the specified entity
LinkedList<Entity> temp = new LinkedList<>();
for(String userId : groupOrUserList){
Sharing sharing = new Sharing();
sharing.setPermissionTypeId(permissionTypeId);
sharing.setEntityId(entityId);
sharing.setGroupId(userId);
sharing.setInheritedParentId(entityId);
sharing.setDomainId(domainId);
if(cascadePermission) {
sharing.setSharingType(SharingType.DIRECT_CASCADING);
}else {
sharing.setSharingType(SharingType.DIRECT_NON_CASCADING);
}
sharing.setCreatedTime(System.currentTimeMillis());
sharing.setUpdatedTime(System.currentTimeMillis());
sharings.add(sharing);
}
if(cascadePermission){
//Adding permission for the specified users/groups for all child entities
(new EntityRepository()).getChildEntities(domainId, entityId).stream().forEach(e -> temp.addLast(e));
while(temp.size() > 0){
Entity entity = temp.pop();
String childEntityId = entity.getEntityId();
for(String userId : groupOrUserList){
Sharing sharing = new Sharing();
sharing.setPermissionTypeId(permissionTypeId);
sharing.setEntityId(childEntityId);
sharing.setGroupId(userId);
sharing.setInheritedParentId(entityId);
sharing.setSharingType(SharingType.INDIRECT_CASCADING);
sharing.setInheritedParentId(entityId);
sharing.setDomainId(domainId);
sharing.setCreatedTime(System.currentTimeMillis());
sharing.setUpdatedTime(System.currentTimeMillis());
sharings.add(sharing);
(new EntityRepository()).getChildEntities(domainId, childEntityId).stream().forEach(e -> temp.addLast(e));
}
}
}
(new SharingRepository()).create(sharings);
EntityPK entityPK = new EntityPK();
entityPK.setDomainId(domainId);
entityPK.setEntityId(entityId);
Entity entity = (new EntityRepository()).get(entityPK);
entity.setSharedCount((new SharingRepository()).getSharedCount(domainId, entityId));
(new EntityRepository()).update(entity);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean revokeEntitySharingFromUsers(String domainId, String entityId, List<String> userList, String permissionTypeId) throws SharingRegistryException, TException {
try{
if(permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))){
throw new SharingRegistryException(OWNER_PERMISSION_NAME + " permission cannot be assigned or removed");
}
return revokeEntitySharing(domainId, entityId, userList, permissionTypeId);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean revokeEntitySharingFromGroups(String domainId, String entityId, List<String> groupList, String permissionTypeId) throws SharingRegistryException, TException {
try{
if(permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))){
throw new SharingRegistryException(OWNER_PERMISSION_NAME + " permission cannot be assigned or removed");
}
return revokeEntitySharing(domainId, entityId, groupList, permissionTypeId);
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
@Override
public boolean userHasAccess(String domainId, String userId, String entityId, String permissionTypeId) throws SharingRegistryException, TException {
try{
//check whether the user has permission directly or indirectly
List<GroupMembership> parentMemberships = (new GroupMembershipRepository()).getAllParentMembershipsForChild(domainId, userId);
List<String> groupIds = new ArrayList<>();
parentMemberships.stream().forEach(pm->groupIds.add(pm.getParentId()));
groupIds.add(userId);
return (new SharingRepository()).hasAccess(domainId, entityId, groupIds, Arrays.asList(permissionTypeId,
(new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId)));
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
public boolean revokeEntitySharing(String domainId, String entityId, List<String> groupOrUserList, String permissionTypeId) throws SharingRegistryException {
try{
if(permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))){
throw new SharingRegistryException(OWNER_PERMISSION_NAME + " permission cannot be removed");
}
//revoking permission for the entity
for(String groupId : groupOrUserList){
SharingPK sharingPK = new SharingPK();
sharingPK.setEntityId(entityId);
sharingPK.setGroupId(groupId);
sharingPK.setPermissionTypeId(permissionTypeId);
sharingPK.setInheritedParentId(entityId);
sharingPK.setDomainId(domainId);
(new SharingRepository()).delete(sharingPK);
}
//revoking permission from inheritance
List<Sharing> temp = new ArrayList<>();
(new SharingRepository()).getIndirectSharedChildren(domainId, entityId, permissionTypeId).stream().forEach(s -> temp.add(s));
for(Sharing sharing : temp){
String childEntityId = sharing.getEntityId();
for(String groupId : groupOrUserList){
SharingPK sharingPK = new SharingPK();
sharingPK.setEntityId(childEntityId);
sharingPK.setGroupId(groupId);
sharingPK.setPermissionTypeId(permissionTypeId);
sharingPK.setInheritedParentId(entityId);
sharingPK.setDomainId(domainId);
(new SharingRepository()).delete(sharingPK);
}
}
EntityPK entityPK = new EntityPK();
entityPK.setDomainId(domainId);
entityPK.setEntityId(entityId);
Entity entity = (new EntityRepository()).get(entityPK);
entity.setSharedCount((new SharingRepository()).getSharedCount(domainId, entityId));
(new EntityRepository()).update(entity);
return true;
}catch (Throwable ex) {
logger.error(ex.getMessage(), ex);
throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex));
}
}
private <T> T getUpdatedObject(T oldEntity, T newEntity) throws SharingRegistryException {
Field[] newEntityFields = newEntity.getClass().getDeclaredFields();
Hashtable newHT = fieldsToHT(newEntityFields, newEntity);
Class oldEntityClass = oldEntity.getClass();
Field[] oldEntityFields = oldEntityClass.getDeclaredFields();
for (Field field : oldEntityFields){
if (!Modifier.isFinal(field.getModifiers())) {
field.setAccessible(true);
Object o = newHT.get(field.getName());
if (o != null) {
Field f = null;
try {
f = oldEntityClass.getDeclaredField(field.getName());
f.setAccessible(true);
logger.debug("setting " + f.getName());
f.set(oldEntity, o);
} catch (Exception e) {
throw new SharingRegistryException(e.getMessage());
}
}
}
}
return oldEntity;
}
private static Hashtable<String, Object> fieldsToHT(Field[] fields, Object obj){
Hashtable<String,Object> hashtable = new Hashtable<>();
for (Field field: fields){
field.setAccessible(true);
try {
Object retrievedObject = field.get(obj);
if (retrievedObject != null){
logger.debug("scanning " + field.getName());
hashtable.put(field.getName(), field.get(obj));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return hashtable;
}
}
| 672 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/server/SharingRegistryServer.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.sharing.registry.server;
import org.apache.airavata.common.exception.AiravataException;
import org.apache.airavata.common.utils.IServer;
import org.apache.airavata.common.utils.ServerSettings;
import org.apache.airavata.sharing.registry.db.utils.SharingRegistryDBInitConfig;
import org.apache.airavata.sharing.registry.messaging.SharingServiceDBEventMessagingFactory;
import org.apache.airavata.sharing.registry.models.SharingRegistryException;
import org.apache.airavata.sharing.registry.service.cpi.SharingRegistryService;
import org.apache.airavata.sharing.registry.utils.Constants;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TSSLTransportFactory;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
public class SharingRegistryServer implements IServer {
private final static Logger logger = LoggerFactory.getLogger(SharingRegistryServer.class);
public static final String SHARING_REG_SERVER_HOST = "sharing.registry.server.host";
public static final String SHARING_REG_SERVER_PORT = "sharing.registry.server.port";
private static final String SERVER_NAME = "Sharing Registry Server";
private static final String SERVER_VERSION = "1.0";
private IServer.ServerStatus status;
private TServer server;
private boolean testMode = false;
public SharingRegistryServer() {
setStatus(IServer.ServerStatus.STOPPED);
}
@Override
public String getName() {
return SERVER_NAME;
}
@Override
public String getVersion() {
return SERVER_VERSION;
}
@Override
public void start() throws Exception {
try {
setStatus(IServer.ServerStatus.STARTING);
final int serverPort = Integer.parseInt(ServerSettings.getSetting(SHARING_REG_SERVER_PORT));
final String serverHost = ServerSettings.getSetting(SHARING_REG_SERVER_HOST);
SharingRegistryService.Processor processor = new SharingRegistryService.Processor(
new SharingRegistryServerHandler(createSharingRegistryDBInitConfig()));
TServerTransport serverTransport;
if (!ServerSettings.isSharingTLSEnabled()) {
InetSocketAddress inetSocketAddress = new InetSocketAddress(serverHost, serverPort);
serverTransport = new TServerSocket(inetSocketAddress);
TThreadPoolServer.Args options = new TThreadPoolServer.Args(serverTransport);
options.minWorkerThreads = 30;
server = new TThreadPoolServer(options.processor(processor));
}else{
TSSLTransportFactory.TSSLTransportParameters TLSParams =
new TSSLTransportFactory.TSSLTransportParameters();
TLSParams.requireClientAuth(true);
TLSParams.setKeyStore(ServerSettings.getKeyStorePath(), ServerSettings.getKeyStorePassword());
if (ServerSettings.isTrustStorePathDefined()) {
TLSParams.setTrustStore(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
}
TServerSocket TLSServerTransport = TSSLTransportFactory.getServerSocket(
serverPort, ServerSettings.getTLSClientTimeout(),
InetAddress.getByName(serverHost), TLSParams);
TThreadPoolServer.Args options = new TThreadPoolServer.Args(TLSServerTransport);
options.minWorkerThreads = 30;
server = new TThreadPoolServer(options.processor(processor));
}
new Thread() {
public void run() {
server.serve();
setStatus(IServer.ServerStatus.STOPPED);
logger.info("Sharing Registry Server Stopped.");
}
}.start();
new Thread() {
public void run() {
while (!server.isServing()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
}
if (server.isServing()) {
try {
logger.info("Register sharing service with DB Event publishers");
SharingServiceDBEventMessagingFactory.registerSharingServiceWithPublishers(Constants.PUBLISHERS);
logger.info("Start sharing service DB Event subscriber");
SharingServiceDBEventMessagingFactory.getDBEventSubscriber();
} catch (AiravataException | SharingRegistryException e) {
logger.error("Error starting sharing service. Error setting up DB event services.");
server.stop();
}
setStatus(IServer.ServerStatus.STARTED);
logger.info("Starting Sharing Registry Server on Port " + serverPort);
logger.info("Listening to Sharing Registry server clients ....");
}
}
}.start();
} catch (TTransportException e) {
setStatus(IServer.ServerStatus.FAILED);
throw new Exception("Error while starting the Sharing Registry service", e);
}
}
@Override
public void stop() throws Exception {
if (server!=null && server.isServing()){
setStatus(IServer.ServerStatus.STOPING);
server.stop();
}
}
@Override
public void restart() throws Exception {
stop();
start();
}
@Override
public void configure() throws Exception {
}
@Override
public IServer.ServerStatus getStatus() throws Exception {
return status;
}
private void setStatus(IServer.ServerStatus stat){
status=stat;
status.updateTime();
}
public TServer getServer() {
return server;
}
public void setServer(TServer server) {
this.server = server;
}
public boolean isTestMode() {
return testMode;
}
public void setTestMode(boolean testMode) {
this.testMode = testMode;
}
private SharingRegistryDBInitConfig createSharingRegistryDBInitConfig() {
SharingRegistryDBInitConfig sharingRegistryDBInitConfig = new SharingRegistryDBInitConfig();
if (this.testMode) {
sharingRegistryDBInitConfig.setDBInitScriptPrefix("sharing-registry");
}
return sharingRegistryDBInitConfig;
}
}
| 673 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/server/ServerMain.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.sharing.registry.server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class ServerMain {
private final static Logger logger = LoggerFactory.getLogger(ServerMain.class);
private static long serverPID = -1;
private static final String stopFileNamePrefix = "server_stop";
private static final String serverStartedFileNamePrefix = "server_start";
public static void main(String[] args) {
try {
setServerStarted();
new SharingRegistryServer().start();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
@SuppressWarnings({"resource"})
private static void setServerStarted() {
try {
serverPID = getPID();
deleteOldStopRequests();
File serverStartedFile = null;
serverStartedFile = new File(getServerStartedFileName());
serverStartedFile.createNewFile();
serverStartedFile.deleteOnExit();
new RandomAccessFile(serverStartedFile, "rw").getChannel().lock();
} catch (FileNotFoundException e) {
logger.warn(e.getMessage(), e);
} catch (IOException e) {
logger.warn(e.getMessage(), e);
}
}
private static String getServerStartedFileName() {
String SHARING_REGISTRY_HOME = System.getenv("" +"SHARING_REGISTRY_HOME");
if(SHARING_REGISTRY_HOME==null)
SHARING_REGISTRY_HOME = "/tmp";
else
SHARING_REGISTRY_HOME = SHARING_REGISTRY_HOME + "/bin";
return new File(SHARING_REGISTRY_HOME, serverStartedFileNamePrefix + "_" + Long.toString(serverPID)).toString();
}
// private static int getPID() {
// try {
// java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory
// .getRuntimeMXBean();
// java.lang.reflect.Field jvm = runtime.getClass()
// .getDeclaredField("jvm");
// jvm.setAccessible(true);
// sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm
// .get(runtime);
// java.lang.reflect.Method pid_method = mgmt.getClass()
// .getDeclaredMethod("getProcessId");
// pid_method.setAccessible(true);
//
// int pid = (Integer) pid_method.invoke(mgmt);
// return pid;
// } catch (Exception e) {
// return -1;
// }
// }
//getPID from ProcessHandle JDK 9 and onwards
private static long getPID () {
try {
return ProcessHandle.current().pid();
} catch (Exception e) {
return -1;
}
}
private static void deleteOldStopRequests() {
File[] files = new File(".").listFiles();
for (File file : files) {
if (file.getName().contains(stopFileNamePrefix)) {
file.delete();
}
}
}
} | 674 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/utils/ThriftDataModelConversion.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.sharing.registry.utils;
import org.apache.airavata.model.user.UserProfile;
import org.apache.airavata.sharing.registry.models.User;
/**
* Created by Ajinkya on 3/29/17.
*/
public class ThriftDataModelConversion {
/**
* Build user object from UserProfile
* @param userProfile thrift object
* @return
* User corresponding to userProfile thrift
*/
public static User getUser(UserProfile userProfile){
User user = new User();
user.setUserId(userProfile.getAiravataInternalUserId());
user.setDomainId(userProfile.getGatewayId());
user.setUserName(userProfile.getUserId());
user.setFirstName(userProfile.getFirstName());
user.setLastName(userProfile.getLastName());
user.setEmail(userProfile.getEmails().get(0));
return user;
}
}
| 675 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/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.sharing.registry.utils;
import org.apache.airavata.common.utils.DBEventService;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ajinkya on 3/28/17.
*/
public class Constants {
/**
* List of publishers in which sharing service is interested.
* Add publishers as required
*/
public static final List<String> PUBLISHERS = new ArrayList<String>(){{
add(DBEventService.USER_PROFILE.toString());
add(DBEventService.TENANT.toString());
add(DBEventService.REGISTRY.toString());
add(DBEventService.IAM_ADMIN.toString());
}};
}
| 676 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/utils/JPAUtils.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.sharing.registry.db.utils;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.apache.airavata.common.utils.JDBCConfig;
public class JPAUtils {
public static final String PERSISTENCE_UNIT_NAME = "airavata-sharing-registry";
private static final JDBCConfig JDBC_CONFIG = new SharingRegistryJDBCConfig();
private static final EntityManagerFactory factory = org.apache.airavata.common.utils.JPAUtils.getEntityManagerFactory(PERSISTENCE_UNIT_NAME, JDBC_CONFIG);
public static EntityManager getEntityManager() {
return factory.createEntityManager();
}
}
| 677 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/utils/Committer.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.sharing.registry.db.utils;
@FunctionalInterface
public interface Committer<T, R> {
R commit(T t);
} | 678 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/utils/SharingRegistryJDBCConfig.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.sharing.registry.db.utils;
import org.apache.airavata.common.exception.ApplicationSettingsException;
import org.apache.airavata.common.utils.JDBCConfig;
import org.apache.airavata.common.utils.ServerSettings;
public class SharingRegistryJDBCConfig implements JDBCConfig {
private static final String SHARING_REG_JDBC_DRIVER = "sharingcatalog.jdbc.driver";
private static final String SHARING_REG_JDBC_URL = "sharingcatalog.jdbc.url";
private static final String SHARING_REG_JDBC_USER = "sharingcatalog.jdbc.user";
private static final String SHARING_REG_JDBC_PWD = "sharingcatalog.jdbc.password";
private static final String SHARING_REG_VALIDATION_QUERY = "sharingcatalog.validationQuery";
@Override
public String getURL() {
return readServerProperties(SHARING_REG_JDBC_URL);
}
@Override
public String getDriver() {
return readServerProperties(SHARING_REG_JDBC_DRIVER);
}
@Override
public String getUser() {
return readServerProperties(SHARING_REG_JDBC_USER);
}
@Override
public String getPassword() {
return readServerProperties(SHARING_REG_JDBC_PWD);
}
@Override
public String getValidationQuery() {
return readServerProperties(SHARING_REG_VALIDATION_QUERY);
}
private String readServerProperties(String propertyName) {
try {
return ServerSettings.getSetting(propertyName);
} catch (ApplicationSettingsException e) {
throw new RuntimeException("Unable to read airavata-server.properties...", e);
}
}
}
| 679 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/utils/DBConstants.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.sharing.registry.db.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DBConstants {
private final static Logger logger = LoggerFactory.getLogger(DBConstants.class);
public static int SELECT_MAX_ROWS = 1000;
public static class DomainTable {
public static final String DOMAIN_ID = "domainId";
public static final String NAME = "name";
public static final String DESCRIPTION = "description";
public static final String CREATED_TIME = "createdTime";
public static final String UPDATED_TIME = "updatedTime";
}
public static class UserTable {
public static final String USER_ID = "userId";
public static final String DOMAIN_ID = "domainId";
public static final String USER_NAME = "userName";
public static final String CREATED_TIME = "createdTime";
public static final String UPDATED_TIME = "updatedTime";
}
public static class UserGroupTable {
public static final String GROUP_ID = "groupId";
public static final String DOMAIN_ID = "domainId";
public static final String NAME = "name";
public static final String DESCRIPTION = "description";
public static final String OWNER_ID = "ownerId";
public static final String GROUP_TYPE = "groupType";
public static final String GROUP_CARDINALITY = "groupCardinality";
public static final String CREATED_TIME = "createdTime";
public static final String UPDATED_TIME = "updatedTime";
}
public static class GroupMembershipTable {
public static final String PARENT_ID = "parentId";
public static final String CHILD_ID = "childId";
public static final String CHILD_TYPE = "childType";
public static final String DOMAIN_ID = "domainId";
public static final String CREATED_TIME = "createdTime";
public static final String UPDATED_TIME = "updatedTime";
}
public static class EntityTypeTable {
public static final String ENTITY_TYPE_ID = "entityTypeId";
public static final String DOMAIN_ID = "domainId";
public static final String CREATED_TIME = "createdTime";
public static final String UPDATED_TIME = "updatedTime";
}
public static class PermissionTypeTable {
public static final String ENTITY_TYPE_ID = "permissionTypeId";
public static final String DOMAIN_ID = "domainId";
public static final String NAME = "name";
public static final String CREATED_TIME = "createdTime";
public static final String UPDATED_TIME = "updatedTime";
}
public static class EntityTable {
public static final String ENTITY_ID = "entityId";
public static final String PARENT_ENTITY_ID = "parentEntityId";
public static final String ENTITY_TYPE_ID = "entityTypeId";
public static final String NAME = "name";
public static final String DESCRIPTION = "description";
public static final String FULL_TEXT = "fullText";
public static final String CREATED_TIME = "createdTime";
public static final String UPDATED_TIME = "updatedTime";
public static final String DOMAIN_ID = "domainId";
public static final String ORIGINAL_ENTITY_CREATION_TIME = "originalEntityCreationTime";
public static final String SHARED = "shared";
}
public static class SharingTable {
public static final String DOMAIN_ID = "domainId";
public static final String PERMISSION_TYPE_ID = "permissionTypeId";
public static final String ENTITY_ID = "entityId";
public static final String GROUP_ID = "groupId";
public static final String INHERITED_PARENT_ID = "inheritedParentId";
public static final String SHARING_TYPE = "sharingType";
public static final String CREATED_TIME = "createdTime";
public static final String UPDATED_TIME = "updatedTime";
}
} | 680 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/utils/SharingRegistryDBInitConfig.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.sharing.registry.db.utils;
import org.apache.airavata.common.utils.DBInitConfig;
import org.apache.airavata.common.utils.JDBCConfig;
public class SharingRegistryDBInitConfig implements DBInitConfig {
private String dbInitScriptPrefix = "database_scripts/sharing-registry";
@Override
public JDBCConfig getJDBCConfig() {
return new SharingRegistryJDBCConfig();
}
@Override
public String getDBInitScriptPrefix() {
return this.dbInitScriptPrefix;
}
@Override
public String getCheckTableName() {
return "CONFIGURATION";
}
public void setDBInitScriptPrefix(String dbInitScriptPrefix) {
this.dbInitScriptPrefix = dbInitScriptPrefix;
}
}
| 681 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/utils/ObjectMapperSingleton.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.sharing.registry.db.utils;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ObjectMapperSingleton extends DozerBeanMapper{
private final static Logger logger = LoggerFactory.getLogger(ObjectMapperSingleton.class);
private static ObjectMapperSingleton instance;
private ObjectMapperSingleton(){}
public static ObjectMapperSingleton getInstance(){
if(instance == null)
instance = new ObjectMapperSingleton();
return instance;
}
} | 682 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/repositories/AbstractRepository.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.sharing.registry.db.repositories;
import org.apache.airavata.sharing.registry.db.utils.Committer;
import org.apache.airavata.sharing.registry.db.utils.DBConstants;
import org.apache.airavata.sharing.registry.db.utils.JPAUtils;
import org.apache.airavata.sharing.registry.db.utils.ObjectMapperSingleton;
import org.apache.airavata.sharing.registry.models.SharingRegistryException;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public abstract class AbstractRepository<T, E, Id> {
private final static Logger logger = LoggerFactory.getLogger(AbstractRepository.class);
private Class<T> thriftGenericClass;
private Class<E> dbEntityGenericClass;
public AbstractRepository(Class<T> thriftGenericClass, Class<E> dbEntityGenericClass){
this.thriftGenericClass = thriftGenericClass;
this.dbEntityGenericClass = dbEntityGenericClass;
}
public T create(T t) throws SharingRegistryException {
return update(t);
}
//FIXME do a bulk insert
public List<T> create(List<T> tList) throws SharingRegistryException {
return update(tList);
}
public T update(T t) throws SharingRegistryException {
Mapper mapper = ObjectMapperSingleton.getInstance();
E entity = mapper.map(t, dbEntityGenericClass);
E persistedCopy = execute(entityManager -> entityManager.merge(entity));
return mapper.map(persistedCopy, thriftGenericClass);
}
//FIXME do a bulk update
public List<T> update(List<T> tList) throws SharingRegistryException {
List<T> returnList = new ArrayList<>();
for(T temp : tList)
returnList.add(update(temp));
return returnList;
}
public boolean delete(Id id) throws SharingRegistryException {
execute(entityManager -> {
E entity = entityManager.find(dbEntityGenericClass, id);
entityManager.remove(entity);
return entity;
});
return true;
}
public boolean delete(List<Id> idList) throws SharingRegistryException {
for(Id id : idList)
delete(id);
return true;
}
public T get(Id id) throws SharingRegistryException {
E entity = execute(entityManager -> entityManager
.find(dbEntityGenericClass, id));
Mapper mapper = ObjectMapperSingleton.getInstance();
if(entity == null)
return null;
return mapper.map(entity, thriftGenericClass);
}
public boolean isExists(Id id) throws SharingRegistryException {
return get(id) != null;
}
public List<T> get(List<Id> idList) throws SharingRegistryException {
List<T> returnList = new ArrayList<>();
for(Id id : idList)
returnList.add(get(id));
return returnList;
}
public List<T> select(Map<String, String> filters, int offset, int limit) throws SharingRegistryException {
String query = "SELECT DISTINCT p from " + dbEntityGenericClass.getSimpleName() + " as p";
ArrayList<String> parameters = new ArrayList<>();
int parameterCount = 1;
if (filters != null && filters.size() != 0) {
query += " WHERE ";
for (String k : filters.keySet()) {
query += "p." + k + " = ?" + parameterCount + " AND ";
parameters.add(filters.get(k));
parameterCount++;
}
query = query.substring(0, query.length() - 5);
}
query += " ORDER BY p.createdTime DESC";
String queryString = query;
int newLimit = limit < 0 ? DBConstants.SELECT_MAX_ROWS: limit;
List resultSet = execute(entityManager -> {
javax.persistence.Query q = entityManager.createQuery(queryString);
for (int i = 0; i < parameters.size(); i++) {
q.setParameter(i + 1, parameters.get(i));
}
return q.setFirstResult(offset).setMaxResults(newLimit).getResultList();
});
Mapper mapper = ObjectMapperSingleton.getInstance();
List<T> gatewayList = new ArrayList<>();
resultSet.stream().forEach(rs -> gatewayList.add(mapper.map(rs, thriftGenericClass)));
return gatewayList;
}
public List<T> select(String queryString, Map<String,Object> queryParameters, int offset, int limit) throws SharingRegistryException {
int newLimit = limit < 0 ? DBConstants.SELECT_MAX_ROWS: limit;
List resultSet = execute(entityManager -> {
Query q = entityManager.createQuery(queryString);
for(Map.Entry<String, Object> queryParam : queryParameters.entrySet()){
q.setParameter(queryParam.getKey(), queryParam.getValue());
}
return q.setFirstResult(offset).setMaxResults(newLimit).getResultList();
});
Mapper mapper = ObjectMapperSingleton.getInstance();
List<T> gatewayList = new ArrayList<>();
resultSet.stream().forEach(rs -> gatewayList.add(mapper.map(rs, thriftGenericClass)));
return gatewayList;
}
public <R> R execute(Committer<EntityManager, R> committer) throws SharingRegistryException {
EntityManager entityManager = JPAUtils.getEntityManager();
try {
entityManager.getTransaction().begin();
R r = committer.commit(entityManager);
entityManager.getTransaction().commit();
return r;
} finally {
if (entityManager.isOpen()) {
if (entityManager.getTransaction().isActive()) {
entityManager.getTransaction().rollback();
}
entityManager.close();
}
}
}
} | 683 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/repositories/EntityRepository.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.sharing.registry.db.repositories;
import org.apache.airavata.sharing.registry.db.entities.EntityEntity;
import org.apache.airavata.sharing.registry.db.entities.EntityPK;
import org.apache.airavata.sharing.registry.db.utils.DBConstants;
import org.apache.airavata.sharing.registry.db.utils.SharingRegistryJDBCConfig;
import org.apache.airavata.sharing.registry.models.*;
import java.util.*;
public class EntityRepository extends AbstractRepository<Entity, EntityEntity, EntityPK> {
public EntityRepository() {
super(Entity.class, EntityEntity.class);
}
public List<Entity> getChildEntities(String domainId, String parentId) throws SharingRegistryException {
HashMap<String, String> filters = new HashMap<>();
filters.put(DBConstants.EntityTable.DOMAIN_ID, domainId);
filters.put(DBConstants.EntityTable.PARENT_ENTITY_ID, parentId);
return select(filters, 0, -1);
}
//TODO Replace with prepared statements
public List<Entity> searchEntities(String domainId, List<String> groupIds, List<SearchCriteria> filters,
int offset, int limit) throws SharingRegistryException {
String groupIdString = "'";
for(String groupId : groupIds)
groupIdString += groupId + "','";
groupIdString = groupIdString.substring(0, groupIdString.length()-2);
String query = "SELECT ENTITY.* FROM ENTITY WHERE ENTITY.ENTITY_ID IN (SELECT DISTINCT E.ENTITY_ID FROM ENTITY AS E INNER JOIN SHARING AS S ON (E.ENTITY_ID=S.ENTITY_ID AND E.DOMAIN_ID=S.DOMAIN_ID) WHERE " +
"E.DOMAIN_ID = '" + domainId + "' AND " + "S.GROUP_ID IN(" + groupIdString + ") AND ";
for(SearchCriteria searchCriteria : filters){
if(searchCriteria.getSearchField().equals(EntitySearchField.NAME)){
if (searchCriteria.getSearchCondition() != null && searchCriteria.getSearchCondition().equals(SearchCondition.NOT)) {
query += "E.NAME != '" + searchCriteria.getValue() + "' AND ";
} else {
query += "E.NAME LIKE '%" + searchCriteria.getValue() + "%' AND ";
}
}else if(searchCriteria.getSearchField().equals(EntitySearchField.DESCRIPTION)){
query += "E.DESCRIPTION LIKE '%" + searchCriteria.getValue() + "%' AND ";
}else if(searchCriteria.getSearchField().equals(EntitySearchField.PERMISSION_TYPE_ID)){
if (searchCriteria.getSearchCondition() != null && searchCriteria.getSearchCondition().equals(SearchCondition.NOT)) {
query += "S.PERMISSION_TYPE_ID != '" + searchCriteria.getValue() + "' AND ";
} else {
query += "S.PERMISSION_TYPE_ID IN ('" + searchCriteria.getValue() + "', '"
+ (new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId) + "') AND ";
}
}else if(searchCriteria.getSearchField().equals(EntitySearchField.FULL_TEXT)){
if (new SharingRegistryJDBCConfig().getDriver().contains("derby")) {
query += "E.FULL_TEXT LIKE '%" + searchCriteria.getValue() + "%' AND ";
} else {
// FULL TEXT Search with Query Expansion
String queryTerms = "";
for (String word : searchCriteria.getValue().trim().replaceAll(" +", " ").split(" ")) {
queryTerms += queryTerms + " +" + word;
}
queryTerms = queryTerms.trim();
query += "MATCH(E.FULL_TEXT) AGAINST ('" + queryTerms + "' IN BOOLEAN MODE) AND ";
}
}else if(searchCriteria.getSearchField().equals(EntitySearchField.PARRENT_ENTITY_ID)){
if (searchCriteria.getSearchCondition() != null && searchCriteria.getSearchCondition().equals(SearchCondition.NOT)) {
query += "E.PARENT_ENTITY_ID != '" + searchCriteria.getValue() + "' AND ";
} else {
query += "E.PARENT_ENTITY_ID = '" + searchCriteria.getValue() + "' AND ";
}
}else if(searchCriteria.getSearchField().equals(EntitySearchField.OWNER_ID)){
if (searchCriteria.getSearchCondition() != null && searchCriteria.getSearchCondition().equals(SearchCondition.NOT)) {
query += "E.OWNER_ID != '" + searchCriteria.getValue() + "' AND ";
} else {
query += "E.OWNER_ID = '" + searchCriteria.getValue() + "' AND ";
}
} else if (searchCriteria.getSearchField().equals(EntitySearchField.ENTITY_TYPE_ID)) {
if (searchCriteria.getSearchCondition() != null && searchCriteria.getSearchCondition().equals(SearchCondition.NOT)) {
query += "E.ENTITY_TYPE_ID != '" + searchCriteria.getValue() + "' AND ";
} else {
query += "E.ENTITY_TYPE_ID = '" + searchCriteria.getValue() + "' AND ";
}
}else if(searchCriteria.getSearchField().equals(EntitySearchField.CREATED_TIME)){
if(searchCriteria.getSearchCondition().equals(SearchCondition.GTE)){
query += "E.CREATED_TIME >= " + Long.parseLong(searchCriteria.getValue().trim()) + " AND ";
}else{
query += "E.CREATED_TIME <= " + Long.parseLong(searchCriteria.getValue().trim()) + " AND ";
}
}else if(searchCriteria.getSearchField().equals(EntitySearchField.UPDATED_TIME)){
if(searchCriteria.getSearchCondition().equals(SearchCondition.GTE)){
query += "E.UPDATED_TIME >= " + Long.parseLong(searchCriteria.getValue().trim()) + " AND ";
}else{
query += "E.UPDATED_TIME <= " + Long.parseLong(searchCriteria.getValue().trim()) + " AND ";
}
} else if (searchCriteria.getSearchField().equals(EntitySearchField.SHARED_COUNT)) {
if (searchCriteria.getSearchCondition().equals(SearchCondition.GTE)) {
query += "E.SHARED_COUNT >= " + Integer.parseInt(searchCriteria.getValue().trim()) + " AND ";
} else {
query += "E.SHARED_COUNT <= " + Integer.parseInt(searchCriteria.getValue().trim()) + " AND ";
}
}
}
query = query.substring(0, query.length() - 5);
query += ") ORDER BY ENTITY.CREATED_TIME DESC";
final String nativeQuery = query;
int newLimit = limit < 0 ? DBConstants.SELECT_MAX_ROWS: limit;
List<Object[]> temp = execute(entityManager -> entityManager.createNativeQuery(nativeQuery).setFirstResult(offset)
.setMaxResults(newLimit).getResultList());
List<Entity> resultSet = new ArrayList<>();
HashMap<String, Object> keys = new HashMap<>();
temp.stream().forEach(rs->{
Entity entity = new Entity();
entity.setEntityId((String)(rs[0]));
entity.setDomainId((String) (rs[1]));
entity.setEntityTypeId((String) (rs[2]));
entity.setOwnerId((String) (rs[3]));
entity.setParentEntityId((String) (rs[4]));
entity.setName((String) (rs[5]));
entity.setDescription((String)(rs[6]));
entity.setBinaryData((byte[]) (rs[7]));
entity.setFullText((String) (rs[8]));
entity.setSharedCount((long) rs[9]);
entity.setOriginalEntityCreationTime((long) (rs[10]));
entity.setCreatedTime((long) (rs[11]));
entity.setUpdatedTime((long) (rs[12]));
//Removing duplicates. Another option is to change the query to remove duplicates.
if (!keys.containsKey(entity + domainId + "," + entity.getEntityId())) {
resultSet.add(entity);
keys.put(entity + domainId + "," + entity.getEntityId(), null);
}
});
return resultSet;
}
public String getSelectQuery(Map<String, String> filters){
String query = "SELECT p from " + EntityEntity.class.getSimpleName() + " as p";
if(filters != null && filters.size() != 0){
query += " WHERE ";
for(String k : filters.keySet()){
query += "p." + k + " = '" + filters.get(k) + "' AND ";
}
query = query.substring(0, query.length()-5);
}
query += " ORDER BY p."+DBConstants.EntityTable.ORIGINAL_ENTITY_CREATION_TIME+" DESC";
return query;
}
}
| 684 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/repositories/UserGroupRepository.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.sharing.registry.db.repositories;
import org.apache.airavata.sharing.registry.db.entities.SharingEntity;
import org.apache.airavata.sharing.registry.db.entities.UserGroupEntity;
import org.apache.airavata.sharing.registry.db.entities.UserGroupPK;
import org.apache.airavata.sharing.registry.db.utils.DBConstants;
import org.apache.airavata.sharing.registry.models.GroupCardinality;
import org.apache.airavata.sharing.registry.models.SharingRegistryException;
import org.apache.airavata.sharing.registry.models.SharingType;
import org.apache.airavata.sharing.registry.models.UserGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class UserGroupRepository extends AbstractRepository<UserGroup, UserGroupEntity, UserGroupPK> {
private final static Logger logger = LoggerFactory.getLogger(UserGroupRepository.class);
public UserGroupRepository() {
super(UserGroup.class, UserGroupEntity.class);
}
public List<UserGroup> getAccessibleGroups(String domainId, String entityId, String permissionTypeId) throws SharingRegistryException {
return getAccessibleGroupsInternal(domainId, entityId, permissionTypeId);
}
public List<UserGroup> getDirectlyAccessibleGroups(String domainId, String entityId, String permissionTypeId) throws SharingRegistryException {
return getAccessibleGroupsInternal(domainId, entityId, permissionTypeId, SharingType.DIRECT_CASCADING, SharingType.DIRECT_NON_CASCADING);
}
private List<UserGroup> getAccessibleGroupsInternal(String domainId, String entityId, String permissionTypeId, SharingType... sharingTypes) throws SharingRegistryException {
String query = "SELECT DISTINCT g from " + UserGroupEntity.class.getSimpleName() + " g, " + SharingEntity.class.getSimpleName() + " s";
query += " WHERE ";
query += "g." + DBConstants.UserGroupTable.GROUP_ID + " = s." + DBConstants.SharingTable.GROUP_ID + " AND ";
query += "g." + DBConstants.UserGroupTable.DOMAIN_ID + " = s." + DBConstants.SharingTable.DOMAIN_ID + " AND ";
query += "g." + DBConstants.UserGroupTable.DOMAIN_ID + " = :" + DBConstants.UserGroupTable.DOMAIN_ID + " AND ";
query += "s." + DBConstants.SharingTable.ENTITY_ID + " = :" + DBConstants.SharingTable.ENTITY_ID + " AND ";
query += "s." + DBConstants.SharingTable.PERMISSION_TYPE_ID + " = :" + DBConstants.SharingTable.PERMISSION_TYPE_ID + " AND ";
query += "g." + DBConstants.UserGroupTable.GROUP_CARDINALITY + " = :" + DBConstants.UserGroupTable.GROUP_CARDINALITY;
if (!Arrays.asList(sharingTypes).isEmpty()) {
query += " AND s." + DBConstants.SharingTable.SHARING_TYPE + " IN :" + DBConstants.SharingTable.SHARING_TYPE;
}
query += " ORDER BY s.createdTime DESC";
Map<String,Object> queryParameters = new HashMap<>();
queryParameters.put(DBConstants.UserGroupTable.DOMAIN_ID, domainId);
queryParameters.put(DBConstants.SharingTable.ENTITY_ID, entityId);
queryParameters.put(DBConstants.SharingTable.PERMISSION_TYPE_ID, permissionTypeId);
queryParameters.put(DBConstants.UserGroupTable.GROUP_CARDINALITY, GroupCardinality.MULTI_USER.toString());
if (!Arrays.asList(sharingTypes).isEmpty()) {
queryParameters.put(DBConstants.SharingTable.SHARING_TYPE, Arrays.asList(sharingTypes).stream().map(s -> s.name()).collect(Collectors.toList()));
}
return select(query, queryParameters, 0, -1);
}
//checks whether is shared with any user or group with any permission
public boolean isShared(String domainId, String entityId) throws SharingRegistryException {
String query = "SELECT DISTINCT g from " + UserGroupEntity.class.getSimpleName() + " g, " + SharingEntity.class.getSimpleName() + " s";
query += " WHERE ";
query += "g." + DBConstants.UserGroupTable.GROUP_ID + " = s." + DBConstants.SharingTable.GROUP_ID + " AND ";
query += "g." + DBConstants.UserGroupTable.DOMAIN_ID + " = s." + DBConstants.SharingTable.DOMAIN_ID + " AND ";
query += "g." + DBConstants.UserGroupTable.DOMAIN_ID + " = :" + DBConstants.UserGroupTable.DOMAIN_ID + " AND ";
query += "s." + DBConstants.SharingTable.ENTITY_ID + " = :" + DBConstants.SharingTable.ENTITY_ID + " AND ";
query += "s." + DBConstants.SharingTable.PERMISSION_TYPE_ID + " <> :" + DBConstants.SharingTable.PERMISSION_TYPE_ID;
query += " ORDER BY s.createdTime DESC";
Map<String,Object> queryParameters = new HashMap<>();
queryParameters.put(DBConstants.UserGroupTable.DOMAIN_ID, domainId);
queryParameters.put(DBConstants.SharingTable.ENTITY_ID, entityId);
String ownerPermissionTypeIdForDomain = (new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId);
queryParameters.put(DBConstants.SharingTable.PERMISSION_TYPE_ID, ownerPermissionTypeIdForDomain);
return select(query, queryParameters, 0, -1).size() != 0;
}
}
| 685 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/repositories/PermissionTypeRepository.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.sharing.registry.db.repositories;
import org.apache.airavata.sharing.registry.db.entities.PermissionTypeEntity;
import org.apache.airavata.sharing.registry.db.entities.PermissionTypePK;
import org.apache.airavata.sharing.registry.db.utils.DBConstants;
import org.apache.airavata.sharing.registry.models.SharingRegistryException;
import org.apache.airavata.sharing.registry.models.PermissionType;
import org.apache.airavata.sharing.registry.server.SharingRegistryServerHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
public class PermissionTypeRepository extends AbstractRepository<PermissionType, PermissionTypeEntity, PermissionTypePK> {
private final static Logger logger = LoggerFactory.getLogger(PermissionTypeRepository.class);
public PermissionTypeRepository() {
super(PermissionType.class, PermissionTypeEntity.class);
}
public String getOwnerPermissionTypeIdForDomain(String domainId) throws SharingRegistryException {
HashMap<String, String> filters = new HashMap<>();
filters.put(DBConstants.PermissionTypeTable.DOMAIN_ID, domainId);
filters.put(DBConstants.PermissionTypeTable.NAME, SharingRegistryServerHandler.OWNER_PERMISSION_NAME);
List<PermissionType> permissionTypeList = select(filters, 0, -1);
if(permissionTypeList.size() != 1){
throw new SharingRegistryException("GLOBAL Permission inconsistency. Found " + permissionTypeList.size()
+ " records with " + SharingRegistryServerHandler.OWNER_PERMISSION_NAME + " name");
}
return permissionTypeList.get(0).getPermissionTypeId();
}
} | 686 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/repositories/EntityTypeRepository.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.sharing.registry.db.repositories;
import org.apache.airavata.sharing.registry.db.entities.EntityTypeEntity;
import org.apache.airavata.sharing.registry.db.entities.EntityTypePK;
import org.apache.airavata.sharing.registry.models.EntityType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EntityTypeRepository extends AbstractRepository<EntityType, EntityTypeEntity, EntityTypePK> {
private final static Logger logger = LoggerFactory.getLogger(EntityTypeRepository.class);
public EntityTypeRepository() {
super(EntityType.class, EntityTypeEntity.class);
}
} | 687 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/repositories/SharingRepository.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.sharing.registry.db.repositories;
import org.apache.airavata.sharing.registry.db.entities.SharingEntity;
import org.apache.airavata.sharing.registry.db.entities.SharingPK;
import org.apache.airavata.sharing.registry.db.utils.DBConstants;
import org.apache.airavata.sharing.registry.models.Sharing;
import org.apache.airavata.sharing.registry.models.SharingRegistryException;
import org.apache.airavata.sharing.registry.models.SharingType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
public class SharingRepository extends AbstractRepository<Sharing, SharingEntity, SharingPK> {
private final static Logger logger = LoggerFactory.getLogger(SharingRepository.class);
public SharingRepository() {
super(Sharing.class, SharingEntity.class);
}
public List<Sharing> getIndirectSharedChildren(String domainId, String parentId, String permissionTypeId) throws SharingRegistryException {
HashMap<String, String> filters = new HashMap<>();
filters.put(DBConstants.SharingTable.DOMAIN_ID, domainId);
filters.put(DBConstants.SharingTable.INHERITED_PARENT_ID, parentId);
filters.put(DBConstants.SharingTable.SHARING_TYPE, SharingType.INDIRECT_CASCADING.toString());
filters.put(DBConstants.SharingTable.PERMISSION_TYPE_ID, permissionTypeId);
return select(filters, 0, -1);
}
public List<Sharing> getCascadingPermissionsForEntity(String domainId, String entityId) throws SharingRegistryException {
String query = "SELECT DISTINCT p from " + SharingEntity.class.getSimpleName() + " as p";
query += " WHERE ";
query += "p." + DBConstants.SharingTable.DOMAIN_ID + " = :" + DBConstants.SharingTable.DOMAIN_ID + " AND ";
query += "p." + DBConstants.SharingTable.ENTITY_ID + " = :" + DBConstants.SharingTable.ENTITY_ID + " AND ";
query += "p." + DBConstants.SharingTable.SHARING_TYPE + " IN('" + SharingType.DIRECT_CASCADING.toString()
+ "', '" + SharingType.INDIRECT_CASCADING + "') ";
query += " ORDER BY p.createdTime DESC";
Map<String,Object> queryParameters = new HashMap<>();
queryParameters.put(DBConstants.SharingTable.DOMAIN_ID, domainId);
queryParameters.put(DBConstants.SharingTable.ENTITY_ID, entityId);
return select(query, queryParameters, 0, -1);
}
public boolean hasAccess(String domainId, String entityId, List<String> groupIds, List<String> permissionTypeIds) throws SharingRegistryException {
Map<String,Object> queryParameters = new HashMap<>();
String query = "SELECT p from " + SharingEntity.class.getSimpleName() + " as p";
query += " WHERE ";
query += "p." + DBConstants.SharingTable.DOMAIN_ID + " = :" + DBConstants.SharingTable.DOMAIN_ID + " AND ";
query += "p." + DBConstants.SharingTable.ENTITY_ID + " = :" + DBConstants.SharingTable.ENTITY_ID + " AND ";
queryParameters.put(DBConstants.SharingTable.DOMAIN_ID, domainId);
queryParameters.put(DBConstants.SharingTable.ENTITY_ID, entityId);
query += "p." + DBConstants.SharingTable.PERMISSION_TYPE_ID + " IN :" + DBConstants.SharingTable.PERMISSION_TYPE_ID + " AND ";
queryParameters.put(DBConstants.SharingTable.PERMISSION_TYPE_ID, permissionTypeIds);
query += "p." + DBConstants.SharingTable.GROUP_ID + " IN :" + DBConstants.SharingTable.GROUP_ID + " ";
queryParameters.put(DBConstants.SharingTable.GROUP_ID, groupIds);
query += " ORDER BY p.createdTime DESC";
return select(query, queryParameters, 0, -1).size() > 0;
}
public int getSharedCount(String domainId, String entityId) throws SharingRegistryException {
Map<String,Object> queryParameters = new HashMap<>();
String query = "SELECT p from " + SharingEntity.class.getSimpleName() + " as p";
query += " WHERE ";
query += "p." + DBConstants.SharingTable.DOMAIN_ID + " = :" + DBConstants.SharingTable.DOMAIN_ID + " AND ";
queryParameters.put(DBConstants.SharingTable.DOMAIN_ID, domainId);
query += "p." + DBConstants.SharingTable.ENTITY_ID + " = :" + DBConstants.SharingTable.ENTITY_ID + " AND ";
queryParameters.put(DBConstants.SharingTable.ENTITY_ID, entityId);
String permissionTypeIdString = (new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId);
query += "p." + DBConstants.SharingTable.PERMISSION_TYPE_ID + " <> :" + DBConstants.SharingTable.PERMISSION_TYPE_ID + " AND ";
queryParameters.put(DBConstants.SharingTable.PERMISSION_TYPE_ID, permissionTypeIdString);
query += "p." + DBConstants.SharingTable.SHARING_TYPE + " <> :" + DBConstants.SharingTable.SHARING_TYPE;
queryParameters.put(DBConstants.SharingTable.SHARING_TYPE, SharingType.INDIRECT_CASCADING.toString());
return select(query, queryParameters, 0, -1).size();
}
public void removeAllIndirectCascadingPermissionsForEntity(String domainId, String entityId) throws SharingRegistryException {
String query = "DELETE from " + SharingEntity.class.getSimpleName() + " as p";
query += " WHERE ";
query += "p." + DBConstants.SharingTable.DOMAIN_ID + " = :" + DBConstants.SharingTable.DOMAIN_ID + " AND ";
query += "p." + DBConstants.SharingTable.ENTITY_ID + " = :" + DBConstants.SharingTable.ENTITY_ID + " AND ";
query += "p." + DBConstants.SharingTable.SHARING_TYPE + " = '" + SharingType.INDIRECT_CASCADING.toString() + "' ";
final String finalQuery = query;
execute(em -> {
Query q = em.createQuery(finalQuery);
q.setParameter(DBConstants.SharingTable.DOMAIN_ID, domainId);
q.setParameter(DBConstants.SharingTable.ENTITY_ID, entityId);
q.executeUpdate();
return true;
});
}
}
| 688 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/repositories/GroupMembershipRepository.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.sharing.registry.db.repositories;
import org.apache.airavata.sharing.registry.db.entities.GroupMembershipEntity;
import org.apache.airavata.sharing.registry.db.entities.GroupMembershipPK;
import org.apache.airavata.sharing.registry.db.entities.UserEntity;
import org.apache.airavata.sharing.registry.db.entities.UserGroupEntity;
import org.apache.airavata.sharing.registry.db.utils.DBConstants;
import org.apache.airavata.sharing.registry.models.*;
import java.util.*;
public class GroupMembershipRepository extends AbstractRepository<GroupMembership, GroupMembershipEntity, GroupMembershipPK> {
public GroupMembershipRepository() {
super(GroupMembership.class, GroupMembershipEntity.class);
}
public List<User> getAllChildUsers(String domainId, String groupId) throws SharingRegistryException {
String queryString = "SELECT DISTINCT U FROM " + UserEntity.class.getSimpleName() + " U, " + GroupMembershipEntity.class.getSimpleName()
+ " GM WHERE GM." + DBConstants.GroupMembershipTable.CHILD_ID + " = U." + DBConstants.UserTable.USER_ID + " AND " +
"GM." + DBConstants.GroupMembershipTable.DOMAIN_ID + " = U." + DBConstants.UserTable.DOMAIN_ID + " AND " +
"GM." + DBConstants.GroupMembershipTable.DOMAIN_ID + "=:" + DBConstants.GroupMembershipTable.DOMAIN_ID + " AND "+
"GM." + DBConstants.GroupMembershipTable.PARENT_ID + "=:" + DBConstants.GroupMembershipTable.PARENT_ID + " AND GM." + DBConstants.GroupMembershipTable.CHILD_TYPE
+ "=:" + DBConstants.GroupMembershipTable.CHILD_TYPE;
Map<String,Object> queryParameters = new HashMap<>();
queryParameters.put(DBConstants.GroupMembershipTable.DOMAIN_ID, domainId);
queryParameters.put(DBConstants.GroupMembershipTable.PARENT_ID, groupId);
queryParameters.put(DBConstants.GroupMembershipTable.CHILD_TYPE, GroupChildType.USER.toString());
UserRepository userRepository = new UserRepository();
List<User> users = userRepository.select(queryString, queryParameters, 0, -1);
return users;
}
public List<UserGroup> getAllChildGroups(String domainId, String groupId) throws SharingRegistryException {
String queryString = "SELECT DISTINCT G FROM " + UserGroupEntity.class.getSimpleName() + " G, " + GroupMembershipEntity.class.getSimpleName()
+ " GM WHERE GM." + DBConstants.GroupMembershipTable.CHILD_ID + " = G." + DBConstants.UserGroupTable.GROUP_ID + " AND " +
"GM." + DBConstants.GroupMembershipTable.DOMAIN_ID + " = G." + DBConstants.UserGroupTable.DOMAIN_ID + " AND " +
"GM." + DBConstants.GroupMembershipTable.DOMAIN_ID+"=:"+DBConstants.GroupMembershipTable.DOMAIN_ID + " AND "+
"GM." + DBConstants.GroupMembershipTable.PARENT_ID+"=:"+DBConstants.GroupMembershipTable.PARENT_ID + " AND GM." + DBConstants.GroupMembershipTable.CHILD_TYPE
+ "=:" + DBConstants.GroupMembershipTable.CHILD_TYPE;
Map<String,Object> queryParameters = new HashMap<>();
queryParameters.put(DBConstants.GroupMembershipTable.DOMAIN_ID, domainId);
queryParameters.put(DBConstants.GroupMembershipTable.PARENT_ID, groupId);
queryParameters.put(DBConstants.GroupMembershipTable.CHILD_TYPE, GroupChildType.GROUP.toString());
UserGroupRepository userGroupRepository = new UserGroupRepository();
List<UserGroup> groups = userGroupRepository.select(queryString, queryParameters,0, -1);
return groups;
}
public List<UserGroup> getAllMemberGroupsForUser(String domainId, String userId) throws SharingRegistryException {
String queryString = "SELECT DISTINCT G FROM " + UserGroupEntity.class.getSimpleName() + " G, " + GroupMembershipEntity.class.getSimpleName()
+ " GM WHERE GM." + DBConstants.GroupMembershipTable.PARENT_ID + " = G." + DBConstants.UserGroupTable.GROUP_ID + " AND " +
"GM." + DBConstants.GroupMembershipTable.DOMAIN_ID + " = G." + DBConstants.UserGroupTable.DOMAIN_ID + " AND " +
"GM." + DBConstants.GroupMembershipTable.DOMAIN_ID+"=:"+DBConstants.GroupMembershipTable.DOMAIN_ID + " AND "+
"GM." + DBConstants.GroupMembershipTable.CHILD_ID+"=:"+DBConstants.GroupMembershipTable.CHILD_ID + " AND GM." + DBConstants.GroupMembershipTable.CHILD_TYPE
+ "=:" + DBConstants.GroupMembershipTable.CHILD_TYPE + " AND " +
"G." + DBConstants.UserGroupTable.GROUP_CARDINALITY + "=:" + DBConstants.UserGroupTable.GROUP_CARDINALITY;
Map<String,Object> queryParameters = new HashMap<>();
queryParameters.put(DBConstants.GroupMembershipTable.DOMAIN_ID, domainId);
queryParameters.put(DBConstants.GroupMembershipTable.CHILD_ID, userId);
queryParameters.put(DBConstants.GroupMembershipTable.CHILD_TYPE, GroupChildType.USER.toString());
queryParameters.put(DBConstants.UserGroupTable.GROUP_CARDINALITY, GroupCardinality.MULTI_USER.name());
UserGroupRepository userGroupRepository = new UserGroupRepository();
List<UserGroup> groups = userGroupRepository.select(queryString, queryParameters, 0, -1);
return groups;
}
public List<GroupMembership> getAllParentMembershipsForChild(String domainId, String childId) throws SharingRegistryException {
List<GroupMembership> finalParentGroups = new ArrayList<>();
Map<String, String> filters = new HashMap<>();
filters.put(DBConstants.GroupMembershipTable.CHILD_ID, childId);
filters.put(DBConstants.GroupMembershipTable.DOMAIN_ID, domainId);
LinkedList<GroupMembership> temp = new LinkedList<>();
select(filters, 0, -1).stream().forEach(m -> temp.addLast(m));
while (temp.size() > 0){
GroupMembership gm = temp.pop();
filters = new HashMap<>();
filters.put(DBConstants.GroupMembershipTable.CHILD_ID, gm.getParentId());
filters.put(DBConstants.GroupMembershipTable.DOMAIN_ID, domainId);
select(filters, 0, -1).stream().forEach(m -> temp.addLast(m));
finalParentGroups.add(gm);
}
return finalParentGroups;
}
} | 689 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/repositories/GroupAdminRepository.java | package org.apache.airavata.sharing.registry.db.repositories;
import org.apache.airavata.sharing.registry.db.entities.GroupAdminEntity;
import org.apache.airavata.sharing.registry.db.entities.GroupAdminPK;
import org.apache.airavata.sharing.registry.models.GroupAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GroupAdminRepository extends AbstractRepository<GroupAdmin, GroupAdminEntity, GroupAdminPK> {
private final static Logger logger = LoggerFactory.getLogger(GroupAdminRepository.class);
public GroupAdminRepository() {
super(GroupAdmin.class, GroupAdminEntity.class);
}
}
| 690 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/repositories/UserRepository.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.sharing.registry.db.repositories;
import org.apache.airavata.sharing.registry.db.entities.SharingEntity;
import org.apache.airavata.sharing.registry.db.entities.UserEntity;
import org.apache.airavata.sharing.registry.db.entities.UserPK;
import org.apache.airavata.sharing.registry.db.utils.DBConstants;
import org.apache.airavata.sharing.registry.models.SharingRegistryException;
import org.apache.airavata.sharing.registry.models.SharingType;
import org.apache.airavata.sharing.registry.models.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class UserRepository extends AbstractRepository<User, UserEntity, UserPK> {
private final static Logger logger = LoggerFactory.getLogger(UserRepository.class);
public UserRepository() {
super(User.class, UserEntity.class);
}
public List<User> getAccessibleUsers(String domainId, String entityId, String permissionTypeId) throws SharingRegistryException {
if(permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))){
return getAccessibleUsersInternal(domainId, entityId, permissionTypeId, SharingType.DIRECT_CASCADING, SharingType.DIRECT_NON_CASCADING);
} else {
return getAccessibleUsersInternal(domainId, entityId, permissionTypeId);
}
}
public List<User> getDirectlyAccessibleUsers(String domainId, String entityId, String permissionTypeId) throws SharingRegistryException {
return getAccessibleUsersInternal(domainId, entityId, permissionTypeId, SharingType.DIRECT_CASCADING, SharingType.DIRECT_NON_CASCADING);
}
private List<User> getAccessibleUsersInternal(String domainId, String entityId, String permissionTypeId, SharingType... sharingTypes) throws SharingRegistryException {
Map<String,Object> queryParameters = new HashMap<>();
String query = "SELECT DISTINCT u from " + UserEntity.class.getSimpleName() + " u, " + SharingEntity.class.getSimpleName() + " s";
query += " WHERE ";
query += "u." + DBConstants.UserTable.USER_ID + " = s." + DBConstants.SharingTable.GROUP_ID + " AND ";
query += "u." + DBConstants.UserTable.DOMAIN_ID + " = s." + DBConstants.SharingTable.DOMAIN_ID + " AND ";
query += "u." + DBConstants.UserTable.DOMAIN_ID + " = :" + DBConstants.UserTable.DOMAIN_ID + " AND ";
query += "s." + DBConstants.SharingTable.ENTITY_ID + " = :" + DBConstants.SharingTable.ENTITY_ID + " AND ";
query += "s." + DBConstants.SharingTable.PERMISSION_TYPE_ID + " = :" + DBConstants.SharingTable.PERMISSION_TYPE_ID;
queryParameters.put(DBConstants.UserTable.DOMAIN_ID, domainId);
queryParameters.put(DBConstants.SharingTable.ENTITY_ID, entityId);
queryParameters.put(DBConstants.SharingTable.PERMISSION_TYPE_ID, permissionTypeId);
if (!Arrays.asList(sharingTypes).isEmpty()) {
query += " AND s." + DBConstants.SharingTable.SHARING_TYPE + " IN :" + DBConstants.SharingTable.SHARING_TYPE;
queryParameters.put(DBConstants.SharingTable.SHARING_TYPE, Arrays.asList(sharingTypes).stream().map(s -> s.name()).collect(Collectors.toList()));
}
query += " ORDER BY s.createdTime DESC";
return select(query, queryParameters,0, -1);
}
}
| 691 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/repositories/DomainRepository.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.sharing.registry.db.repositories;
import org.apache.airavata.sharing.registry.db.entities.DomainEntity;
import org.apache.airavata.sharing.registry.models.Domain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DomainRepository extends AbstractRepository<Domain, DomainEntity, String> {
private final static Logger logger = LoggerFactory.getLogger(DomainRepository.class);
public DomainRepository(){
super(Domain.class, DomainEntity.class);
}
} | 692 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/entities/GroupMembershipEntity.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.sharing.registry.db.entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.*;
@Entity
@Table(name = "GROUP_MEMBERSHIP", schema = "")
@IdClass(GroupMembershipPK.class)
public class GroupMembershipEntity {
private final static Logger logger = LoggerFactory.getLogger(GroupMembershipEntity.class);
private String parentId;
private String childId;
private String childType;
private String domainId;
private Long createdTime;
private Long updatedTime;
@Id
@Column(name = "PARENT_ID")
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
@Id
@Column(name = "CHILD_ID")
public String getChildId() {
return childId;
}
public void setChildId(String childId) {
this.childId = childId;
}
@Id
@Column(name = "DOMAIN_ID")
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
@Basic
@Column(name = "CHILD_TYPE")
public String getChildType() {
return childType;
}
public void setChildType(String childType) {
this.childType = childType;
}
@Basic
@Column(name = "CREATED_TIME")
public Long getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Long createdTime) {
this.createdTime = createdTime;
}
@Basic
@Column(name = "UPDATED_TIME")
public Long getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Long updatedTime) {
this.updatedTime = updatedTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GroupMembershipEntity that = (GroupMembershipEntity) o;
if (getParentId() != null ? !getParentId().equals(that.getParentId()) : that.getParentId() != null)
return false;
if (getChildId() != null ? !getChildId().equals(that.getChildId()) : that.getChildId() != null) return false;
if (getChildType() != null ? !getChildType().equals(that.getChildType()) : that.getChildType() != null)
return false;
if (getCreatedTime() != null ? !getCreatedTime().equals(that.getCreatedTime()) : that.getCreatedTime() != null)
return false;
if (getUpdatedTime() != null ? !getUpdatedTime().equals(that.getUpdatedTime()) : that.getUpdatedTime() != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = getParentId() != null ? getParentId().hashCode() : 0;
result = 31 * result + (getChildId() != null ? getChildId().hashCode() : 0);
result = 31 * result + (getChildType() != null ? getChildType().hashCode() : 0);
return result;
}
} | 693 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/entities/EntityTypePK.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.sharing.registry.db.entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
public class EntityTypePK implements Serializable {
private final static Logger logger = LoggerFactory.getLogger(EntityTypePK.class);
private String entityTypeId;
private String domainId;
@Column(name = "ENTITY_TYPE_ID")
@Id
public String getEntityTypeId() {
return entityTypeId;
}
public void setEntityTypeId(String entityTypeId) {
this.entityTypeId = entityTypeId;
}
@Column(name = "DOMAIN_ID")
@Id
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EntityTypePK that = (EntityTypePK) o;
if (getEntityTypeId() != null ? !getEntityTypeId().equals(that.getEntityTypeId()) : that.getEntityTypeId() != null)
return false;
if (getDomainId() != null ? !getDomainId().equals(that.getDomainId()) : that.getDomainId() != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = getEntityTypeId() != null ? getEntityTypeId().hashCode() : 0;
result = 31 * result + (getDomainId() != null ? getDomainId().hashCode() : 0);
return result;
}
} | 694 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/entities/PermissionTypePK.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.sharing.registry.db.entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
public class PermissionTypePK implements Serializable {
private final static Logger logger = LoggerFactory.getLogger(PermissionTypePK.class);
private String permissionTypeId;
private String domainId;
@Column(name = "PERMISSION_TYPE_ID")
@Id
public String getPermissionTypeId() {
return permissionTypeId;
}
public void setPermissionTypeId(String permissionTypeId) {
this.permissionTypeId = permissionTypeId;
}
@Column(name = "DOMAIN_ID")
@Id
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PermissionTypePK that = (PermissionTypePK) o;
if (getPermissionTypeId() != null ? !getPermissionTypeId().equals(that.getPermissionTypeId()) : that.getPermissionTypeId() != null)
return false;
if (getDomainId() != null ? !getDomainId().equals(that.getDomainId()) : that.getDomainId() != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = getPermissionTypeId() != null ? getPermissionTypeId().hashCode() : 0;
result = 31 * result + (getDomainId() != null ? getDomainId().hashCode() : 0);
return result;
}
} | 695 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/entities/GroupAdminPK.java | package org.apache.airavata.sharing.registry.db.entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
public class GroupAdminPK implements Serializable{
private final static Logger logger = LoggerFactory.getLogger(GroupAdminPK.class);
private String groupId;
private String domainId;
private String adminId;
@Id
@Column(name = "GROUP_ID")
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
@Id
@Column(name = "DOMAIN_ID")
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
@Id
@Column(name = "ADMIN_ID")
public String getAdminId() {
return adminId;
}
public void setAdminId(String adminId) {
this.adminId = adminId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GroupAdminPK groupAdminPK = (GroupAdminPK) o;
if (!getGroupId().equals(groupAdminPK.getGroupId())) return false;
if (!getDomainId().equals(groupAdminPK.getDomainId())) return false;
return getAdminId().equals(groupAdminPK.getAdminId());
}
@Override
public int hashCode() {
int result = getGroupId().hashCode();
result = 31 * result + getDomainId().hashCode();
result = 31 * result + getAdminId().hashCode();
return result;
}
}
| 696 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/entities/GroupAdminEntity.java | package org.apache.airavata.sharing.registry.db.entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.*;
@Entity
@Table(name = "GROUP_ADMIN", schema = "")
@IdClass(GroupAdminPK.class)
public class GroupAdminEntity {
private final static Logger logger = LoggerFactory.getLogger(GroupAdminEntity.class);
private String groupId;
private String domainId;
private String adminId;
private UserGroupEntity userGroup;
@Id
@Column(name = "GROUP_ID")
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
@Id
@Column(name = "DOMAIN_ID")
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
@Id
@Column(name = "ADMIN_ID")
public String getAdminId() {
return adminId;
}
public void setAdminId(String adminId) {
this.adminId = adminId;
}
@ManyToOne(targetEntity = UserGroupEntity.class, cascade = CascadeType.MERGE)
@JoinColumns({
@JoinColumn(name="GROUP_ID", referencedColumnName="GROUP_ID"),
@JoinColumn(name="DOMAIN_ID", referencedColumnName="DOMAIN_ID")
})
public UserGroupEntity getUserGroup() {
return userGroup;
}
public void setUserGroup(UserGroupEntity userGroup) {
this.userGroup = userGroup;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GroupAdminEntity that = (GroupAdminEntity) o;
if (!getGroupId().equals(that.getGroupId())) return false;
if (!getDomainId().equals(that.getDomainId())) return false;
return getAdminId().equals(that.getAdminId());
}
@Override
public int hashCode() {
int result = getGroupId().hashCode();
result = 31 * result + getDomainId().hashCode();
result = 31 * result + getAdminId().hashCode();
return result;
}
}
| 697 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/entities/SharingPK.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.sharing.registry.db.entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.Column;
import javax.persistence.Id;
import java.io.Serializable;
public class SharingPK implements Serializable {
private final static Logger logger = LoggerFactory.getLogger(SharingPK.class);
private String permissionTypeId;
private String entityId;
private String groupId;
private String inheritedParentId;
private String domainId;
@Column(name = "PERMISSION_TYPE_ID")
@Id
public String getPermissionTypeId() {
return permissionTypeId;
}
public void setPermissionTypeId(String permissionTypeId) {
this.permissionTypeId = permissionTypeId;
}
@Column(name = "ENTITY_ID")
@Id
public String getEntityId() {
return entityId;
}
public void setEntityId(String entityId) {
this.entityId = entityId;
}
@Column(name = "GROUP_ID")
@Id
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
@Column(name = "INHERITED_PARENT_ID")
@Id
public String getInheritedParentId() {
return inheritedParentId;
}
public void setInheritedParentId(String inheritedParentId) {
this.inheritedParentId = inheritedParentId;
}
@Column(name = "DOMAIN_ID")
@Id
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SharingPK that = (SharingPK) o;
if (getPermissionTypeId() != null ? !getPermissionTypeId().equals(that.getPermissionTypeId()) : that.getPermissionTypeId() != null)
return false;
if (getEntityId() != null ? !getEntityId().equals(that.getEntityId()) : that.getEntityId() != null)
return false;
if (getGroupId() != null ? !getGroupId().equals(that.getGroupId()) : that.getGroupId() != null) return false;
if (getInheritedParentId() != null ? !getInheritedParentId().equals(that.getInheritedParentId()) : that.getInheritedParentId() != null)
return false;
if (getDomainId() != null ? !getDomainId().equals(that.getDomainId()) : that.getDomainId() != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = getPermissionTypeId() != null ? getPermissionTypeId().hashCode() : 0;
result = 31 * result + (getEntityId() != null ? getEntityId().hashCode() : 0);
result = 31 * result + (getGroupId() != null ? getGroupId().hashCode() : 0);
result = 31 * result + (getInheritedParentId() != null ? getInheritedParentId().hashCode() : 0);
result = 31 * result + (getDomainId() != null ? getDomainId().hashCode() : 0);
return result;
}
} | 698 |
0 | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db | Create_ds/airavata/modules/sharing-registry/sharing-registry-server/src/main/java/org/apache/airavata/sharing/registry/db/entities/UserGroupEntity.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.sharing.registry.db.entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "USER_GROUP", schema = "")
@IdClass(UserGroupPK.class)
public class UserGroupEntity {
private final static Logger logger = LoggerFactory.getLogger(UserGroupEntity.class);
private String groupId;
private String domainId;
private String name;
private String description;
private String ownerId;
private String groupType;
private String groupCardinality;
private Long createdTime;
private Long updatedTime;
private List<GroupAdminEntity> groupAdmins;
@Id
@Column(name = "GROUP_ID")
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
@Id
@Column(name = "DOMAIN_ID")
public String getDomainId() {
return domainId;
}
public void setDomainId(String domainId) {
this.domainId = domainId;
}
@Basic
@Column(name = "OWNER_ID")
public String getOwnerId() {
return ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
@Basic
@Column(name = "NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "DESCRIPTION")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Basic
@Column(name = "GROUP_CARDINALITY")
public String getGroupCardinality() {
return groupCardinality;
}
public void setGroupCardinality(String groupCardinality) {
this.groupCardinality = groupCardinality;
}
@Basic
@Column(name = "GROUP_TYPE")
public String getGroupType() {
return groupType;
}
public void setGroupType(String type) {
this.groupType = type;
}
@Basic
@Column(name = "CREATED_TIME")
public Long getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Long createdTime) {
this.createdTime = createdTime;
}
@Basic
@Column(name = "UPDATED_TIME")
public Long getUpdatedTime() {
return updatedTime;
}
public void setUpdatedTime(Long updatedTime) {
this.updatedTime = updatedTime;
}
@OneToMany(targetEntity = GroupAdminEntity.class, cascade = CascadeType.ALL,
mappedBy = "userGroup", fetch = FetchType.EAGER)
public List<GroupAdminEntity> getGroupAdmins() {
return groupAdmins;
}
public void setGroupAdmins(List<GroupAdminEntity> groupAdmins) {
this.groupAdmins = groupAdmins;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserGroupEntity that = (UserGroupEntity) o;
if (getGroupId() != null ? !getGroupId().equals(that.getGroupId()) : that.getGroupId() != null) return false;
if (getDomainId() != null ? !getDomainId().equals(that.getDomainId()) : that.getDomainId() != null)
return false;
if (getOwnerId() != null ? !getOwnerId().equals(that.getOwnerId()) : that.getOwnerId() != null) return false;
if (getName() != null ? !getName().equals(that.getName()) : that.getName() != null) return false;
if (getDescription() != null ? !getDescription().equals(that.getDescription()) : that.getDescription() != null)
return false;
if (getGroupType() != null ? !getGroupType().equals(that.getGroupType()) : that.getGroupType() != null)
return false;
if (getCreatedTime() != null ? !getCreatedTime().equals(that.getCreatedTime()) : that.getCreatedTime() != null)
return false;
if (getUpdatedTime() != null ? !getUpdatedTime().equals(that.getUpdatedTime()) : that.getUpdatedTime() != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = getGroupId() != null ? getGroupId().hashCode() : 0;
result = 31 * result + (getName() != null ? getName().hashCode() : 0);
result = 31 * result + (getDescription() != null ? getDescription().hashCode() : 0);
result = 31 * result + (getGroupType() != null ? getGroupType().hashCode() : 0);
result = 31 * result + (getCreatedTime() != null ? getCreatedTime().hashCode() : 0);
result = 31 * result + (getUpdatedTime() != null ? getUpdatedTime().hashCode() : 0);
return result;
}
} | 699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.