index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/Mapping.java
package org.apache.airavata.credential.store; /** * This keeps the mapping between community user and portal user. */ public class Mapping { private String gatewayName; private String communityUser; private String portalUser; public Mapping() { } public Mapping(String gatewayName, String communityUser, String portalUser) { this.gatewayName = gatewayName; this.communityUser = communityUser; this.portalUser = portalUser; } public String getGatewayName() { return gatewayName; } public void setGatewayName(String gatewayName) { this.gatewayName = gatewayName; } public String getCommunityUser() { return communityUser; } public void setCommunityUser(String communityUser) { this.communityUser = communityUser; } public String getPortalUser() { return portalUser; } public void setPortalUser(String portalUser) { this.portalUser = portalUser; } }
8,600
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/Credential.java
package org.apache.airavata.credential.store; import java.io.Serializable; /** * This class represents the actual credential. The credential can be a certificate, user name password * or a SSH key. As per now we only have certificate implementation. */ public interface Credential { }
8,601
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/CredentialWriter.java
package org.apache.airavata.credential.store; /** * The entity who's writing credentials to DB will use this interface. */ public interface CredentialWriter { /** * Writes given credentials to a persistent storage. * @param credential The credentials implementation. */ void writeCredentials(Credential credential) throws CredentialStoreException; /** * Writes community user information. * @param communityUser Writes community user information to a persistent storage. * @throws CredentialStoreException If an error occurred while writing community user. */ void writeCommunityUser(CommunityUser communityUser) throws CredentialStoreException; }
8,602
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/AuditInfo.java
package org.apache.airavata.credential.store; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; import java.util.Date; /** * Audit information related to community credential. */ @XmlRootElement public class AuditInfo implements Serializable { private static final long serialVersionUID = 13213123L; private String gatewayName; private String communityUserName; private String portalUserName; private Date credentialsRequestedTime; private String notBefore; private String notAfter; private long credentialLifeTime; public String getGatewayName() { return gatewayName; } public void setGatewayName(String gatewayName) { this.gatewayName = gatewayName; } public String getCommunityUserName() { return communityUserName; } public void setCommunityUserName(String communityUserName) { this.communityUserName = communityUserName; } public String getPortalUserName() { return portalUserName; } public void setPortalUserName(String portalUserName) { this.portalUserName = portalUserName; } public Date getCredentialsRequestedTime() { return credentialsRequestedTime; } public void setCredentialsRequestedTime(Date credentialsRequestedTime) { this.credentialsRequestedTime = credentialsRequestedTime; } public String getNotBefore() { return notBefore; } public void setNotBefore(String notBefore) { this.notBefore = notBefore; } public String getNotAfter() { return notAfter; } public void setNotAfter(String notAfter) { this.notAfter = notAfter; } public long getCredentialLifeTime() { return credentialLifeTime; } public void setCredentialLifeTime(long credentialLifeTime) { this.credentialLifeTime = credentialLifeTime; } }
8,603
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/impl/CertificateCredentialWriter.java
package org.apache.airavata.credential.store.impl; import org.apache.airavata.credential.store.*; import org.apache.airavata.credential.store.impl.db.CommunityUserDAO; import org.apache.airavata.credential.store.impl.db.CredentialsDAO; import org.apache.airavata.credential.store.util.DBUtil; /** * Writes certificate credentials to database. */ public class CertificateCredentialWriter implements CredentialWriter { private CredentialsDAO credentialsDAO; private CommunityUserDAO communityUserDAO; public CertificateCredentialWriter(DBUtil dbUtil) { credentialsDAO = new CredentialsDAO(dbUtil); communityUserDAO = new CommunityUserDAO(dbUtil); } @Override public void writeCredentials(Credential credential) throws CredentialStoreException { CertificateCredential certificateCredential = (CertificateCredential)credential; // Write community user writeCommunityUser(certificateCredential.getCommunityUser()); // First delete existing credentials credentialsDAO.deleteCredentials(certificateCredential.getCommunityUser().getGatewayName(), certificateCredential.getCommunityUser().getUserName()); // Add the new certificate CertificateCredential certificateCredentials = (CertificateCredential)credential; credentialsDAO.addCredentials(certificateCredentials); } @Override public void writeCommunityUser(CommunityUser communityUser) throws CredentialStoreException { // First delete existing community user communityUserDAO.deleteCommunityUser(communityUser); // Persist new community user communityUserDAO.addCommunityUser(communityUser); } }
8,604
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/impl/CredentialStoreImpl.java
package org.apache.airavata.credential.store.impl; import org.apache.airavata.credential.store.*; import org.apache.airavata.credential.store.impl.db.CommunityUserDAO; import org.apache.airavata.credential.store.impl.db.CredentialsDAO; import org.apache.airavata.credential.store.util.DBUtil; import java.io.Serializable; /** * Credential store API implementation. */ public class CredentialStoreImpl implements CredentialStore, Serializable { private CommunityUserDAO communityUserDAO; private CredentialsDAO credentialsDAO; public CredentialStoreImpl(DBUtil dbUtil) { this.communityUserDAO = new CommunityUserDAO(dbUtil); this.credentialsDAO = new CredentialsDAO(dbUtil); } @Override public String getPortalUser(String gatewayName, String communityUser) throws CredentialStoreException { CertificateCredential certificateCredential = this.credentialsDAO.getCredential(gatewayName, communityUser); return certificateCredential.getPortalUserName(); } @Override public AuditInfo getAuditInfo(String gatewayName, String communityUser) throws CredentialStoreException { CertificateCredential certificateCredential = this.credentialsDAO.getCredential(gatewayName, communityUser); AuditInfo auditInfo = new AuditInfo(); CommunityUser retrievedUser = certificateCredential.getCommunityUser(); auditInfo.setCommunityUserName(retrievedUser.getUserName()); auditInfo.setCredentialLifeTime(certificateCredential.getLifeTime()); auditInfo.setCredentialsRequestedTime(certificateCredential.getCertificateRequestedTime()); auditInfo.setGatewayName(gatewayName); auditInfo.setNotAfter(certificateCredential.getNotAfter()); auditInfo.setNotBefore(certificateCredential.getNotBefore()); auditInfo.setPortalUserName(certificateCredential.getPortalUserName()); return auditInfo; //To change body of implemented methods use File | Settings | File Templates. } @Override public void updateCommunityUserEmail(String gatewayName, String communityUser, String email) throws CredentialStoreException { this.communityUserDAO.updateCommunityUser( new CommunityUser(gatewayName, communityUser, email)); } @Override public void removeCredentials(String gatewayName, String communityUser) throws CredentialStoreException { credentialsDAO.deleteCredentials(gatewayName, communityUser); } }
8,605
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/impl
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/impl/db/MappingDAO.java
package org.apache.airavata.credential.store.impl.db; import org.apache.airavata.credential.store.CredentialStoreException; import org.apache.airavata.credential.store.Mapping; import org.apache.airavata.credential.store.util.DBUtil; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Data access class for Mapping table. */ public class MappingDAO extends ParentDAO { public MappingDAO(DBUtil dbUtil) { super(dbUtil); } public void addMapping (Mapping mapping) throws CredentialStoreException { String sql = "insert into mapping values (?, ?, ?)"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, mapping.getGatewayName()); preparedStatement.setString(2, mapping.getCommunityUser()); preparedStatement.setString(3, mapping.getPortalUser()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error persisting community user."); stringBuilder.append("gateway - ").append(mapping.getGatewayName()); stringBuilder.append("community user name - ").append(mapping.getCommunityUser()); stringBuilder.append("portal user name - ").append(mapping.getPortalUser()); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } } public void deleteGatewayMapping(String portalUser, String gatewayName) throws CredentialStoreException { String sql = "delete from mapping where gateway_name=? and portal_user_name=?;"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); preparedStatement.setString(2, portalUser); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error deleting mapping for portal user."); stringBuilder.append("gateway - ").append(gatewayName); stringBuilder.append("portal user name - ").append(portalUser); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } } public void deleteGatewayCommunityAccountMappings(String communityUserName, String gatewayName) throws CredentialStoreException { String sql = "delete from mapping where gateway_name=? and community_user_name=?;"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); preparedStatement.setString(2, communityUserName); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error deleting mapping for portal user."); stringBuilder.append("gateway - ").append(gatewayName); stringBuilder.append("community user name - ").append(communityUserName); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } } public List<String> getMappingPortalUsers (String communityUserName, String gatewayName) throws CredentialStoreException{ String sql = "select portal_user_name from mapping where gateway_name=? and community_user_name=?;"; List<String> portalUsers = new ArrayList<String>(); Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); preparedStatement.setString(2, communityUserName); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { portalUsers.add(resultSet.getString("portal_user_name")); } } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error retrieving mapping user."); stringBuilder.append("gateway - ").append(gatewayName); stringBuilder.append("community user name - ").append(communityUserName); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } return portalUsers; } public String getMappingCommunityUser (String portalUserName, String gatewayName) throws CredentialStoreException { String sql = "select community_user_name from mapping where gateway_name=? and portal_user_name=?;"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); preparedStatement.setString(2, portalUserName); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { return resultSet.getString("community_user_name"); } } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error retrieving mapping user."); stringBuilder.append("gateway - ").append(gatewayName); stringBuilder.append("portal user name - ").append(portalUserName); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } return null; } public String getCredentials(String portalUserName, String gatewayName) throws Exception { String sql = "select credential from credentials where credentials.community_user_name in " + "(select mapping.community_user_name from mapping where mapping.gateway_name = ?" + "and mapping.portal_user_name = ?);"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); preparedStatement.setString(2, portalUserName); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { return resultSet.getString("credential"); } } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error retrieving credentials for "); stringBuilder.append("gateway - ").append(gatewayName); stringBuilder.append("portal user name - ").append(portalUserName); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } return null; } }
8,606
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/impl
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/impl/db/CommunityUserDAO.java
package org.apache.airavata.credential.store.impl.db; import org.apache.airavata.credential.store.CommunityUser; import org.apache.airavata.credential.store.CredentialStoreException; import org.apache.airavata.credential.store.util.DBUtil; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Data access class for community_user table. */ public class CommunityUserDAO extends ParentDAO { public CommunityUserDAO(DBUtil dbUtil) { super(dbUtil); } public void addCommunityUser(CommunityUser user) throws CredentialStoreException { String sql = "insert into community_user values (?, ?, ?)"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, user.getGatewayName()); preparedStatement.setString(2, user.getUserName()); preparedStatement.setString(3, user.getUserEmail()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error persisting community user."); stringBuilder.append("gateway - ").append(user.getGatewayName()); stringBuilder.append("community user name - ").append(user.getUserName()); stringBuilder.append("community user email - ").append(user.getUserEmail()); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } } public void deleteCommunityUser(CommunityUser user) throws CredentialStoreException { String sql = "delete from community_user where gateway_name=? and community_user_name=?;"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, user.getGatewayName()); preparedStatement.setString(2, user.getUserName()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error deleting community user."); stringBuilder.append("gateway - ").append(user.getGatewayName()); stringBuilder.append("community user name - ").append(user.getUserName()); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } } public void updateCommunityUser(CommunityUser user) throws CredentialStoreException { //TODO } public CommunityUser getCommunityUser(String gatewayName, String communityUserName) throws CredentialStoreException{ String sql = "select * from community_user where gateway_name=? and community_user_name=?;"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); preparedStatement.setString(2, communityUserName); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { String email = resultSet.getString("COMMUNITY_USER_EMAIL"); //TODO fix typo return new CommunityUser(gatewayName, communityUserName, email); } } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error retrieving community user."); stringBuilder.append("gateway - ").append(gatewayName); stringBuilder.append("community user name - ").append(communityUserName); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } return null; } public List<CommunityUser> getCommunityUsers(String gatewayName) throws CredentialStoreException{ List<CommunityUser> userList = new ArrayList<CommunityUser>(); String sql = "select * from community_user where gateway_name=?"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String userName = resultSet.getString("COMMUNITY_USER_NAME"); String email = resultSet.getString("COMMUNITY_USER_EMAIL"); //TODO fix typo userList.add(new CommunityUser(gatewayName, userName, email)); } } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error retrieving community users for "); stringBuilder.append("gateway - ").append(gatewayName); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } return userList; } }
8,607
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/impl
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/impl/db/ParentDAO.java
package org.apache.airavata.credential.store.impl.db; import org.apache.airavata.credential.store.util.DBUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Super class to abstract out Data access classes. */ public class ParentDAO { protected static Logger log = LoggerFactory.getLogger(CommunityUserDAO.class); protected DBUtil dbUtil; public ParentDAO(DBUtil dbUtil) { this.dbUtil = dbUtil; } }
8,608
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/impl
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/impl/db/CredentialsDAO.java
package org.apache.airavata.credential.store.impl.db; import org.apache.airavata.credential.store.CommunityUser; import org.apache.airavata.credential.store.CredentialStoreException; import org.apache.airavata.credential.store.CertificateCredential; import org.apache.airavata.credential.store.util.DBUtil; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Data access class for credential store. */ public class CredentialsDAO extends ParentDAO { public CredentialsDAO(DBUtil dbUtil) { super(dbUtil); } public void addCredentials(CertificateCredential certificateCredential) throws CredentialStoreException { String sql = "insert into credentials values (?, ?, ?, ?, ?, ?, ?, ?, CURDATE())"; //TODO By any chance will we use some other database other than MySQL ? Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, certificateCredential.getCommunityUser().getGatewayName()); preparedStatement.setString(2, certificateCredential.getCommunityUser().getUserName()); preparedStatement.setString(3, certificateCredential.getCertificate()); preparedStatement.setString(4, certificateCredential.getPrivateKey()); preparedStatement.setString(5, certificateCredential.getNotBefore()); preparedStatement.setString(6, certificateCredential.getNotAfter()); preparedStatement.setLong(7, certificateCredential.getLifeTime()); preparedStatement.setString(8, certificateCredential.getPortalUserName()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error persisting community credentials."); stringBuilder.append(" gateway - ").append(certificateCredential.getCommunityUser().getGatewayName()); stringBuilder.append(" community user name - ").append(certificateCredential. getCommunityUser().getUserName()); stringBuilder.append(" life time - ").append(certificateCredential.getLifeTime()); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } } public void deleteCredentials(String gatewayName, String communityUserName) throws CredentialStoreException { String sql = "delete from credentials where gateway_name=? and community_user_name=?;"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); preparedStatement.setString(2, communityUserName); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error deleting credentials for ."); stringBuilder.append("gateway - ").append(gatewayName); stringBuilder.append("community user name - ").append(communityUserName); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } } public void updateCredentials(CertificateCredential certificateCredential) throws CredentialStoreException { String sql = "update credentials set credential = ?, private_key = ?, lifetime = ?, " + "requesting_portal_user_name = ?, " + "not_before = ?," + "not_after = ?," + "requested_time = CURDATE() where gateway_name = ? and community_user_name = ?"; //TODO By any chance will we use some other database other than MySQL ? Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, certificateCredential.getCertificate()); preparedStatement.setString(2, certificateCredential.getPrivateKey()); preparedStatement.setLong(3, certificateCredential.getLifeTime()); preparedStatement.setString(4, certificateCredential.getPortalUserName()); preparedStatement.setString(5, certificateCredential.getNotBefore()); preparedStatement.setString(6, certificateCredential.getNotAfter()); preparedStatement.setString(7, certificateCredential.getCommunityUser().getGatewayName()); preparedStatement.setString(8, certificateCredential.getCommunityUser().getUserName()); preparedStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error updating credentials."); stringBuilder.append(" gateway - ").append(certificateCredential.getCommunityUser().getGatewayName()); stringBuilder.append(" community user name - ").append(certificateCredential. getCommunityUser().getUserName()); stringBuilder.append(" life time - ").append(certificateCredential.getLifeTime()); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } } public CertificateCredential getCredential(String gatewayName, String communityUserName) throws CredentialStoreException { String sql = "select * from credentials where gateway_name=? and community_user_name=?;"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); preparedStatement.setString(2, communityUserName); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { CertificateCredential certificateCredential = new CertificateCredential(); certificateCredential.setCertificate(resultSet.getString("CREDENTIAL")); certificateCredential.setPrivateKey(resultSet.getString("PRIVATE_KEY")); certificateCredential.setLifeTime(resultSet.getLong("LIFETIME")); certificateCredential.setCommunityUser(new CommunityUser(gatewayName, communityUserName, null)); certificateCredential.setPortalUserName(resultSet.getString("REQUESTING_PORTAL_USER_NAME")); certificateCredential.setCertificateRequestedTime(resultSet.getTimestamp("REQUESTED_TIME")); return certificateCredential; } } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error retrieving credentials for community user."); stringBuilder.append("gateway - ").append(gatewayName); stringBuilder.append("community user name - ").append(communityUserName); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } return null; } public List<CertificateCredential> getCredentials(String gatewayName) throws CredentialStoreException { List<CertificateCredential> credentialList = new ArrayList<CertificateCredential>(); String sql = "select * from credentials where gateway_name=?"; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = dbUtil.getConnection(); preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, gatewayName); ResultSet resultSet = preparedStatement.executeQuery(); CertificateCredential certificateCredential; while (resultSet.next()) { certificateCredential = new CertificateCredential(); certificateCredential.setCommunityUser(new CommunityUser(gatewayName, resultSet.getString("COMMUNITY_USER_NAME"), null)); certificateCredential.setCertificate(resultSet.getString("CREDENTIAL")); certificateCredential.setPrivateKey(resultSet.getString("PRIVATE_KEY")); certificateCredential.setNotBefore(resultSet.getString("NOT_BEFORE")); certificateCredential.setNotBefore(resultSet.getString("NOT_AFTER")); certificateCredential.setLifeTime(resultSet.getLong("LIFETIME")); certificateCredential.setPortalUserName(resultSet.getString("REQUESTING_PORTAL_USER_NAME")); certificateCredential.setCertificateRequestedTime(resultSet.getTimestamp("REQUESTED_TIME")); credentialList.add(certificateCredential); } } catch (SQLException e) { StringBuilder stringBuilder = new StringBuilder("Error retrieving credential list for "); stringBuilder.append("gateway - ").append(gatewayName); log.error(stringBuilder.toString(), e); throw new CredentialStoreException(stringBuilder.toString(), e); } finally { dbUtil.cleanup(preparedStatement, connection); } return credentialList; } }
8,609
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialBootstrapper.java
package org.apache.airavata.credential.store.servlet; import edu.uiuc.ncsa.myproxy.oa4mp.client.loader.ClientBootstrapper; import edu.uiuc.ncsa.security.core.util.ConfigurationLoader; import javax.servlet.ServletContext; import java.io.File; /** * Bootstrapper class for credential-store. */ public class CredentialBootstrapper extends ClientBootstrapper { public ConfigurationLoader getConfigurationLoader(ServletContext servletContext) throws Exception { File currentDirectory = new File("."); System.out.println("Current directory is - " + currentDirectory.getAbsolutePath()); return super.getConfigurationLoader(servletContext); } }
8,610
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreOA4MPServer.java
package org.apache.airavata.credential.store.servlet; import edu.uiuc.ncsa.myproxy.oa4mp.client.ClientEnvironment; import edu.uiuc.ncsa.myproxy.oa4mp.client.OA4MPResponse; import edu.uiuc.ncsa.myproxy.oa4mp.client.OA4MPService; import edu.uiuc.ncsa.security.core.exceptions.GeneralException; import edu.uiuc.ncsa.security.delegation.client.request.DelegationRequest; import edu.uiuc.ncsa.security.delegation.client.request.DelegationResponse; import org.apache.commons.codec.binary.Base64; import org.bouncycastle.jce.PKCS10CertificationRequest; import java.security.KeyPair; import java.util.HashMap; import java.util.Map; import static edu.uiuc.ncsa.myproxy.oa4mp.client.ClientEnvironment.CALLBACK_URI_KEY; import static edu.uiuc.ncsa.security.util.pkcs.CertUtil.createCertRequest; import static edu.uiuc.ncsa.security.util.pkcs.KeyUtil.generateKeyPair; /** * Credential store specific OA4MPService. * Only change is add support to include get parameters. */ public class CredentialStoreOA4MPServer extends OA4MPService { public CredentialStoreOA4MPServer(ClientEnvironment environment) { super(environment); } public OA4MPResponse requestCert(Map additionalParameters) { if (additionalParameters == null) { additionalParameters = new HashMap(); } try { KeyPair keyPair = generateKeyPair(); PKCS10CertificationRequest certReq = createCertRequest(keyPair); OA4MPResponse mpdsResponse = new OA4MPResponse(); mpdsResponse.setPrivateKey(keyPair.getPrivate()); additionalParameters.put(ClientEnvironment.CERT_REQUEST_KEY, Base64.encodeBase64String(certReq.getDEREncoded())); if (additionalParameters.get(getEnvironment().getConstants().get(CALLBACK_URI_KEY)) == null) { additionalParameters.put(getEnvironment().getConstants().get(CALLBACK_URI_KEY), getEnvironment(). getCallback().toString()); } DelegationRequest daReq = new DelegationRequest(); daReq.setParameters(additionalParameters); daReq.setClient(getEnvironment().getClient()); daReq.setBaseUri(getEnvironment().getAuthorizationUri()); DelegationResponse daResp = (DelegationResponse) getEnvironment().getDelegationService().process(daReq); mpdsResponse.setRedirect(daResp.getRedirectUri()); return mpdsResponse; } catch (Throwable e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } throw new GeneralException("Error generating request", e); } } }
8,611
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreStartServlet.java
package org.apache.airavata.credential.store.servlet; import edu.uiuc.ncsa.myproxy.oa4mp.client.OA4MPResponse; import edu.uiuc.ncsa.myproxy.oa4mp.client.servlet.ClientServlet; import edu.uiuc.ncsa.security.servlet.JSPUtil; import edu.uiuc.ncsa.security.util.pkcs.KeyUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import static edu.uiuc.ncsa.myproxy.oa4mp.client.ClientEnvironment.CALLBACK_URI_KEY; /** * When portal initiate a request to get credentials it will hit this servlet. */ public class CredentialStoreStartServlet extends ClientServlet { private String errorUrl; private String redirectUrl; private static Logger log = LoggerFactory.getLogger(CredentialStoreStartServlet.class); protected String decorateURI(URI inputURI, Map<String, String> parameters) { if (parameters.isEmpty()) { return inputURI.toString(); } String stringUri = inputURI.toString(); StringBuilder stringBuilder = new StringBuilder(stringUri); boolean isFirst = true; for (Map.Entry<String, String> entry : parameters.entrySet()) { if (isFirst) { stringBuilder.append("?"); isFirst = false; } else { stringBuilder.append("&"); } stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()); } return stringBuilder.toString(); } @Override protected void doIt(HttpServletRequest request, HttpServletResponse response) throws Throwable { String gatewayName = request.getParameter("gatewayName"); String portalUserName = request.getParameter("portalUserName"); String contactEmail = request.getParameter("email"); if (gatewayName == null) { JSPUtil.handleException(new RuntimeException("Please specify a gateway name."), request, response, "/credential-store/error.jsp"); return; } if (portalUserName == null) { JSPUtil.handleException(new RuntimeException("Please specify a portal user name."), request, response, "/credential-store/error.jsp"); return; } if (contactEmail == null) { JSPUtil.handleException(new RuntimeException("Please specify a contact email address for community" + " user account."), request, response, "/credential-store/error.jsp"); return; } log.info("1.a. Starting transaction"); OA4MPResponse gtwResp = null; Map<String, String> queryParameters = new HashMap<String, String>(); queryParameters.put("gatewayName", gatewayName); queryParameters.put("portalUserName", portalUserName); queryParameters.put("email", contactEmail); Map<String, String> additionalParameters = new HashMap<String, String>(); String modifiedCallbackUri = decorateURI(getOA4MPService().getEnvironment().getCallback(), queryParameters); info("The modified callback URI - " + modifiedCallbackUri); additionalParameters.put(getEnvironment().getConstants().get(CALLBACK_URI_KEY), modifiedCallbackUri); // Drumroll please: here is the work for this call. try { gtwResp = getOA4MPService().requestCert(additionalParameters); } catch (Throwable t) { JSPUtil.handleException(t, request, response, "/credential-store/error.jsp"); return; } log.info("1.b. Got response. Creating page with redirect for " + gtwResp.getRedirect().getHost()); // Normally, we'd just do a redirect, but we will put up a page and show the redirect to the user. // The client response contains the generated private key as well // In a real application, the private key would be stored. This, however, exceeds the scope of this // sample application -- all we need to do to complete the process is send along the redirect url. request.setAttribute(REDIR, REDIR); request.setAttribute("redirectUrl", gtwResp.getRedirect().toString()); request.setAttribute(ACTION_KEY, ACTION_KEY); request.setAttribute("action", ACTION_REDIRECT_VALUE); log.info("1.b. Showing redirect page."); JSPUtil.fwd(request, response, "/credential-store/show-redirect.jsp"); } }
8,612
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreCallbackServlet.java
package org.apache.airavata.credential.store.servlet; import edu.uiuc.ncsa.myproxy.oa4mp.client.AssetResponse; import edu.uiuc.ncsa.myproxy.oa4mp.client.ClientEnvironment; import edu.uiuc.ncsa.myproxy.oa4mp.client.OA4MPService; import edu.uiuc.ncsa.myproxy.oa4mp.client.servlet.ClientServlet; import edu.uiuc.ncsa.security.core.exceptions.GeneralException; import edu.uiuc.ncsa.security.servlet.JSPUtil; import edu.uiuc.ncsa.security.util.pkcs.CertUtil; import org.apache.airavata.credential.store.CertificateCredential; import org.apache.airavata.credential.store.CommunityUser; import org.apache.airavata.credential.store.impl.CertificateCredentialWriter; import org.apache.airavata.credential.store.util.DBUtil; import org.apache.airavata.credential.store.util.Utility; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.security.cert.X509Certificate; /** * Callback from the portal will come here. In this class we will store incomming * certificate to the database. * Partly taken from OA4MP code base. */ public class CredentialStoreCallbackServlet extends ClientServlet { private static final String ERROR_PAGE = "/credential-store/error.jsp"; private static final String SUCCESS_PAGE = "/credential-store/success.jsp"; private OA4MPService oa4mpService; private CertificateCredentialWriter certificateCredentialWriter; public void init() throws ServletException { DBUtil dbUtil; try { dbUtil = DBUtil.getDBUtil(getServletContext()); } catch (Exception e) { throw new ServletException("Error initializing database operations.", e); } super.init(); certificateCredentialWriter = new CertificateCredentialWriter(dbUtil); info("Credential store callback initialized successfully."); } @Override public OA4MPService getOA4MPService() { return oa4mpService; } @Override public void loadEnvironment() throws IOException { environment = getConfigurationLoader().load(); oa4mpService = new CredentialStoreOA4MPServer((ClientEnvironment) environment); } @Override protected void doIt(HttpServletRequest request, HttpServletResponse response) throws Throwable { String gatewayName = request.getParameter("gatewayName"); String portalUserName = request.getParameter("portalUserName"); String durationParameter = request.getParameter("duration"); String contactEmail = request.getParameter("email"); //TODO remove hard coded values, once passing query parameters is //fixed in OA4MP client api long duration = 800; contactEmail = "ogce@sciencegateway.org"; if (durationParameter != null) { duration = Long.parseLong(durationParameter); } info("Gateway name " + gatewayName); info("Portal user name " + portalUserName); info("Community user contact email " + portalUserName); //TODO remove later gatewayName = "defaultGateway"; portalUserName = "defaultPortal"; info("2.a. Getting token and verifier."); String token = request.getParameter(TOKEN_KEY); String verifier = request.getParameter(VERIFIER_KEY); if (token == null || verifier == null) { warn("2.a. The token is " + (token == null ? "null" : token) + " and the verifier is " + (verifier == null ? "null" : verifier)); GeneralException ge = new GeneralException("Error: This servlet requires parameters for the token and verifier. It cannot be called directly."); request.setAttribute("exception", ge); JSPUtil.fwd(request, response, ERROR_PAGE); return; } info("2.a Token and verifier found."); X509Certificate cert = null; AssetResponse assetResponse = null; try { info("2.a. Getting the cert(s) from the service"); assetResponse = getOA4MPService().getCert(token, verifier); cert = assetResponse.getX509Certificates()[0]; // The work in this call } catch (Throwable t) { warn("2.a. Exception from the server: " + t.getCause().getMessage()); error("Exception while trying to get cert. message:" + t.getMessage()); request.setAttribute("exception", t); JSPUtil.fwd(request, response, ERROR_PAGE); return; } info("2.b. Done! Displaying success page."); CertificateCredential certificateCredential = new CertificateCredential(); certificateCredential.setNotBefore(Utility.convertDateToString(cert.getNotBefore())); certificateCredential.setNotAfter(Utility.convertDateToString(cert.getNotAfter())); certificateCredential.setCertificate(CertUtil.toPEM(assetResponse.getX509Certificates())); certificateCredential.setCommunityUser(new CommunityUser(gatewayName, assetResponse.getUsername(), contactEmail)); certificateCredential.setPortalUserName(portalUserName); certificateCredential.setLifeTime(duration); certificateCredentialWriter.writeCredentials(certificateCredential); StringBuilder stringBuilder = new StringBuilder("Certificate for community user "); stringBuilder.append(assetResponse.getUsername()).append(" successfully persisted."); stringBuilder.append(" Certificate DN - ").append(cert.getSubjectDN()); info(stringBuilder.toString()); String contextPath = request.getContextPath(); if (!contextPath.endsWith("/")) { contextPath = contextPath + "/"; } request.setAttribute("action", contextPath); JSPUtil.fwd(request, response, SUCCESS_PAGE); info("2.a. Completely finished with delegation."); } }
8,613
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/util/DBUtil.java
package org.apache.airavata.credential.store.util; import org.apache.commons.dbcp.BasicDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContext; import javax.sql.DataSource; import java.sql.*; import java.util.Properties; /** * Database utility class. */ public class DBUtil { private String jdbcUrl; private String databaseUserName; private String databasePassword; private String driverName; protected static Logger log = LoggerFactory.getLogger(DBUtil.class); private Properties properties; public DBUtil(String jdbcUrl, String userName, String password, String driver) { this.jdbcUrl = jdbcUrl; this.databaseUserName = userName; this.databasePassword = password; this.driverName = driver; } public void init() throws ClassNotFoundException, InstantiationException, IllegalAccessException { properties = new Properties(); properties.put("user", databaseUserName); properties.put("password", databasePassword); properties.put("characterEncoding", "ISO-8859-1"); properties.put("useUnicode", "true"); loadDriver(); } private void loadDriver() throws ClassNotFoundException, IllegalAccessException, InstantiationException { Class.forName(driverName).newInstance(); } public DataSource getDataSource() { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(this.driverName); ds.setUsername(this.databaseUserName); ds.setPassword(this.databasePassword); ds.setUrl(this.jdbcUrl); return ds; } /** * Mainly useful for tests. * @param tableName The table name. * @param connection The connection to be used. */ public static void truncate(String tableName, Connection connection) throws SQLException { String sql = "delete from " + tableName; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); connection.commit(); } public Connection getConnection() throws SQLException { Connection connection = DriverManager.getConnection(jdbcUrl, properties); connection.setAutoCommit(false); return connection; } public void cleanup(PreparedStatement preparedStatement, Connection connection) { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { log.error("Error closing prepared statement.", e); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { log.error("Error closing database connection.", e); } } } public static DBUtil getDBUtil(ServletContext servletContext) throws Exception{ String jdbcUrl = servletContext.getInitParameter("credential-store-jdbc-url"); String userName = servletContext.getInitParameter("credential-store-db-user"); String password = servletContext.getInitParameter("credential-store-db-password"); String driverName = servletContext.getInitParameter("credential-store-db-driver"); StringBuilder stringBuilder = new StringBuilder("Starting credential store, connecting to database - "); stringBuilder.append(jdbcUrl).append(" DB user - ").append(userName). append(" driver name - ").append(driverName); log.info(stringBuilder.toString()); DBUtil dbUtil = new DBUtil(jdbcUrl, userName, password, driverName); try { dbUtil.init(); } catch (Exception e) { log.error("Error initializing database operations.", e); throw e; } return dbUtil; } }
8,614
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store
Create_ds/airavata-sandbox/airavata-rest-security/modules/credential-store/src/main/java/org/apache/airavata/credential/store/util/Utility.java
package org.apache.airavata.credential.store.util; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Contains some utility methods. */ public class Utility { private static final String DATE_FORMAT = "MM/dd/yyyy HH:mm:ss"; public static String convertDateToString(Date date) { DateFormat df = new SimpleDateFormat(DATE_FORMAT); return df.format(date); } }
8,615
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security/configurations/TestUserStore.java
/* * * * * * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.apache.airavata.security.configurations; import org.apache.airavata.security.UserStore; import org.w3c.dom.Node; /** * Test user store class. */ public class TestUserStore implements UserStore { @Override public boolean authenticate(String userName, Object credentials) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean authenticate(Object credentials) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public void configure(Node node) throws RuntimeException { //To change body of implemented methods use File | Settings | File Templates. } }
8,616
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security/configurations/TestDBAuthenticator1.java
package org.apache.airavata.security.configurations; import org.apache.airavata.security.AbstractDatabaseAuthenticator; import org.apache.airavata.security.AuthenticationException; public class TestDBAuthenticator1 extends AbstractDatabaseAuthenticator { public TestDBAuthenticator1() { super(); } @Override public void onSuccessfulAuthentication(Object authenticationInfo) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void onFailedAuthentication(Object authenticationInfo) { //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean authenticate(Object credentials) throws AuthenticationException { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override protected boolean doAuthentication(Object credentials) throws AuthenticationException { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isAuthenticated(Object credentials) { return false; //To change body of implemented methods use File | Settings | File Templates. } }
8,617
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security/configurations/AuthenticatorConfigurationReaderTest.java
package org.apache.airavata.security.configurations; import junit.framework.TestCase; import org.apache.airavata.security.Authenticator; import org.apache.airavata.security.userstore.JDBCUserStore; import org.apache.airavata.security.userstore.LDAPUserStore; import java.io.File; import java.util.List; /** * A test class for authenticator configuration reader. * Reads the authenticators.xml in resources directory. */ public class AuthenticatorConfigurationReaderTest extends TestCase { private String configurationFile = this.getClass().getClassLoader().getResource("authenticators.xml").getFile(); public void setUp() throws Exception { File f = new File("."); System.out.println(f.getAbsolutePath()); File file = new File(configurationFile); if (!file.exists() && !file.canRead()) { throw new Exception("Error reading configuration file " + configurationFile); } } public void testInit() throws Exception { AuthenticatorConfigurationReader authenticatorConfigurationReader = new AuthenticatorConfigurationReader(); authenticatorConfigurationReader.init(configurationFile); assertTrue(AuthenticatorConfigurationReader.isAuthenticationEnabled()); List<Authenticator> authenticators = authenticatorConfigurationReader.getAuthenticatorList(); assertEquals(authenticators.size(), 3); for (Authenticator authenticator : authenticators) { if (authenticator instanceof TestDBAuthenticator1) { assertEquals("dbAuthenticator1", authenticator.getAuthenticatorName()); assertEquals(6, authenticator.getPriority()); assertEquals(true, authenticator.isEnabled()); assertEquals("jdbc:sql:thin:@//myhost:1521/mysql1", ((TestDBAuthenticator1) authenticator).getDatabaseURL()); assertEquals("org.myqsql.Driver1", ((TestDBAuthenticator1) authenticator).getDatabaseDriver()); assertEquals("mysql1", ((TestDBAuthenticator1) authenticator).getDatabaseUserName()); assertEquals("secret1", ((TestDBAuthenticator1) authenticator).getDatabasePassword()); assertNotNull(authenticator.getUserStore()); assertTrue(authenticator.getUserStore() instanceof JDBCUserStore); } else if (authenticator instanceof TestDBAuthenticator2) { assertEquals("dbAuthenticator2", authenticator.getAuthenticatorName()); assertEquals(7, authenticator.getPriority()); assertEquals(true, authenticator.isEnabled()); assertEquals("jdbc:sql:thin:@//myhost:1521/mysql2", ((TestDBAuthenticator2) authenticator).getDatabaseURL()); assertEquals("org.myqsql.Driver2", ((TestDBAuthenticator2) authenticator).getDatabaseDriver()); assertEquals("mysql2", ((TestDBAuthenticator2) authenticator).getDatabaseUserName()); assertEquals("secret2", ((TestDBAuthenticator2) authenticator).getDatabasePassword()); assertNotNull(authenticator.getUserStore()); assertTrue(authenticator.getUserStore() instanceof LDAPUserStore); } else if (authenticator instanceof TestDBAuthenticator3) { assertEquals("dbAuthenticator3", authenticator.getAuthenticatorName()); assertEquals(8, authenticator.getPriority()); assertEquals(true, authenticator.isEnabled()); assertEquals("jdbc:sql:thin:@//myhost:1521/mysql3", ((TestDBAuthenticator3) authenticator).getDatabaseURL()); assertEquals("org.myqsql.Driver3", ((TestDBAuthenticator3) authenticator).getDatabaseDriver()); assertEquals("mysql3", ((TestDBAuthenticator3) authenticator).getDatabaseUserName()); assertEquals("secret3", ((TestDBAuthenticator3) authenticator).getDatabasePassword()); assertNotNull(authenticator.getUserStore()); assertTrue(authenticator.getUserStore() instanceof JDBCUserStore); } } assertEquals(8, authenticators.get(0).getPriority()); assertEquals(7, authenticators.get(1).getPriority()); assertEquals(6, authenticators.get(2).getPriority()); } public void testDisabledAuthenticator() throws Exception { String disabledConfiguration = this.getClass().getClassLoader().getResource("disabled-authenticator.xml").getFile(); AuthenticatorConfigurationReader authenticatorConfigurationReader = new AuthenticatorConfigurationReader(); authenticatorConfigurationReader.init(disabledConfiguration); assertFalse(AuthenticatorConfigurationReader.isAuthenticationEnabled()); } }
8,618
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security/configurations/TestDBAuthenticator3.java
package org.apache.airavata.security.configurations; import org.apache.airavata.security.AbstractDatabaseAuthenticator; import org.apache.airavata.security.AuthenticationException; /** * Created with IntelliJ IDEA. * User: thejaka * Date: 9/6/12 * Time: 6:30 PM * To change this template use File | Settings | File Templates. */ public class TestDBAuthenticator3 extends AbstractDatabaseAuthenticator { public TestDBAuthenticator3() { super(); } @Override public void onSuccessfulAuthentication(Object authenticationInfo) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void onFailedAuthentication(Object authenticationInfo) { //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean authenticate(Object credentials) throws AuthenticationException { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override protected boolean doAuthentication(Object credentials) throws AuthenticationException { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isAuthenticated(Object credentials) { return false; //To change body of implemented methods use File | Settings | File Templates. } }
8,619
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security/configurations/TestDBAuthenticator2.java
package org.apache.airavata.security.configurations; import org.apache.airavata.security.AbstractDatabaseAuthenticator; import org.apache.airavata.security.AuthenticationException; /** * Created with IntelliJ IDEA. * User: thejaka * Date: 9/6/12 * Time: 6:30 PM * To change this template use File | Settings | File Templates. */ public class TestDBAuthenticator2 extends AbstractDatabaseAuthenticator { public TestDBAuthenticator2() { super(); } @Override public void onSuccessfulAuthentication(Object authenticationInfo) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void onFailedAuthentication(Object authenticationInfo) { //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean authenticate(Object credentials) throws AuthenticationException { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override protected boolean doAuthentication(Object credentials) throws AuthenticationException { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isAuthenticated(Object credentials) { return false; //To change body of implemented methods use File | Settings | File Templates. } }
8,620
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security/userstore/JDBCUserStoreTest.java
/* * * * * * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.apache.airavata.security.userstore; import junit.framework.TestCase; import org.apache.airavata.security.Authenticator; import org.apache.airavata.security.UserStore; import org.apache.airavata.security.configurations.AuthenticatorConfigurationReader; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.util.List; /** * Test class for JDBC user store. */ public class JDBCUserStoreTest extends TestCase { /** * <specificConfigurations> <database> <!--jdbcUrl>jdbc:h2:modules/commons/airavata-registry-rest/src/test/resources/testdb/test</jdbcUrl--> <jdbcUrl>jdbc:h2:src/test/resources/testdb/test</jdbcUrl> <userName>sa</userName> <password>sa</password> <databaseDriver>org.h2.Driver</databaseDriver> <userTableName>AIRAVATA_USER</userTableName> <userNameColumnName>USERID</userNameColumnName> <passwordColumnName>PASSWORD</passwordColumnName> </database> </specificConfigurations> * @throws Exception */ public void testAuthenticate() throws Exception { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(this.getClass().getClassLoader().getResourceAsStream("jdbc-authenticator.xml")); doc.getDocumentElement().normalize(); NodeList configurations = doc.getElementsByTagName("specificConfigurations"); UserStore userStore = new JDBCUserStore(); userStore.configure(configurations.item(0)); assertTrue(userStore.authenticate("amilaj", "secret")); assertFalse(userStore.authenticate("amilaj", "1secret")); assertFalse(userStore.authenticate("lahiru", "1234")); } }
8,621
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security/userstore/LDAPUserStoreTest.java
/* * * * * * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.apache.airavata.security.userstore; import junit.framework.TestCase; import org.apache.airavata.security.UserStore; import org.junit.Ignore; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; /** * User store test 2 */ @Ignore("Need LDAP server to run these tests") public class LDAPUserStoreTest extends TestCase{ private LDAPUserStore ldapUserStore; public void setUp() { ldapUserStore = new LDAPUserStore(); ldapUserStore.initializeLDAP("ldap://localhost:10389", "admin", "secret", "uid={0},ou=system"); } public void testAuthenticate() throws Exception { assertTrue(ldapUserStore.authenticate("amilaj", "secret")); assertFalse(ldapUserStore.authenticate("amilaj", "secret1")); } public void testConfigure() throws Exception { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(this.getClass().getClassLoader().getResourceAsStream("ldap-authenticator.xml")); doc.getDocumentElement().normalize(); NodeList configurations = doc.getElementsByTagName("specificConfigurations"); UserStore userStore = new LDAPUserStore(); userStore.configure(configurations.item(0)); assertTrue(userStore.authenticate("amilaj", "secret")); } }
8,622
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/test/java/org/apache/airavata/security/userstore/SessionDBUserStoreTest.java
/* * * * * * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.apache.airavata.security.userstore; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.File; import java.io.InputStream; /** * Test class for session DB authenticator. */ public class SessionDBUserStoreTest extends TestCase { private SessionDBUserStore sessionDBUserStore = new SessionDBUserStore(); private InputStream configurationFileStream = this.getClass().getClassLoader().getResourceAsStream("session-authenticator.xml"); public void setUp() throws Exception { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(configurationFileStream); doc.getDocumentElement().normalize(); NodeList specificConfigurations = doc.getElementsByTagName("specificConfigurations"); sessionDBUserStore.configure(specificConfigurations.item(0)); } public void testAuthenticate() throws Exception { assertTrue(sessionDBUserStore.authenticate("1234")); } public void testAuthenticateFailure() throws Exception { assertFalse(sessionDBUserStore.authenticate("12345")); } }
8,623
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/AbstractAuthenticator.java
package org.apache.airavata.security; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.SimpleDateFormat; import java.util.Calendar; /** * An abstract implementation of the authenticator. */ @SuppressWarnings("UnusedDeclaration") public abstract class AbstractAuthenticator implements Authenticator { protected static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; protected static Logger log = LoggerFactory.getLogger(AbstractAuthenticator.class); public static int DEFAULT_AUTHENTICATOR_PRIORITY = 5; protected String authenticatorName; private int priority = DEFAULT_AUTHENTICATOR_PRIORITY; protected boolean enabled = true; protected UserStore userStore; public AbstractAuthenticator() { } public AbstractAuthenticator(String name) { this.authenticatorName = name; } public void setUserStore(UserStore store) { this.userStore = store; } public UserStore getUserStore() { return this.userStore; } public int getPriority() { return priority; } public boolean canProcess(Object credentials) { return false; } public String getAuthenticatorName() { return authenticatorName; } public void setAuthenticatorName(String authenticatorName) { this.authenticatorName = authenticatorName; } public void setPriority(int priority) { this.priority = priority; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isEnabled() { return enabled; } public boolean authenticate(Object credentials) throws AuthenticationException { boolean authenticated = doAuthentication(credentials); if (authenticated) { onSuccessfulAuthentication(credentials); } else { onFailedAuthentication(credentials); } return authenticated; } /** * Gets the current time converted to format in DATE_TIME_FORMAT. * @return Current time as a string. */ protected String getCurrentTime() { Calendar cal = Calendar.getInstance(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_TIME_FORMAT); return simpleDateFormat.format(cal.getTime()); } /** * The actual authenticating logic goes here. If user is successfully authenticated this should return * <code>true</code> else this should return <code>false</code>. If an error occurred while authenticating * this will throw an exception. * @param credentials The object which contains request credentials. This could be request most of the time. * @return <code>true</code> if successfully authenticated else <code>false</code>. * @throws AuthenticationException If system error occurs while authenticating. */ protected abstract boolean doAuthentication(Object credentials) throws AuthenticationException; /** * If authentication is successful we can do post authentication actions in following method. * E.g :- adding user to session, audit logging etc ... * @param authenticationInfo A generic object with authentication information. */ public abstract void onSuccessfulAuthentication(Object authenticationInfo); /** * If authentication is failed we can do post authentication actions in following method. * E.g :- adding user to session, audit logging etc ... * @param authenticationInfo A generic object with authentication information. */ public abstract void onFailedAuthentication(Object authenticationInfo); }
8,624
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/UserStore.java
/* * * * * * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.apache.airavata.security; import org.w3c.dom.Node; /** * An interface to wrap the functionality of a user store. A user store is place where we keep user attribute * information. Usually this contains, user id, user name, password etc ... * We also authenticate users against the credentials stored in a user store. In addition to user attributes * we also store role information and group information. * This interface provide methods to manipulated data in a user store. * Such operations are as follows, * <ol> * <li>authenticate user</li> * <li>add user</li> * <li>delete user</li> * <li>add a role</li> * <li>delete a role</li> * <li>... etc ...</li> * </ol> */ public interface UserStore { /** * Checks whether given user exists in the user store and its credentials match with the credentials stored * in the user store. * @param userName Name of the user to authenticate. * @param credentials User credentials as an object. User credentials may not be a string always. * @return True if user exists in the user store and its credentials match with the credentials in user store. * <code>false</code> else. * @throws UserStoreException if a system wide error occurred while authenticating the user. */ boolean authenticate(String userName, Object credentials) throws UserStoreException; /** * Authenticates a user using a token. * @param credentials The token information. * @return <code>true</code> if authentication successful else <code>false</code>. * @throws UserStoreException if a system wide error occurred while authenticating the user. */ boolean authenticate(Object credentials) throws UserStoreException; /** * This method will do necessary configurations of the user store. * @param node An XML configuration node. * @throws RuntimeException If an error occurred while configuring the authenticator. */ void configure(Node node) throws UserStoreException; }
8,625
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/Authoriser.java
package org.apache.airavata.security; /** * An interface which can be used to authorise accessing resources. */ @SuppressWarnings("UnusedDeclaration") public interface Authoriser { /** * Checks whether user has sufficient privileges to perform action on the given resource. * @param userName The user who is performing the action. * @param resource The resource which user is trying to access. * @param action The action (GET, PUT etc ...) * @return Returns <code>true</code> if user is authorised to perform the action, else false. */ boolean isAuthorised (String userName, String resource, String action); }
8,626
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/Authenticator.java
package org.apache.airavata.security; import org.w3c.dom.Node; /** * A generic interface to do request authentication. Specific authenticator will implement authenticate method. */ @SuppressWarnings("UnusedDeclaration") public interface Authenticator { /** * Authenticates the request with given credentials. * @param credentials Credentials can be a session ticket, password or session id. * @return <code>true</code> if request is successfully authenticated else <code>false</code>. * @throws AuthenticationException If a system error occurred during authentication process. */ boolean authenticate(Object credentials) throws AuthenticationException; /** * Checks whether given user is already authenticated. * @param credentials The token to be authenticated. * @return <code>true</code> if token is already authenticated else <code>false</code>. */ boolean isAuthenticated(Object credentials); /** * Says whether current authenticator can handle given credentials. * @param credentials Credentials used during authentication. * @return <code>true</code> is can authenticate else <code>false</code>. */ boolean canProcess(Object credentials); /** * Gets the priority of this authenticator. * @return Higher the priority higher the precedence of selecting the authenticator. */ int getPriority(); /** * Returns the authenticator name. Each authenticator is associated with an identifiable name. * @return The authenticator name. */ String getAuthenticatorName(); /** * Authenticator specific configurations goes into this method. * @param node An XML configuration node. * @throws RuntimeException If an error occurred while configuring the authenticator. */ void configure(Node node) throws RuntimeException; /** * Return <code>true</code> if current authenticator is enabled. Else <code>false</code>. * @return <code>true</code> if enabled. */ boolean isEnabled(); /** * User store that should be used by this authenticator. When authenticating a request * authenticator should use the user store set by this method. * @param userStore The user store to be used. */ void setUserStore(UserStore userStore); /** * Gets the user store used by this authenticator. * @return The user store used by this authenticator. */ UserStore getUserStore(); }
8,627
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/UserStoreException.java
/* * * * * * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.apache.airavata.security; /** * Exception class to wrap user store errors. */ public class UserStoreException extends Exception { public UserStoreException() { super(); } public UserStoreException(String message) { super(message); } public UserStoreException(String message, Exception e) { super(message, e); } public UserStoreException(Exception e) { super(e); } }
8,628
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/AuthenticationException.java
package org.apache.airavata.security; /** * Wraps errors during authentication. This exception will be thrown if there is a system error during authentication. */ public class AuthenticationException extends Exception { public AuthenticationException() { super(); } public AuthenticationException (String message) { super(message); } public AuthenticationException (String message, Exception e) { super(message, e); } }
8,629
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/AbstractDatabaseAuthenticator.java
package org.apache.airavata.security; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * An abstract authenticator class which reads database configurations. */ @SuppressWarnings("UnusedDeclaration") public abstract class AbstractDatabaseAuthenticator extends AbstractAuthenticator { private String databaseURL; private String databaseDriver; private String databaseUserName; private String databasePassword; public AbstractDatabaseAuthenticator() { super(); } public AbstractDatabaseAuthenticator(String name) { super(name); } /** * We are reading database parameters in this case. * * @param node An XML configuration node. */ public void configure(Node node) { /** <specificConfigurations> <database> <jdbcUrl></jdbcUrl> <databaseDriver></databaseDriver> <userName></userName> <password></password> </database> </specificConfigurations> */ NodeList databaseNodeList = node.getChildNodes(); Node databaseNode = null; for (int k = 0; k < databaseNodeList.getLength(); ++k) { Node n = databaseNodeList.item(k); if (n != null && n.getNodeType() == Node.ELEMENT_NODE) { databaseNode = n; } } if (databaseNode != null) { NodeList nodeList = databaseNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); ++i) { Node n = nodeList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) n; if (element.getNodeName().equals("jdbcUrl")) { databaseURL = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("databaseDriver")) { databaseDriver = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("userName")) { databaseUserName = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("password")) { databasePassword = element.getFirstChild().getNodeValue(); } } } } StringBuilder stringBuilder = new StringBuilder("Configuring DB parameters for authenticator with JDBC URL - "); stringBuilder.append(databaseURL).append(" DB driver - ").append(" DB user - "). append(databaseUserName).append(" DB password - xxxxxx"); log.info(stringBuilder.toString()); } public String getDatabaseURL() { return databaseURL; } public String getDatabaseDriver() { return databaseDriver; } public String getDatabaseUserName() { return databaseUserName; } public String getDatabasePassword() { return databasePassword; } }
8,630
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/configurations/AbstractConfigurationReader.java
/* * * * * * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.apache.airavata.security.configurations; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * Abstract implementation to read configurations. */ public abstract class AbstractConfigurationReader { public void init(String fileName) throws IOException, SAXException, ParserConfigurationException { File configurationFile = new File(fileName); if (!configurationFile.canRead()) { throw new IOException("Error reading configuration file " + configurationFile.getAbsolutePath()); } FileInputStream streamIn = new FileInputStream(configurationFile); try { init(streamIn); } finally { streamIn.close(); } } public abstract void init(InputStream inputStream) throws IOException, ParserConfigurationException, SAXException; }
8,631
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/configurations/AuthenticatorConfigurationReader.java
package org.apache.airavata.security.configurations; import org.apache.airavata.security.AbstractAuthenticator; import org.apache.airavata.security.Authenticator; import org.apache.airavata.security.UserStore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * This class will read authenticators.xml and load all configurations related to authenticators. */ public class AuthenticatorConfigurationReader extends AbstractConfigurationReader { private List<Authenticator> authenticatorList = new ArrayList<Authenticator>(); protected static Logger log = LoggerFactory.getLogger(AuthenticatorConfigurationReader.class); protected static boolean authenticationEnabled = true; public AuthenticatorConfigurationReader() { } public void init(InputStream inputStream) throws IOException, ParserConfigurationException, SAXException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputStream); doc.getDocumentElement().normalize(); NodeList rootNodeList = doc.getElementsByTagName("authenticators"); if (rootNodeList == null || rootNodeList.getLength() == 0) { throw new ParserConfigurationException("authenticators.xml should have authenticators root element."); } Node authenticatorsNode = rootNodeList.item(0); NamedNodeMap rootAttributes = authenticatorsNode.getAttributes(); if (rootAttributes != null && rootAttributes.getNamedItem("enabled") != null) { String enabledAttribute = rootAttributes.getNamedItem("enabled").getNodeValue(); if ( enabledAttribute != null) { if (enabledAttribute.equals("false")) { authenticationEnabled = false; } } } NodeList authenticators = doc.getElementsByTagName("authenticator"); for (int i = 0; i < authenticators.getLength(); ++i) { Node node = authenticators.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { NamedNodeMap namedNodeMap = node.getAttributes(); String name = namedNodeMap.getNamedItem("name").getNodeValue(); String className = namedNodeMap.getNamedItem("class").getNodeValue(); String enabled = namedNodeMap.getNamedItem("enabled").getNodeValue(); String priority = namedNodeMap.getNamedItem("priority").getNodeValue(); String userStoreClass = namedNodeMap.getNamedItem("userstore").getNodeValue(); if (className == null) { reportError("class"); } if (userStoreClass == null) { reportError("userstore"); } Authenticator authenticator = createAuthenticator(name, className, enabled, priority, userStoreClass); NodeList configurationNodes = node.getChildNodes(); for (int j = 0; j < configurationNodes.getLength(); ++j) { Node configurationNode = configurationNodes.item(j); if (configurationNode.getNodeType() == Node.ELEMENT_NODE) { if (configurationNode.getNodeName().equals("specificConfigurations")) { authenticator.configure(configurationNode); } } } if (authenticator.isEnabled()) { authenticatorList.add(authenticator); } Collections.sort(authenticatorList, new AuthenticatorComparator()); StringBuilder stringBuilder = new StringBuilder("Successfully initialized authenticator "); stringBuilder.append(name).append(" with class ").append(className).append(" enabled? ").append(enabled) .append(" priority = ").append(priority); log.info(stringBuilder.toString()); } } } private void reportError(String element) throws ParserConfigurationException { throw new ParserConfigurationException("Error in configuration. Missing mandatory element " + element); } protected Authenticator createAuthenticator(String name, String className, String enabled, String priority, String userStoreClassName) { log.info("Loading authenticator class " + className + " and name " + name); // Load a class and instantiate an object Class authenticatorClass; try { authenticatorClass = Class.forName(className, true, Thread.currentThread().getContextClassLoader()); //authenticatorClass = Class.forName(className); } catch (ClassNotFoundException e) { log.error("Error loading authenticator class " + className); throw new RuntimeException("Error loading authenticator class " + className, e); } try { AbstractAuthenticator authenticatorInstance = (AbstractAuthenticator) authenticatorClass.newInstance(); authenticatorInstance.setAuthenticatorName(name); if (enabled != null) { authenticatorInstance.setEnabled(Boolean.parseBoolean(enabled)); } if (priority != null) { authenticatorInstance.setPriority(Integer.parseInt(priority)); } UserStore userStore = createUserStore(userStoreClassName); authenticatorInstance.setUserStore(userStore); return authenticatorInstance; } catch (InstantiationException e) { String error = "Error instantiating authenticator class " + className + " object."; log.error(error); throw new RuntimeException(error, e); } catch (IllegalAccessException e) { String error = "Not allowed to instantiate authenticator class " + className; log.error(error); throw new RuntimeException(error, e); } } protected UserStore createUserStore(String userStoreClassName) { try { Class userStoreClass = Class.forName(userStoreClassName, true, Thread.currentThread().getContextClassLoader()); return (UserStore)userStoreClass.newInstance(); } catch (ClassNotFoundException e) { log.error("Error loading authenticator class " + userStoreClassName); throw new RuntimeException("Error loading authenticator class " + userStoreClassName, e); } catch (InstantiationException e) { String error = "Error instantiating authenticator class " + userStoreClassName + " object."; log.error(error); throw new RuntimeException(error, e); } catch (IllegalAccessException e) { String error = "Not allowed to instantiate authenticator class " + userStoreClassName; log.error(error); throw new RuntimeException(error, e); } } public List<Authenticator> getAuthenticatorList() { return Collections.unmodifiableList(authenticatorList); } /** * We can specify whether authentication is enabled in the system for all request or not. * This we can state in the configuration. AuthenticatorConfigurationReader will read that information * and will populate that to static boolean authenticationEnabled. This method will say whether * authentication is enabled in the system or disabled in the system. * @return <code>true</code> if authentication is enabled. Else <code>false</code>. */ public static boolean isAuthenticationEnabled() { return authenticationEnabled; } /** * Comparator to sort authenticators based on authenticator priority. */ public class AuthenticatorComparator implements Comparator<Authenticator> { @Override public int compare(Authenticator o1, Authenticator o2) { return (o1.getPriority() > o2.getPriority() ? -1 : (o1.getPriority() == o2.getPriority() ? 0 : 1)); } } }
8,632
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/util/DBLookup.java
package org.apache.airavata.security.util; import org.apache.commons.dbcp.BasicDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.sql.DataSource; import java.sql.*; import java.util.Properties; /** * Database lookup. */ public class DBLookup { private String jdbcUrl; private String databaseUserName; private String databasePassword; private String driverName; protected static Logger log = LoggerFactory.getLogger(DBLookup.class); private Properties properties; public DBLookup(String jdbcUrl, String userName, String password, String driver) { this.jdbcUrl = jdbcUrl; this.databaseUserName = userName; this.databasePassword = password; this.driverName = driver; } public void init() throws ClassNotFoundException, InstantiationException, IllegalAccessException { properties = new Properties(); properties.put("user", databaseUserName); properties.put("password", databasePassword); properties.put("characterEncoding", "ISO-8859-1"); properties.put("useUnicode", "true"); loadDriver(); } public String getMatchingColumnValue(String tableName, String selectColumn, String whereValue) throws SQLException { return getMatchingColumnValue(tableName, selectColumn, selectColumn, whereValue); } public String getMatchingColumnValue(String tableName, String selectColumn, String whereColumn, String whereValue) throws SQLException { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("SELECT ").append(selectColumn).append(" FROM ").append(tableName) .append(" WHERE ").append(whereColumn).append(" = ?"); String sql = stringBuilder.toString(); Connection connection = getConnection(); PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = null; try { ps.setString(1, whereValue); rs = ps.executeQuery(); if (rs.next()) { return rs.getString(1); } } finally { try { if (rs != null) { rs.close(); } ps.close(); connection.close(); } catch (Exception ignore) { log.error("An error occurred while closing database connections ", ignore); } } return null; } private void loadDriver() throws ClassNotFoundException, IllegalAccessException, InstantiationException { Class.forName(driverName).newInstance(); } public DataSource getDataSource() { BasicDataSource ds = new BasicDataSource(); ds.setDriverClassName(this.driverName); ds.setUsername(this.databaseUserName); ds.setPassword(this.databasePassword); ds.setUrl(this.jdbcUrl); return ds; } public Connection getConnection() throws SQLException { return DriverManager.getConnection(jdbcUrl, properties); } }
8,633
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/userstore/JDBCUserStore.java
/* * * * * * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.apache.airavata.security.userstore; import org.apache.airavata.security.UserStore; import org.apache.airavata.security.UserStoreException; import org.apache.airavata.security.util.DBLookup; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.realm.jdbc.JdbcRealm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import javax.sql.DataSource; /** * The JDBC user store implementation. */ public class JDBCUserStore extends AbstractJDBCUserStore { protected static Logger log = LoggerFactory.getLogger(JDBCUserStore.class); private JdbcRealm jdbcRealm; public JDBCUserStore() { jdbcRealm = new JdbcRealm(); } @Override public boolean authenticate(String userName, Object credentials) throws UserStoreException{ AuthenticationToken authenticationToken = new UsernamePasswordToken(userName, (String)credentials); AuthenticationInfo authenticationInfo; try { authenticationInfo = jdbcRealm.getAuthenticationInfo(authenticationToken); } catch (AuthenticationException e) { log.warn(e.getLocalizedMessage(), e); return false; } return authenticationInfo != null; } @Override public boolean authenticate(Object credentials) throws UserStoreException{ log.error("JDBC user store only supports user name, password based authentication."); throw new NotImplementedException(); } @Override public void configure(Node node) throws UserStoreException { super.configure(node); /** <specificConfigurations> <database> <jdbcUrl></jdbcUrl> <databaseDriver></databaseDriver> <userName></userName> <password></password> <userTableName></userTableName> <userNameColumnName></userNameColumnName> <passwordColumnName></passwordColumnName> </database> </specificConfigurations> */ NodeList databaseNodeList = node.getChildNodes(); Node databaseNode = null; for (int k = 0; k < databaseNodeList.getLength(); ++k) { Node n = databaseNodeList.item(k); if (n != null && n.getNodeType() == Node.ELEMENT_NODE) { databaseNode = n; } } String userTable = null; String userNameColumn = null; String passwordColumn = null; if (databaseNode != null) { NodeList nodeList = databaseNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); ++i) { Node n = nodeList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) n; if (element.getNodeName().equals("userTableName")) { userTable = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("userNameColumnName")) { userNameColumn = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("passwordColumnName")) { passwordColumn = element.getFirstChild().getNodeValue(); } } } } initializeDatabaseLookup(passwordColumn, userTable, userNameColumn); StringBuilder stringBuilder = new StringBuilder("Configuring DB parameters for authenticator with User name Table - "); stringBuilder.append(userTable).append(" User name column - ").append(userNameColumn).append(" Password column - "). append(passwordColumn); log.info(stringBuilder.toString()); } protected void initializeDatabaseLookup(String passwordColumn, String userTable, String userNameColumn) { DBLookup dbLookup = new DBLookup(getDatabaseURL(), getDatabaseUserName(), getDatabasePassword(), getDatabaseDriver()); DataSource dataSource = dbLookup.getDataSource(); jdbcRealm.setDataSource(dataSource); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("SELECT ").append(passwordColumn).append(" FROM ").append(userTable) .append(" WHERE ").append(userNameColumn).append(" = ?"); jdbcRealm.setAuthenticationQuery(stringBuilder.toString()); } }
8,634
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/userstore/LDAPUserStore.java
/* * * * * * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.apache.airavata.security.userstore; import org.apache.airavata.security.UserStore; import org.apache.airavata.security.UserStoreException; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.realm.ldap.JndiLdapContextFactory; import org.apache.shiro.realm.ldap.JndiLdapRealm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import sun.reflect.generics.reflectiveObjects.NotImplementedException; /** * A user store which talks to LDAP server. User credentials and user information * are stored in a LDAP server. */ public class LDAPUserStore implements UserStore { private JndiLdapRealm ldapRealm; protected static Logger log = LoggerFactory.getLogger(LDAPUserStore.class); public boolean authenticate(String userName, Object credentials) throws UserStoreException { AuthenticationToken authenticationToken = new UsernamePasswordToken(userName, (String)credentials); AuthenticationInfo authenticationInfo; try { authenticationInfo = ldapRealm.getAuthenticationInfo(authenticationToken); } catch (AuthenticationException e) { log.warn(e.getLocalizedMessage(), e); return false; } return authenticationInfo != null; } @Override public boolean authenticate(Object credentials) throws UserStoreException { log.error("LDAP user store only supports authenticating with user name and password."); throw new NotImplementedException(); } public void configure(Node specificConfigurationNode) throws UserStoreException{ /** * <specificConfiguration> * <ldap> * <url>ldap://localhost:10389</url> * <systemUser>admin</systemUser> * <systemUserPassword>secret</systemUserPassword> * <userDNTemplate>uid={0},ou=system</userDNTemplate> * </ldap> * </specificConfiguration> */ Node configurationNode = null; if (specificConfigurationNode != null) { NodeList nodeList = specificConfigurationNode.getChildNodes(); for (int i=0; i < nodeList.getLength(); ++i) { Node n = nodeList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { configurationNode = n; } } } String url = null; String systemUser = null; String systemUserPassword = null; String userTemplate = null; if (configurationNode != null) { NodeList nodeList = configurationNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); ++i) { Node n = nodeList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) n; if (element.getNodeName().equals("url")) { url = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("systemUser")) { systemUser = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("systemUserPassword")) { systemUserPassword = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("userDNTemplate")) { userTemplate = element.getFirstChild().getNodeValue(); } } } } initializeLDAP(url, systemUser, systemUserPassword, userTemplate); } protected void initializeLDAP(String ldapUrl, String systemUser, String systemUserPassword, String userNameTemplate) { JndiLdapContextFactory jndiLdapContextFactory = new JndiLdapContextFactory(); jndiLdapContextFactory.setUrl(ldapUrl); jndiLdapContextFactory.setSystemUsername(systemUser); jndiLdapContextFactory.setSystemPassword(systemUserPassword); ldapRealm = new JndiLdapRealm(); ldapRealm.setContextFactory(jndiLdapContextFactory); ldapRealm.setUserDnTemplate(userNameTemplate); ldapRealm.init(); } }
8,635
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/userstore/AbstractJDBCUserStore.java
/* * * * * * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.apache.airavata.security.userstore; import org.apache.airavata.security.UserStore; import org.apache.airavata.security.UserStoreException; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * An abstract implementation of the UserStore. This will encapsulate * JDBC configurations reading code. */ public abstract class AbstractJDBCUserStore implements UserStore { private String databaseURL = null; private String databaseDriver = null; private String databaseUserName = null; private String databasePassword = null; public String getDatabaseURL() { return databaseURL; } public String getDatabaseDriver() { return databaseDriver; } public String getDatabaseUserName() { return databaseUserName; } public String getDatabasePassword() { return databasePassword; } /** * Configures primary JDBC parameters. i.e * @param node An XML configuration node. * @throws UserStoreException */ public void configure(Node node) throws UserStoreException{ /** <specificConfigurations> <database> <jdbcUrl></jdbcUrl> <databaseDriver></databaseDriver> <userName></userName> <password></password> </database> </specificConfigurations> */ NodeList databaseNodeList = node.getChildNodes(); Node databaseNode = null; for (int k = 0; k < databaseNodeList.getLength(); ++k) { Node n = databaseNodeList.item(k); if (n != null && n.getNodeType() == Node.ELEMENT_NODE) { databaseNode = n; } } if (databaseNode != null) { NodeList nodeList = databaseNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); ++i) { Node n = nodeList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) n; if (element.getNodeName().equals("jdbcUrl")) { databaseURL = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("databaseDriver")) { databaseDriver = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("userName")) { databaseUserName = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("password")) { databasePassword = element.getFirstChild().getNodeValue(); } } } } } }
8,636
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/security/src/main/java/org/apache/airavata/security/userstore/SessionDBUserStore.java
/* * * * * * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, * * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * * KIND, either express or implied. See the License for the * * specific language governing permissions and limitations * * under the License. * * * */ package org.apache.airavata.security.userstore; import org.apache.airavata.security.UserStoreException; import org.apache.airavata.security.util.DBLookup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.sql.SQLException; /** * User store which works on sessions. Will talk to database to check * whether session ids are stored in the database. */ public class SessionDBUserStore extends AbstractJDBCUserStore { private String sessionTable; private String sessionColumn; private String comparingColumn; protected DBLookup dbLookup; protected static Logger log = LoggerFactory.getLogger(SessionDBUserStore.class); @Override public boolean authenticate(String userName, Object credentials) throws UserStoreException { // This user store only supports session tokens. throw new NotImplementedException(); } @Override public boolean authenticate(Object credentials) throws UserStoreException { String sessionTicket = (String)credentials; try { String sessionString = dbLookup.getMatchingColumnValue(sessionTable, sessionColumn, sessionTicket); return (sessionString != null); } catch (SQLException e) { throw new UserStoreException("Error querying database for session information.", e); } } @Override public void configure(Node node) throws UserStoreException { super.configure(node); /** <specificConfigurations> <sessionTable> </sessionTable> <sessionColumn></sessionColumn> <comparingColumn></comparingColumn> </specificConfigurations> */ NodeList databaseNodeList = node.getChildNodes(); Node databaseNode = null; for (int k = 0; k < databaseNodeList.getLength(); ++k) { Node n = databaseNodeList.item(k); if (n != null && n.getNodeType() == Node.ELEMENT_NODE) { databaseNode = n; } } if (databaseNode != null) { NodeList nodeList = databaseNode.getChildNodes(); for (int i = 0; i < nodeList.getLength(); ++i) { Node n = nodeList.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) n; if (element.getNodeName().equals("sessionTable")) { sessionTable = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("sessionColumn")) { sessionColumn = element.getFirstChild().getNodeValue(); } else if (element.getNodeName().equals("comparingColumn")) { comparingColumn = element.getFirstChild().getNodeValue(); } } } } initializeDatabaseLookup(); StringBuilder stringBuilder = new StringBuilder("Configuring DB parameters for authenticator with Session Table - "); stringBuilder.append(sessionTable).append(" Session column - ").append(sessionColumn).append(" Comparing column - "). append(comparingColumn); log.info(stringBuilder.toString()); } private void initializeDatabaseLookup() throws RuntimeException { this.dbLookup = new DBLookup(getDatabaseURL(), getDatabaseUserName(), getDatabasePassword(), getDatabaseDriver()); try { this.dbLookup.init(); } catch (ClassNotFoundException e) { throw new RuntimeException("Error loading database driver. Driver class not found.", e); } catch (InstantiationException e) { throw new RuntimeException("Error loading database driver. Error instantiating driver object.", e); } catch (IllegalAccessException e) { throw new RuntimeException("Error loading database driver. Illegal access to driver object.", e); } } }
8,637
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/test/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/test/java/org/apache/airavata/services/registry/rest/security/MyHttpServletRequest.java
package org.apache.airavata.services.registry.rest.security; import javax.servlet.*; import javax.servlet.http.*; import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.*; /** * Test servlet implementation. For test cases only. */ public class MyHttpServletRequest implements HttpServletRequest { private Map<String, String> headers = new HashMap<String, String>(); public void addHeader(String name, String value) { headers.put(name, value); } @Override public String getAuthType() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Cookie[] getCookies() { return new Cookie[0]; //To change body of implemented methods use File | Settings | File Templates. } @Override public long getDateHeader(String s) { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getHeader(String s) { return headers.get(s); } @Override public Enumeration<String> getHeaders(String s) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Enumeration<String> getHeaderNames() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getIntHeader(String s) { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getMethod() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getPathInfo() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getPathTranslated() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getContextPath() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getQueryString() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getRemoteUser() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isUserInRole(String s) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public Principal getUserPrincipal() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getRequestedSessionId() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getRequestURI() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public StringBuffer getRequestURL() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getServletPath() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public HttpSession getSession(boolean b) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public HttpSession getSession() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isRequestedSessionIdValid() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isRequestedSessionIdFromCookie() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isRequestedSessionIdFromURL() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isRequestedSessionIdFromUrl() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean authenticate(HttpServletResponse httpServletResponse) throws IOException, ServletException { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public void login(String s, String s1) throws ServletException { //To change body of implemented methods use File | Settings | File Templates. } @Override public void logout() throws ServletException { //To change body of implemented methods use File | Settings | File Templates. } @Override public Collection<Part> getParts() throws IOException, ServletException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Part getPart(String s) throws IOException, ServletException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Object getAttribute(String s) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Enumeration<String> getAttributeNames() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getCharacterEncoding() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setCharacterEncoding(String s) throws UnsupportedEncodingException { //To change body of implemented methods use File | Settings | File Templates. } @Override public int getContentLength() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getContentType() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public ServletInputStream getInputStream() throws IOException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getParameter(String s) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Enumeration<String> getParameterNames() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String[] getParameterValues(String s) { return new String[0]; //To change body of implemented methods use File | Settings | File Templates. } @Override public Map<String, String[]> getParameterMap() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getProtocol() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getScheme() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getServerName() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getServerPort() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public BufferedReader getReader() throws IOException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getRemoteAddr() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getRemoteHost() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public void setAttribute(String s, Object o) { //To change body of implemented methods use File | Settings | File Templates. } @Override public void removeAttribute(String s) { //To change body of implemented methods use File | Settings | File Templates. } @Override public Locale getLocale() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public Enumeration<Locale> getLocales() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isSecure() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public RequestDispatcher getRequestDispatcher(String s) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getRealPath(String s) { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getRemotePort() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getLocalName() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public String getLocalAddr() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public int getLocalPort() { return 0; //To change body of implemented methods use File | Settings | File Templates. } @Override public ServletContext getServletContext() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public AsyncContext startAsync() throws IllegalStateException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isAsyncStarted() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean isAsyncSupported() { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public AsyncContext getAsyncContext() { return null; //To change body of implemented methods use File | Settings | File Templates. } @Override public DispatcherType getDispatcherType() { return null; //To change body of implemented methods use File | Settings | File Templates. } }
8,638
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/test/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/test/java/org/apache/airavata/services/registry/rest/security/AbstractAuthenticatorTest.java
package org.apache.airavata.services.registry.rest.security; import junit.framework.TestCase; import org.apache.airavata.security.Authenticator; import org.apache.airavata.security.configurations.AuthenticatorConfigurationReader; import java.util.List; /** * An abstract class to implement test cases for authenticators. */ public abstract class AbstractAuthenticatorTest extends TestCase { private String authenticatorName; protected Authenticator authenticator = null; public AbstractAuthenticatorTest(String name) throws Exception { authenticatorName = name; } protected AuthenticatorConfigurationReader authenticatorConfigurationReader; public void setUp() throws Exception { authenticatorConfigurationReader = new AuthenticatorConfigurationReader(); authenticatorConfigurationReader.init(this.getClass().getClassLoader().getResourceAsStream("authenticators.xml")); List<Authenticator> listAuthenticators = authenticatorConfigurationReader.getAuthenticatorList(); if (listAuthenticators == null) { throw new Exception("No authenticators found !"); } for (Authenticator a : listAuthenticators) { if (a.getAuthenticatorName().equals(authenticatorName)) { authenticator = a; } } if (authenticator == null) { throw new Exception("Could not find an authenticator with name " + authenticatorName); } } public abstract void testAuthenticateSuccess() throws Exception; public abstract void testAuthenticateFail() throws Exception; public abstract void testCanProcess() throws Exception; }
8,639
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/test/java/org/apache/airavata/services/registry/rest/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/test/java/org/apache/airavata/services/registry/rest/security/basic/BasicAccessAuthenticatorTest.java
package org.apache.airavata.services.registry.rest.security.basic; import org.apache.airavata.security.configurations.AuthenticatorConfigurationReader; import org.apache.airavata.services.registry.rest.security.AbstractAuthenticatorTest; import org.apache.airavata.services.registry.rest.security.MyHttpServletRequest; import org.apache.airavata.services.registry.rest.security.session.SessionAuthenticator; import org.apache.commons.codec.binary.Base64; /** * Test class for basic access authenticator. */ public class BasicAccessAuthenticatorTest extends AbstractAuthenticatorTest { private SessionAuthenticator sessionAuthenticator; private AuthenticatorConfigurationReader authenticatorConfigurationReader; public BasicAccessAuthenticatorTest() throws Exception { super("basicAccessAuthenticator"); } @Override public void testAuthenticateSuccess() throws Exception { assertTrue(authenticator.authenticate(getRequest("amilaj:secret"))); } @Override public void testAuthenticateFail() throws Exception { assertFalse(authenticator.authenticate(getRequest("amilaj:secret1"))); } public void testAuthenticateFailUserName() throws Exception { assertFalse(authenticator.authenticate(getRequest("amila:secret1"))); } @Override public void testCanProcess() throws Exception { assertTrue(authenticator.canProcess(getRequest("amilaj:secret"))); } private MyHttpServletRequest getRequest(String userPassword) { MyHttpServletRequest myHttpServletRequest = new MyHttpServletRequest(); String authHeader = "Basic " + new String(Base64.encodeBase64(userPassword.getBytes())); myHttpServletRequest.addHeader("Authorization", authHeader); return myHttpServletRequest; } public void tearDown() throws Exception { } /*public void testConfigure() throws Exception { BasicAccessAuthenticator basicAccessAuthenticator = (BasicAccessAuthenticator)authenticator; assertEquals("AIRAVATA_USER", basicAccessAuthenticator.getUserTable()); assertEquals("USERID", basicAccessAuthenticator.getUserNameColumn()); assertEquals("PASSWORD", basicAccessAuthenticator.getPasswordColumn()); }*/ }
8,640
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/test/java/org/apache/airavata/services/registry/rest/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/test/java/org/apache/airavata/services/registry/rest/security/session/DBLookupTest.java
package org.apache.airavata.services.registry.rest.security.session; import junit.framework.TestCase; import org.apache.airavata.security.util.DBLookup; import java.io.File; /** * Test class for DBSession lookup. */ public class DBLookupTest extends TestCase { private DBLookup dbLookup; private String url = "jdbc:h2:src/test/resources/testdb/test"; //private String url = "jdbc:h2:modules/commons/airavata-registry-rest/src/test/resources/testdb/test"; private String userName = "sa"; private String password = "sa"; private String driver = "org.h2.Driver"; private String sessionTable = "Persons"; private String sessionColumn = "sessionId"; public void setUp() throws Exception { File f = new File("."); System.out.println(f.getAbsolutePath()); dbLookup = new DBLookup(url, userName, password, driver); dbLookup.init(); } public void tearDown() throws Exception { } public void testGetSessionString() throws Exception { String sessionId = dbLookup.getMatchingColumnValue(sessionTable, sessionColumn, "1234"); assertNotNull(sessionId); } public void testGetSessionStringInvalidSession() throws Exception { String sessionId = dbLookup.getMatchingColumnValue(sessionTable, sessionColumn, "12345"); assertNull(sessionId); } }
8,641
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/test/java/org/apache/airavata/services/registry/rest/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/test/java/org/apache/airavata/services/registry/rest/security/session/SessionAuthenticatorTest.java
package org.apache.airavata.services.registry.rest.security.session; import org.apache.airavata.services.registry.rest.security.AbstractAuthenticatorTest; import org.apache.airavata.services.registry.rest.security.MyHttpServletRequest; /** * Session authenticator test. */ public class SessionAuthenticatorTest extends AbstractAuthenticatorTest { public SessionAuthenticatorTest() throws Exception { super("sessionAuthenticator"); } public void testAuthenticateSuccess() throws Exception { MyHttpServletRequest servletRequestRequest = new MyHttpServletRequest(); servletRequestRequest.addHeader("sessionTicket", "1234"); assertTrue(authenticator.authenticate(servletRequestRequest)); } public void testAuthenticateFail() throws Exception { MyHttpServletRequest servletRequestRequest = new MyHttpServletRequest(); servletRequestRequest.addHeader("sessionTicket", "12345"); assertFalse(authenticator.authenticate(servletRequestRequest)); } public void testCanProcess() throws Exception { MyHttpServletRequest servletRequestRequest = new MyHttpServletRequest(); servletRequestRequest.addHeader("sessionTicket", "12345"); assertTrue(authenticator.canProcess(servletRequestRequest)); } }
8,642
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/User.java
package org.apache.airavata.services.registry.rest; /** * Created with IntelliJ IDEA. * User: amila * Date: 8/29/12 * Time: 10:33 AM * To change this template use File | Settings | File Templates. */ public class User { private String userName; private String password; public User() { } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
8,643
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/security/HttpAuthenticatorFilter.java
package org.apache.airavata.services.registry.rest.security; import org.apache.airavata.security.AuthenticationException; import org.apache.airavata.security.Authenticator; import org.apache.airavata.security.configurations.AuthenticatorConfigurationReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.SAXException; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.InputStream; import java.util.Calendar; import java.util.List; /** * A servlet filter class which intercepts the request and do authentication. */ public class HttpAuthenticatorFilter implements Filter { private List<Authenticator> authenticatorList; private static Logger log = LoggerFactory.getLogger(HttpAuthenticatorFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { String authenticatorConfiguration = filterConfig.getInitParameter("authenticatorConfigurations"); //TODO make this able to read from a file as well InputStream configurationFileStream = HttpAuthenticatorFilter.class.getClassLoader(). getResourceAsStream(authenticatorConfiguration); if (configurationFileStream == null) { String msg = "Invalid authenticator configuration. Cannot read file - ".concat(authenticatorConfiguration); log.error(msg); throw new ServletException(msg); } AuthenticatorConfigurationReader authenticatorConfigurationReader = new AuthenticatorConfigurationReader(); try { authenticatorConfigurationReader.init(configurationFileStream); } catch (IOException e) { String msg = "Error reading authenticator configurations."; log.error(msg, e); throw new ServletException(msg, e); } catch (ParserConfigurationException e) { String msg = "Error parsing authenticator configurations."; log.error(msg, e); throw new ServletException(msg, e); } catch (SAXException e) { String msg = "Error parsing authenticator configurations."; log.error(msg, e); throw new ServletException(msg, e); } finally { try { configurationFileStream.close(); } catch (IOException e) { log.error("Error closing authenticator file stream.", e); } } this.authenticatorList = authenticatorConfigurationReader.getAuthenticatorList(); if (this.authenticatorList.isEmpty()) { String msg = "No authenticators registered in the system. System cannot function without authenticators"; log.error(msg); throw new ServletException(msg); } } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // Firs check whether authenticators are disabled if (! AuthenticatorConfigurationReader.isAuthenticationEnabled()) { filterChain.doFilter(servletRequest, servletResponse); return; } HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; Authenticator authenticator = getAuthenticator(httpServletRequest); if (authenticator == null) { //sendUnauthorisedError(servletResponse, "Invalid request. Request does not contain sufficient credentials to authenticate"); populateUnauthorisedData(servletResponse, "Invalid request. Request does not contain sufficient credentials to authenticate"); } else { if (authenticator.isAuthenticated(httpServletRequest)) { // Allow request to flow filterChain.doFilter(servletRequest, servletResponse); } else { try { if (!authenticator.authenticate(httpServletRequest)) { //sendUnauthorisedError(servletResponse, "Unauthorised : Provided credentials are not valid."); populateUnauthorisedData(servletResponse, "Invalid request. Request does not contain sufficient credentials to authenticate"); } else { // Allow request to flow filterChain.doFilter(servletRequest, servletResponse); } } catch (AuthenticationException e) { String msg = "An error occurred while authenticating request."; log.error(msg, e); //sendUnauthorisedError(servletResponse, e.getMessage()); populateUnauthorisedData(servletResponse, "Invalid request. Request does not contain sufficient credentials to authenticate"); } } } } protected void sendUnauthorisedError(ServletResponse servletResponse, String message) throws IOException { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, message); } @Override public void destroy() { if (this.authenticatorList != null) { this.authenticatorList.clear(); } this.authenticatorList = null; } private Authenticator getAuthenticator(HttpServletRequest httpServletRequest) { for (Authenticator authenticator : authenticatorList) { if (authenticator.canProcess(httpServletRequest)) { return authenticator; } } return null; } /** * This method will create a 401 unauthorized response to be sent. * * @param servletResponse The HTTP response. */ private void populateUnauthorisedData(ServletResponse servletResponse, String message) { HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse; httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); httpServletResponse.addHeader("Server", "Airavata Server"); httpServletResponse.addHeader("Description", message); httpServletResponse.addDateHeader("Date", Calendar.getInstance().getTimeInMillis()); httpServletResponse.addHeader("WWW-Authenticate", "Basic realm=Airavata"); httpServletResponse.setContentType("text/html"); } }
8,644
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/security/basic/BasicAccessAuthenticator.java
package org.apache.airavata.services.registry.rest.security.basic; import org.apache.airavata.security.AbstractAuthenticator; import org.apache.airavata.security.AuthenticationException; import org.apache.airavata.security.UserStoreException; import org.apache.commons.codec.binary.Base64; import org.w3c.dom.Node; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * This authenticator handles basic access authentication requests. In basic access authentication * we get user name and password as HTTP headers. The password is encoded with base64. * More information @link{http://en.wikipedia.org/wiki/Basic_access_authentication} */ public class BasicAccessAuthenticator extends AbstractAuthenticator { private static final String AUTHENTICATOR_NAME = "BasicAccessAuthenticator"; /** * Header names */ private static final String AUTHORISATION_HEADER_NAME = "Authorization"; private static final String USER_IN_SESSION = "userName"; public BasicAccessAuthenticator() { super(AUTHENTICATOR_NAME); } private String decode(String encoded) { return new String(Base64.decodeBase64(encoded.getBytes())); } /** * Returns user name and password as an array. The first element is user name and second is password. * * @param httpServletRequest The servlet request. * @return User name password pair as an array. * @throws AuthenticationException If an error occurred while extracting user name and password. */ private String[] getUserNamePassword(HttpServletRequest httpServletRequest) throws AuthenticationException { String basicHeader = httpServletRequest.getHeader(AUTHORISATION_HEADER_NAME); if (basicHeader == null) { throw new AuthenticationException("Authorization Required"); } String[] userNamePasswordArray = basicHeader.split(" "); if (userNamePasswordArray == null || userNamePasswordArray.length != 2) { throw new AuthenticationException("Authorization Required"); } String decodedString = decode(userNamePasswordArray[1]); String[] array = decodedString.split(":"); if (array == null || array.length != 2) { throw new AuthenticationException("Authorization Required"); } return array; } @Override protected boolean doAuthentication(Object credentials) throws AuthenticationException { if (this.getUserStore() == null) { throw new AuthenticationException("Authenticator is not initialized. Error processing request."); } if (credentials == null) return false; HttpServletRequest httpServletRequest = (HttpServletRequest) credentials; String[] array = getUserNamePassword(httpServletRequest); String userName = array[0]; String password = array[1]; try { return this.getUserStore().authenticate(userName, password); } catch (UserStoreException e) { throw new AuthenticationException("Error querying database for session information.", e); } } protected void addUserToSession(String userName, HttpServletRequest servletRequest) { if (servletRequest.getSession() != null) { servletRequest.getSession().setAttribute(USER_IN_SESSION, userName); } } @Override public void onSuccessfulAuthentication(Object authenticationInfo) { HttpServletRequest httpServletRequest = (HttpServletRequest) authenticationInfo; try { String[] array = getUserNamePassword(httpServletRequest); StringBuilder stringBuilder = new StringBuilder("User : "); if (array != null) { addUserToSession(array[0], httpServletRequest); stringBuilder.append(array[0]).append(" successfully logged into system at ").append(getCurrentTime()); log.info(stringBuilder.toString()); } else { log.error("System error occurred while extracting user name after authentication. " + "Couldn't extract user name from the request."); } } catch (AuthenticationException e) { log.error("System error occurred while extracting user name after authentication.", e); } } @Override public void onFailedAuthentication(Object authenticationInfo) { HttpServletRequest httpServletRequest = (HttpServletRequest) authenticationInfo; try { String[] array = getUserNamePassword(httpServletRequest); StringBuilder stringBuilder = new StringBuilder("User : "); if (array != null) { stringBuilder.append(array[0]).append(" Failed login attempt to system at ").append(getCurrentTime()); log.warn(stringBuilder.toString()); } else { stringBuilder.append("Failed login attempt to system at ").append(getCurrentTime()).append( ". User unknown."); log.warn(stringBuilder.toString()); } } catch (AuthenticationException e) { log.error("System error occurred while extracting user name after authentication.", e); } } @Override public boolean isAuthenticated(Object credentials) { HttpServletRequest httpServletRequest = (HttpServletRequest) credentials; HttpSession httpSession = httpServletRequest.getSession(); return httpSession != null && httpSession.getAttribute(USER_IN_SESSION) != null; } @Override public boolean canProcess(Object credentials) { HttpServletRequest httpServletRequest = (HttpServletRequest) credentials; return (httpServletRequest.getHeader(AUTHORISATION_HEADER_NAME) != null); } @Override public void configure(Node node) throws RuntimeException { /** <specificConfigurations> <database> <jdbcUrl></jdbcUrl> <databaseDriver></databaseDriver> <userName></userName> <password></password> <userTableName></userTableName> <userNameColumnName></userNameColumnName> <passwordColumnName></passwordColumnName> </database> </specificConfigurations> */ try { this.getUserStore().configure(node); } catch (UserStoreException e) { throw new RuntimeException("Error while configuring authenticator user store", e); } } }
8,645
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/security
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/security/session/SessionAuthenticator.java
package org.apache.airavata.services.registry.rest.security.session; import org.apache.airavata.security.AbstractAuthenticator; import org.apache.airavata.security.AuthenticationException; import org.apache.airavata.security.UserStoreException; import org.w3c.dom.Node; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * This authenticator will authenticate requests based on a session (NOT HTTP Session) id stored * in the database. */ public class SessionAuthenticator extends AbstractAuthenticator { private static final String AUTHENTICATOR_NAME = "SessionAuthenticator"; private static final String SESSION_TICKET = "sessionTicket"; public SessionAuthenticator() { super(AUTHENTICATOR_NAME); } @Override public boolean doAuthentication(Object credentials) throws AuthenticationException { if (credentials == null) return false; HttpServletRequest httpServletRequest = (HttpServletRequest)credentials; String sessionTicket = httpServletRequest.getHeader(SESSION_TICKET); try { return this.getUserStore().authenticate(sessionTicket); } catch (UserStoreException e) { throw new AuthenticationException("Error querying database for session information.", e); } } @Override public boolean canProcess(Object credentials) { if (credentials instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) credentials; String ticket = request.getHeader(SESSION_TICKET); if (ticket != null) { return true; } } return false; } @Override public void onSuccessfulAuthentication(Object authenticationInfo) { HttpServletRequest httpServletRequest = (HttpServletRequest)authenticationInfo; String sessionTicket = httpServletRequest.getHeader(SESSION_TICKET); // Add sessionTicket to http session HttpSession httpSession = httpServletRequest.getSession(); if (httpSession != null) { httpSession.setAttribute(SESSION_TICKET, sessionTicket); } log.info("A request with a session ticket is successfully logged in."); } @Override public void onFailedAuthentication(Object authenticationInfo) { log.warn("Failed attempt to login."); } @Override public void configure(Node node) throws RuntimeException { try { this.getUserStore().configure(node); } catch (UserStoreException e) { throw new RuntimeException("Error while configuring authenticator user store", e); } } @Override public boolean isAuthenticated(Object credentials) { HttpServletRequest httpServletRequest = (HttpServletRequest)credentials; if (httpServletRequest.getSession() != null) { String sessionTicket = (String)httpServletRequest.getSession().getAttribute(SESSION_TICKET); return (sessionTicket != null); } return false; } }
8,646
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/CredentialStoreAPI.java
package org.apache.airavata.services.registry.rest.resources; import org.apache.airavata.credential.store.AuditInfo; import org.apache.airavata.credential.store.CredentialStore; import org.apache.airavata.credential.store.CredentialStoreException; import org.apache.airavata.services.registry.rest.utils.RegistryListener; import javax.servlet.ServletContext; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; /** * API to access the credential store. * Provides methods to manage credential store and to query information in credential store. * Though we will not provide methods to retrieve credentials. * We will trust the portal to execute following operations and we will also assume * portal interface will implement appropriate authentication and authorization. */ @Path("/credentialStore") public class CredentialStoreAPI { @Context ServletContext context; @Path("/get/portalUser") @GET @Produces("text/plain") public Response getAssociatingPortalUser(@QueryParam("gatewayName")String gatewayName, @QueryParam("communityUserName")String communityUser) { try { String result = getCredentialStore().getPortalUser(gatewayName, communityUser); return getOKResponse(result); } catch (CredentialStoreException e) { return getErrorResponse(e); } } @Path("/get/portalUser") @GET @Produces("text/plain") public Response getAuditInfo(@QueryParam("gatewayName")String gatewayName, @QueryParam("communityUserName")String communityUser) { try { AuditInfo auditInfo = getCredentialStore().getAuditInfo(gatewayName, communityUser); return getOKResponse(auditInfo); } catch (CredentialStoreException e) { return getErrorResponse(e); } } @Path("/delete/credential") @POST @Produces("text/plain") public Response removeCredentials(@QueryParam("gatewayName")String gatewayName, @QueryParam("communityUserName")String communityUser) { try { getCredentialStore().removeCredentials(gatewayName, communityUser); return getOKResponse("success"); } catch (CredentialStoreException e) { return getErrorResponse(e); } } @Path("/update/email") @POST @Produces("text/plain") public Response updateCommunityUserEmail(@QueryParam("gatewayName")String gatewayName, @QueryParam("communityUserName")String communityUser, @QueryParam("email")String email) { try { getCredentialStore().updateCommunityUserEmail(gatewayName, communityUser, email); return getOKResponse("success"); } catch (CredentialStoreException e) { return getErrorResponse(e); } } private CredentialStore getCredentialStore() { return (CredentialStore) context.getAttribute(RegistryListener.CREDENTIAL_STORE); } private Response getOKResponse(String result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } private Response getOKResponse(AuditInfo result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } private Response getErrorResponse(CredentialStoreException exception) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity(exception.getMessage()); return builder.build(); } }
8,647
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/RegistryResource.java
package org.apache.airavata.services.registry.rest.resources; import org.apache.airavata.common.registry.api.exception.RegistryException; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.registry.api.AiravataRegistry; import org.apache.airavata.registry.api.Axis2Registry; import org.apache.airavata.registry.api.DataRegistry; import org.apache.airavata.registry.api.workflow.WorkflowExecution; import org.apache.airavata.registry.api.workflow.WorkflowIOData; import org.apache.airavata.registry.api.workflow.WorkflowInstanceStatus; import org.apache.airavata.registry.api.workflow.WorkflowServiceIOData; import org.apache.xmlbeans.XmlException; import javax.jcr.Node; import javax.servlet.ServletContext; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.xml.namespace.QName; import java.net.URI; import java.net.URISyntaxException; import java.sql.Timestamp; import java.util.List; import java.util.Map; @Path("/airavataRegistry/api") public class RegistryResource { private AiravataRegistry airavataRegistry; private Axis2Registry axis2Registry; private DataRegistry dataRegistry; @Context ServletContext context; @Path("/userName") @GET @Produces("text/plain") public String getUserName() { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); return airavataRegistry.getUsername(); // return "Amila Jayasekara"; } @Path("/repositoryUrl") @GET @Produces("text/plain") public String getRepositoryURI() { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); return airavataRegistry.getRepositoryURI().toString(); } @Path("/repositoryName") @GET @Produces("text/plain") public String getName() { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); return airavataRegistry.getName(); } @Path("/service/wsdl") @GET @Produces("text/xml") public Response getWSDL(@QueryParam("serviceName") String serviceName) { axis2Registry = (Axis2Registry) context.getAttribute("axis2Registry"); try { String result = axis2Registry.getWSDL(serviceName); if (result != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } //need to check the name /*@Path("/service/description/wsdl") @GET @Produces("text/xml") public Response getWSDLFromServiceDescription(@FormParam("service") String service) { axis2Registry = (Axis2Registry) context.getAttribute("axis2Registry"); try { ServiceDescription serviceDescription = ServiceDescription.fromXML(service); String result = axis2Registry.getWSDL(serviceDescription); if (result != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } */ @Path("/service/description") @GET @Produces("text/xml") public String getServiceDescription(@QueryParam("serviceID") String serviceId) throws RegistryException { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); return airavataRegistry.getServiceDescription(serviceId).toXML(); } @Path("/service/deploymentDescription") @GET @Produces("text/xml") public String getDeploymentDescription(@QueryParam("serviceID") String serviceId, @QueryParam("hostId") String hostId) throws RegistryException { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); return airavataRegistry.getDeploymentDescription(serviceId, hostId).toXML(); } @Path("host/description") @GET @Produces("text/xml") public String getHostDescription(@QueryParam("hostId") String hostId) throws RegistryException { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); return airavataRegistry.getHostDescription(hostId).toXML(); } @POST @Path("save/hostDescription") @Produces("text/plain") public Response saveHostDescription(@FormParam("host") String host) { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); try { HostDescription hostDescription = HostDescription.fromXML(host); String result = airavataRegistry.saveHostDescription(hostDescription); if (result != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (XmlException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity("Invalid XML"); return builder.build(); } } @POST @Path("save/serviceDescription") @Produces("text/plain") public Response saveServiceDescription(@FormParam("service") String service) { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); try { ServiceDescription serviceDescription = ServiceDescription.fromXML(service); String result = airavataRegistry.saveServiceDescription(serviceDescription); if (result != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (XmlException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity("Invalid XML"); return builder.build(); } } @POST @Path("save/deploymentDescription") @Produces("text/plain") public Response saveDeploymentDescription(@FormParam("serviceId") String serviceId, @FormParam("hostId") String hostId, @FormParam("app") String app) { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); try { ApplicationDeploymentDescription deploymentDescription = ApplicationDeploymentDescription.fromXML(app); String result = airavataRegistry.saveDeploymentDescription(serviceId, hostId, deploymentDescription); if (result != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (XmlException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } } @POST @Path("service/deployOnHost") @Produces("text/plain") public Response deployServiceOnHost(@FormParam("serviceName") String serviceName, @FormParam("hostName") String hostName) { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); boolean state; try { state = airavataRegistry.deployServiceOnHost(serviceName, hostName); if (state) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } public List<HostDescription> searchHostDescription(String name) throws RegistryException { return null; } public List<ServiceDescription> searchServiceDescription(String nameRegEx) throws RegistryException { return null; } public List<ApplicationDeploymentDescription> searchDeploymentDescription(String serviceName, String hostName) throws RegistryException { return null; } public Map<HostDescription, List<ApplicationDeploymentDescription>> searchDeploymentDescription(String serviceName) throws RegistryException { return null; } public List<ApplicationDeploymentDescription> searchDeploymentDescription(String serviceName, String hostName, String applicationName) throws RegistryException { return null; } public Map<ApplicationDeploymentDescription, String> searchDeploymentDescription() throws RegistryException { return null; } @POST @Path("save/gfacDescriptor") @Produces("text/plain") public Response saveGFacDescriptor(@FormParam("gfacURL") String gfacURL) { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); try { Boolean result = airavataRegistry.saveGFacDescriptor(gfacURL); if (result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("true"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("delete/gfacDescriptor") @Produces("text/plain") public Response deleteGFacDescriptor(@QueryParam("gfacURL") String gfacURL) throws RegistryException { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); try { Boolean result = airavataRegistry.deleteGFacDescriptor(gfacURL); if (result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("true"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } public List<URI> getInterpreterServiceURLList() throws RegistryException { return null; } @POST @Path("save/interpreterServiceUrl") @Produces("text/plain") public Response saveInterpreterServiceURL(@QueryParam("gfacURL") String gfacURL) { airavataRegistry = (AiravataRegistry) context.getAttribute("airavataRegistry"); try { URI gfacURI = new URI(gfacURL); Boolean result = airavataRegistry.saveInterpreterServiceURL(gfacURI); if (result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("true"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (URISyntaxException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } } @DELETE @Path("delete/interpreterServiceURL") @Produces("text/plain") public Response deleteInterpreterServiceURL(URI gfacURL) throws RegistryException { return null; } public List<URI> getMessageBoxServiceURLList() throws RegistryException { return null; } public boolean saveMessageBoxServiceURL(URI gfacURL) throws RegistryException { return true; } public boolean deleteMessageBoxServiceURL(URI gfacURL) throws RegistryException { return true; } public List<URI> getEventingServiceURLList() throws RegistryException { return null; } public boolean saveEventingServiceURL(URI gfacURL) throws RegistryException { return true; } public boolean deleteEventingServiceURL(URI gfacURL) throws RegistryException { return true; } public List<String> getGFacDescriptorList() throws RegistryException { return null; } public boolean saveWorkflow(QName ResourceID, String workflowName, String resourceDesc, String workflowAsaString, String owner, boolean isMakePublic) throws RegistryException { return true; } public Map<QName, Node> getWorkflows(String userName) throws RegistryException { return null; } public Node getWorkflow(QName templateID, String userName) throws RegistryException { return null; } public boolean deleteWorkflow(QName resourceID, String userName) throws RegistryException { return true; } public void deleteServiceDescription(String serviceId) throws RegistryException { } public void deleteDeploymentDescription(String serviceName, String hostName, String applicationName) throws RegistryException { } public void deleteHostDescription(String hostId) throws RegistryException { } public boolean saveWorkflowExecutionServiceInput(WorkflowServiceIOData workflowInputData) throws RegistryException { return true; } public boolean saveWorkflowExecutionServiceOutput(WorkflowServiceIOData workflowOutputData) throws RegistryException { return true; } public List<WorkflowServiceIOData> searchWorkflowExecutionServiceInput(String experimentIdRegEx, String workflowNameRegEx, String nodeNameRegEx) throws RegistryException { return null; } public String getWorkflowExecutionTemplateName(String experimentId) throws RegistryException { return null; } public List<WorkflowServiceIOData> searchWorkflowExecutionServiceOutput(String experimentIdRegEx, String workflowNameRegEx, String nodeNameRegEx) throws RegistryException { return null; } public boolean saveWorkflowExecutionName(String experimentId, String workflowIntanceName) throws RegistryException { return true; } public boolean saveWorkflowExecutionStatus(String experimentId, WorkflowInstanceStatus status) throws RegistryException { return true; } public boolean saveWorkflowExecutionStatus(String experimentId, WorkflowInstanceStatus.ExecutionStatus status) throws RegistryException { return true; } public WorkflowInstanceStatus getWorkflowExecutionStatus(String experimentId) throws RegistryException { return null; } public boolean saveWorkflowExecutionOutput(String experimentId, String outputNodeName, String output) throws RegistryException { return true; } public boolean saveWorkflowExecutionOutput(String experimentId, WorkflowIOData data) throws RegistryException { return true; } public WorkflowIOData getWorkflowExecutionOutput(String experimentId, String outputNodeName) throws RegistryException { return null; } public List<WorkflowIOData> getWorkflowExecutionOutput(String experimentId) throws RegistryException { return null; } public String[] getWorkflowExecutionOutputNames(String exeperimentId) throws RegistryException { return null; } public boolean saveWorkflowExecutionUser(String experimentId, String user) throws RegistryException { return true; } public String getWorkflowExecutionUser(String experimentId) throws RegistryException { return null; } public String getWorkflowExecutionName(String experimentId) throws RegistryException { return null; } public WorkflowExecution getWorkflowExecution(String experimentId) throws RegistryException { return null; } public List<String> getWorkflowExecutionIdByUser(String user) throws RegistryException { return null; } public List<WorkflowExecution> getWorkflowExecutionByUser(String user) throws RegistryException { return null; } public List<WorkflowExecution> getWorkflowExecutionByUser(String user, int pageSize, int pageNo) throws RegistryException { return null; } public String getWorkflowExecutionMetadata(String experimentId) throws RegistryException { return null; } public boolean saveWorkflowExecutionMetadata(String experimentId, String metadata) throws RegistryException { return true; } // public boolean saveWorkflowData(WorkflowRunTimeData workflowData)throws RegistryException{ // return true; // } public boolean saveWorkflowLastUpdateTime(String experimentId, Timestamp timestamp) throws RegistryException { return true; } public boolean saveWorkflowNodeStatus(String workflowInstanceID, String workflowNodeID, WorkflowInstanceStatus.ExecutionStatus status) throws RegistryException { return true; } public boolean saveWorkflowNodeLastUpdateTime(String workflowInstanceID, String workflowNodeID, Timestamp lastUpdateTime) throws RegistryException { return true; } // public boolean saveWorkflowNodeGramData(WorkflowNodeGramData workflowNodeGramData)throws RegistryException{ // return true; // } public boolean saveWorkflowNodeGramLocalJobID(String workflowInstanceID, String workflowNodeID, String localJobID) throws RegistryException { return true; } }
8,648
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/RegistryApplication.java
package org.apache.airavata.services.registry.rest.resources; import javax.ws.rs.core.Application; import java.util.HashSet; import java.util.Set; public class RegistryApplication extends Application { @Override public Set<Class<?>> getClasses() { final Set<Class<?>> classes = new HashSet<Class<?>>(); // register root resource classes.add(RegistryResource.class); classes.add(CredentialStoreAPI.class); return classes; } @Override public Set<Object> getSingletons() { return super.getSingletons(); } }
8,649
0
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-rest-security/modules/commons/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/utils/RegistryListener.java
package org.apache.airavata.services.registry.rest.utils; import org.apache.airavata.credential.store.CredentialStore; import org.apache.airavata.credential.store.impl.CredentialStoreImpl; import org.apache.airavata.credential.store.util.DBUtil; import org.apache.airavata.registry.api.AiravataRegistry; import org.apache.airavata.registry.api.Axis2Registry; import org.apache.airavata.registry.api.DataRegistry; import org.apache.airavata.registry.api.impl.AiravataJCRRegistry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.net.URI; import java.util.HashMap; public class RegistryListener implements ServletContextListener { private static AiravataRegistry airavataRegistry; private static Axis2Registry axis2Registry; private static DataRegistry dataRegistry; public static final String CREDENTIAL_STORE = "credentialStore"; protected static Logger log = LoggerFactory.getLogger(RegistryListener.class); public void contextInitialized(ServletContextEvent servletContextEvent) { try { ServletContext servletContext = servletContextEvent.getServletContext(); URI url = new URI("http://localhost:8081/rmi"); String username = "admin"; String password = "admin"; HashMap<String, String> map = new HashMap<String, String>(); map.put("org.apache.jackrabbit.repository.uri", url.toString()); airavataRegistry = new AiravataJCRRegistry(url, "org.apache.jackrabbit.rmi.repository.RmiRepositoryFactory", username, password, map); axis2Registry = new AiravataJCRRegistry(url, "org.apache.jackrabbit.rmi.repository.RmiRepositoryFactory", username, password, map); dataRegistry = new AiravataJCRRegistry(url, "org.apache.jackrabbit.rmi.repository.RmiRepositoryFactory", username, password, map); servletContext.setAttribute("airavataRegistry", airavataRegistry); servletContext.setAttribute("axis2Registry", axis2Registry); servletContext.setAttribute("dataRegistry", dataRegistry); initializeCredentialStoreAPI(servletContext); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } private void initializeCredentialStoreAPI(ServletContext servletContext) throws Exception { CredentialStore credentialStore = new CredentialStoreImpl(DBUtil.getDBUtil(servletContext)); servletContext.setAttribute(CREDENTIAL_STORE, credentialStore); } public void contextDestroyed(ServletContextEvent servletContextEvent) { } }
8,650
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/Test.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.services.registry.rest; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.schemas.gfac.GlobusHostType; import org.apache.airavata.services.registry.rest.client.ConfigurationResourceClient; import org.apache.airavata.services.registry.rest.client.DescriptorResourceClient; import org.apache.airavata.services.registry.rest.resourcemappings.HostDescriptor; import java.net.URI; import java.util.List; public class Test { public static void main(String[] args) { configurationResourceClientTest(); // descriptorClientTest(); } public static void configurationResourceClientTest(){ //configuration resource test ConfigurationResourceClient configurationResourceClient = new ConfigurationResourceClient(); // System.out.println("###############getConfiguration###############"); // Object configuration = configurationResourceClient.getConfiguration("interpreter.url"); // System.out.println(configuration.toString()); // // System.out.println("###############getConfigurationList###############"); // configurationResourceClient.addWFInterpreterURI("http://192.168.17.1:8080/axis2/services/WorkflowInterpretor2"); List<Object> configurationList = configurationResourceClient.getConfigurationList("testKey1"); for(Object object : configurationList){ System.out.println(object.toString()); } // // System.out.println("###############setConfiguration###############"); // configurationResourceClient.setConfiguration("testKey1", "testVal1", "2012-11-12 00:12:31"); // // System.out.println("###############addConfiguration###############"); // configurationResourceClient.addConfiguration("testKey1", "testVal2", "2012-11-12 05:12:31"); // System.out.println("###############remove all configuration ###############"); // configurationResourceClient.removeAllConfiguration("testKey1"); // // System.out.println("###############remove configuration ###############"); // configurationResourceClient.setConfiguration("testKey2", "testVal2", "2012-11-12 00:12:31"); // configurationResourceClient.removeAllConfiguration("testKey2"); // // System.out.println("###############get GFAC URI ###############"); // configurationResourceClient.addGFacURI("http://192.168.17.1:8080/axis2/services/GFacService2"); // List<URI> gFacURIs = configurationResourceClient.getGFacURIs(); // for (URI uri : gFacURIs){ // System.out.println(uri.toString()); // } // System.out.println("###############get WF interpreter URIs ###############"); // List<URI> workflowInterpreterURIs = configurationResourceClient.getWorkflowInterpreterURIs(); // for (URI uri : workflowInterpreterURIs){ // System.out.println(uri.toString()); // } // // System.out.println("###############get eventing URI ###############"); // URI eventingURI = configurationResourceClient.getEventingURI(); // System.out.println(eventingURI.toString()); // // System.out.println("###############get message Box URI ###############"); // URI mesgBoxUri = configurationResourceClient.getMsgBoxURI(); // System.out.println(mesgBoxUri.toString()); // // System.out.println("###############Set eventing URI ###############"); // configurationResourceClient.setEventingURI("http://192.168.17.1:8080/axis2/services/EventingService2"); // // System.out.println("###############Set MSGBox URI ###############"); // configurationResourceClient.setEventingURI("http://192.168.17.1:8080/axis2/services/MsgBoxService2"); // // System.out.println("###############Add GFAC URI by date ###############"); // configurationResourceClient.addGFacURIByDate("http://192.168.17.1:8080/axis2/services/GFacService3", "2012-11-12 00:12:27"); // // System.out.println("###############Add WF interpreter URI by date ###############"); // configurationResourceClient.addWorkflowInterpreterURI("http://192.168.17.1:8080/axis2/services/WorkflowInterpretor3", "2012-11-12 00:12:27"); // System.out.println("###############Set eventing URI by date ###############"); // configurationResourceClient.setEventingURIByDate("http://192.168.17.1:8080/axis2/services/EventingService3", "2012-11-12 00:12:27"); // // System.out.println("###############Set MsgBox URI by date ###############"); // configurationResourceClient.setMessageBoxURIByDate("http://192.168.17.1:8080/axis2/services/MsgBoxService3", "2012-11-12 00:12:27"); // System.out.println("############### Remove GFac URI ###############"); // configurationResourceClient.removeGFacURI("http://192.168.17.1:8080/axis2/services/GFacService3"); // // System.out.println("############### Remove all GFac URI ###############"); // configurationResourceClient.removeAllGFacURI(); // // System.out.println("############### Remove removeWorkflowInterpreter URI ###############"); // configurationResourceClient.removeWorkflowInterpreterURI("http://192.168.17.1:8080/axis2/services/WorkflowInterpretor3"); // System.out.println("############### Remove removeAllWorkflowInterpreterURI ###############"); // configurationResourceClient.removeAllWorkflowInterpreterURI(); // // System.out.println("############### Remove eventing URI ###############"); // configurationResourceClient.unsetEventingURI(); // // System.out.println("############### unsetMessageBoxURI ###############"); // configurationResourceClient.unsetMessageBoxURI(); } public static void descriptorClientTest(){ DescriptorResourceClient descriptorResourceClient = new DescriptorResourceClient(); // boolean localHost = descriptorResourceClient.isHostDescriptorExists("LocalHost"); // System.out.println(localHost); // HostDescription descriptor = new HostDescription(GlobusHostType.type); // descriptor.getType().setHostName("testHost"); // descriptor.getType().setHostAddress("testHostAddress2"); // descriptorResourceClient.addHostDescriptor(descriptor); // HostDescription localHost = descriptorResourceClient.getHostDescriptor("purdue.teragrid.org"); List<HostDescription> hostDescriptors = descriptorResourceClient.getHostDescriptors(); // System.out.println(localHost.getType().getHostName()); // System.out.println(localHost.getType().getHostAddress()); } }
8,651
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/DescriptorRegistryResource.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.services.registry.rest.resources; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.registry.api.AiravataRegistry2; import org.apache.airavata.registry.api.exception.RegistryException; import org.apache.airavata.registry.api.exception.gateway.DescriptorAlreadyExistsException; import org.apache.airavata.registry.api.exception.gateway.DescriptorDoesNotExistsException; import org.apache.airavata.registry.api.exception.gateway.MalformedDescriptorException; import org.apache.airavata.services.registry.rest.resourcemappings.*; import org.apache.airavata.services.registry.rest.utils.DescriptorUtil; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.apache.airavata.services.registry.rest.utils.RestServicesConstants; import javax.servlet.ServletContext; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * This class is the REST interface for all the operation regarding descriptors that are * exposed from Airavatas Registry API */ @Path(ResourcePathConstants.DecResourcePathConstants.DESC_RESOURCE_PATH) public class DescriptorRegistryResource { private AiravataRegistry2 airavataRegistry; @Context ServletContext context; /** * ---------------------------------Descriptor Registry----------------------------------* */ /** * This method will check whether the host descriptor exists * @param hostDescriptorName host descriptor name * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.HOST_DESC_EXISTS) @Produces(MediaType.TEXT_PLAIN) public Response isHostDescriptorExists(@QueryParam("hostDescriptorName") String hostDescriptorName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); boolean state; try { state = airavataRegistry.isHostDescriptorExists(hostDescriptorName); if (state) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Host Descriptor exists..."); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Host Descriptor does not exist.."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will save the host descriptor * @param host JSON message send according to HostDescriptor class * @return HTTP response */ @POST @Path(ResourcePathConstants.DecResourcePathConstants.HOST_DESC_SAVE) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response addHostDescriptor(HostDescriptor host) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { HostDescription hostDescription = DescriptorUtil.createHostDescription(host); airavataRegistry.addHostDescriptor(hostDescription); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Host descriptor saved successfully..."); return builder.build(); } catch (DescriptorAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update the host descriptor * @param host JSON message send according to HostDescriptor class * @return HTTP response */ @POST @Path(ResourcePathConstants.DecResourcePathConstants.HOST_DESC_UPDATE) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateHostDescriptor(HostDescriptor host) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { HostDescription hostDescription = DescriptorUtil.createHostDescription(host); airavataRegistry.updateHostDescriptor(hostDescription); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Host descriptor updated successfully..."); return builder.build(); } catch (DescriptorDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve host descriptor. Clients will get a JSON message that is generated * according to HostDescriptor class * @param hostName host name * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.HOST_DESC) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getHostDescriptor(@QueryParam("hostName") String hostName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { HostDescription hostDescription = airavataRegistry.getHostDescriptor(hostName); HostDescriptor hostDescriptor = DescriptorUtil.createHostDescriptor(hostDescription); if (hostDescription != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(hostDescriptor); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity("Host Descriptor does not exist..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will delete the given host descriptor * @param hostName host descriptor name * @return HTTP response */ @DELETE @Path(ResourcePathConstants.DecResourcePathConstants.HOST_DESC_DELETE) @Produces(MediaType.TEXT_PLAIN) public Response removeHostDescriptor(@QueryParam("hostName") String hostName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.removeHostDescriptor(hostName); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Host descriptor deleted successfully..."); return builder.build(); } catch (DescriptorDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve all the host descriptors available. * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.GET_HOST_DESCS) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getHostDescriptors() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<HostDescription> hostDescriptionList = airavataRegistry.getHostDescriptors(); HostDescriptionList list = new HostDescriptionList(); HostDescriptor[] hostDescriptions = new HostDescriptor[hostDescriptionList.size()]; for (int i = 0; i < hostDescriptionList.size(); i++) { HostDescriptor hostDescriptor = DescriptorUtil.createHostDescriptor(hostDescriptionList.get(i)); hostDescriptions[i] = hostDescriptor; } list.setHostDescriptions(hostDescriptions); if (hostDescriptionList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(list); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No host descriptors available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all the host descriptor names available * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.GET_HOST_DESCS_NAMES) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getHostDescriptorNames() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<HostDescription> hostDescriptionList = airavataRegistry.getHostDescriptors(); List<String> hostDescriptorNames = new ArrayList<String>(); DescriptorNameList descriptorNameList = new DescriptorNameList(); for (int i = 0; i < hostDescriptionList.size(); i++) { hostDescriptorNames.add(hostDescriptionList.get(i).getType().getHostName()); } descriptorNameList.setDescriptorNames(hostDescriptorNames); if (hostDescriptionList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(descriptorNameList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No host descriptors available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will check whether the service descriptor available * @param serviceDescriptorName service descriptor name * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.SERVICE_DESC_EXISTS) @Produces(MediaType.TEXT_PLAIN) public Response isServiceDescriptorExists(@QueryParam("serviceDescriptorName") String serviceDescriptorName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); boolean state; try { state = airavataRegistry.isServiceDescriptorExists(serviceDescriptorName); if (state) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Service descriptor does not exist..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will save the service descriptor * @param service this is a JSON message created according to ServiceDescriptor class * @return HTTP response */ @POST @Path(ResourcePathConstants.DecResourcePathConstants.SERVICE_DESC_SAVE) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response addServiceDescriptor(ServiceDescriptor service) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { ServiceDescription serviceDescription = DescriptorUtil.createServiceDescription(service); airavataRegistry.addServiceDescriptor(serviceDescription); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Service descriptor saved successfully..."); return builder.build(); } catch (DescriptorAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update the service descriptor * @param service this is a JSON message generated according to Service Descriptor class * @return HTTP response */ @POST @Path(ResourcePathConstants.DecResourcePathConstants.SERVICE_DESC_UPDATE) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateServiceDescriptor(ServiceDescriptor service) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { ServiceDescription serviceDescription = DescriptorUtil.createServiceDescription(service); airavataRegistry.updateServiceDescriptor(serviceDescription); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Service descriptor updated successfully..."); return builder.build(); } catch (DescriptorAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve service descriptor for a given service descriptor name. Clients * will get a JSON message that is generated according to Service Descriptor class * @param serviceName service name * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.SERVICE_DESC) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getServiceDescriptor(@QueryParam("serviceName") String serviceName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { ServiceDescription serviceDescription = airavataRegistry.getServiceDescriptor(serviceName); ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); if (serviceDescription != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(serviceDescriptor); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity("No service descriptor available with given service name..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will delete a given service descriptor * @param serviceName service descriptor name * @return HTTP response */ @DELETE @Path(ResourcePathConstants.DecResourcePathConstants.SERVICE_DESC_DELETE) @Produces(MediaType.TEXT_PLAIN) public Response removeServiceDescriptor(@QueryParam("serviceName") String serviceName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.removeServiceDescriptor(serviceName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Service descriptor deleted successfully..."); return builder.build(); } catch (DescriptorDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve all the service descriptors * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.GET_SERVICE_DESCS) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getServiceDescriptors() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<ServiceDescription> serviceDescriptors = airavataRegistry.getServiceDescriptors(); ServiceDescriptionList list = new ServiceDescriptionList(); ServiceDescriptor[] serviceDescriptions = new ServiceDescriptor[serviceDescriptors.size()]; for (int i = 0; i < serviceDescriptors.size(); i++) { ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescriptors.get(i)); serviceDescriptions[i] = serviceDescriptor; } list.setServiceDescriptions(serviceDescriptions); if (serviceDescriptors.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(list); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No service descriptors available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will check whether the given application descriptor exists * @param serviceName service descriptor name * @param hostName host descriptor name * @param appDescriptorName application descriptor name * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.APPL_DESC_EXIST) @Produces(MediaType.TEXT_PLAIN) public Response isApplicationDescriptorExists(@QueryParam("serviceName") String serviceName, @QueryParam("hostName") String hostName, @QueryParam("appDescName") String appDescriptorName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); boolean state; try { state = airavataRegistry.isApplicationDescriptorExists(serviceName, hostName, appDescriptorName); if (state) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Application descriptor does not exist..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will save given application descriptor * @param applicationDescriptor this is a JSON message created according to * ApplicationDescriptor class * @return HTTP response */ @POST @Path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_BUILD_SAVE) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response addApplicationDescriptor(ApplicationDescriptor applicationDescriptor) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { String hostdescName = applicationDescriptor.getHostdescName(); if (!airavataRegistry.isHostDescriptorExists(hostdescName)) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity("Given host does not exist..."); return builder.build(); } ApplicationDeploymentDescription applicationDeploymentDescription = DescriptorUtil.createApplicationDescription(applicationDescriptor); ServiceDescriptor serviceDescriptor = applicationDescriptor.getServiceDescriptor(); String serviceName; if (serviceDescriptor != null) { if (serviceDescriptor.getServiceName() == null) { serviceName = applicationDescriptor.getName(); serviceDescriptor.setServiceName(serviceName); } else { serviceName = serviceDescriptor.getServiceName(); } ServiceDescription serviceDescription = DescriptorUtil.createServiceDescription(serviceDescriptor); if (!airavataRegistry.isServiceDescriptorExists(serviceName)) { airavataRegistry.addServiceDescriptor(serviceDescription); } } else { serviceName = applicationDescriptor.getName(); } airavataRegistry.addApplicationDescriptor(serviceName, hostdescName, applicationDeploymentDescription); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Application descriptor saved successfully..."); return builder.build(); } catch (DescriptorAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update the application descriptor * @param applicationDescriptor JSON message of ApplicationDescriptor class * @return HTTP response */ @POST @Path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_UPDATE) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response udpateApplicationDescriptor(ApplicationDescriptor applicationDescriptor) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { String hostdescName = applicationDescriptor.getHostdescName(); if (!airavataRegistry.isHostDescriptorExists(hostdescName)) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity("Host does not available..."); return builder.build(); } ApplicationDeploymentDescription applicationDeploymentDescription = DescriptorUtil.createApplicationDescription(applicationDescriptor); ServiceDescriptor serviceDescriptor = applicationDescriptor.getServiceDescriptor(); String serviceName; if (serviceDescriptor != null) { if (serviceDescriptor.getServiceName() == null) { serviceName = applicationDescriptor.getName(); serviceDescriptor.setServiceName(serviceName); } else { serviceName = serviceDescriptor.getServiceName(); } ServiceDescription serviceDescription = DescriptorUtil.createServiceDescription(serviceDescriptor); if (airavataRegistry.isServiceDescriptorExists(serviceName)) { airavataRegistry.updateServiceDescriptor(serviceDescription); } else { airavataRegistry.addServiceDescriptor(serviceDescription); } } else { serviceName = applicationDescriptor.getName(); } airavataRegistry.updateApplicationDescriptor(serviceName, hostdescName, applicationDeploymentDescription); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Application descriptor updated successfully..."); return builder.build(); } catch (DescriptorAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve an application descriptor according to given service name, host name * and application name * @param serviceName service name * @param hostName host name * @param applicationName application name * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_DESCRIPTION) @Produces("text/xml") public Response getApplicationDescriptor(@QueryParam("serviceName") String serviceName, @QueryParam("hostName") String hostName, @QueryParam("applicationName") String applicationName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { ApplicationDeploymentDescription applicationDeploymentDescription = airavataRegistry.getApplicationDescriptor(serviceName, hostName, applicationName); ApplicationDescriptor applicationDescriptor = DescriptorUtil.createApplicationDescriptor(applicationDeploymentDescription); applicationDescriptor.setHostdescName(hostName); ServiceDescription serviceDescription = airavataRegistry.getServiceDescriptor(serviceName); ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); applicationDescriptor.setServiceDescriptor(serviceDescriptor); if (applicationDeploymentDescription != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(applicationDescriptor); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity("Application descriptor does not exist..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve application descriptors for a given service and host * @param serviceName service name * @param hostName host name * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_PER_HOST_SERVICE) @Produces("text/xml") public Response getApplicationDescriptorPerServiceHost(@QueryParam("serviceName") String serviceName, @QueryParam("hostName") String hostName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { ApplicationDeploymentDescription applicationDeploymentDescription = airavataRegistry.getApplicationDescriptors(serviceName, hostName); ApplicationDescriptor applicationDescriptor = DescriptorUtil.createApplicationDescriptor(applicationDeploymentDescription); applicationDescriptor.setHostdescName(hostName); ServiceDescription serviceDescription = airavataRegistry.getServiceDescriptor(serviceName); ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); applicationDescriptor.setServiceDescriptor(serviceDescriptor); if (applicationDeploymentDescription != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(applicationDescriptor); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); builder.entity("Application descriptor does not exist..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will get all the application descriptors for a given service * @param serviceName service name * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_ALL_DESCS_SERVICE) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getApplicationDescriptors(@QueryParam("serviceName") String serviceName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { Map<String, ApplicationDeploymentDescription> applicationDeploymentDescriptionMap = airavataRegistry.getApplicationDescriptors(serviceName); ApplicationDescriptorList applicationDescriptorList = new ApplicationDescriptorList(); ApplicationDescriptor[] applicationDescriptors = new ApplicationDescriptor[applicationDeploymentDescriptionMap.size()]; int i = 0; for (String hostName : applicationDeploymentDescriptionMap.keySet()) { ApplicationDeploymentDescription applicationDeploymentDescription = applicationDeploymentDescriptionMap.get(hostName); ApplicationDescriptor applicationDescriptor = DescriptorUtil.createApplicationDescriptor(applicationDeploymentDescription); applicationDescriptor.setHostdescName(hostName); ServiceDescription serviceDescription = airavataRegistry.getServiceDescriptor(serviceName); ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); applicationDescriptor.setServiceDescriptor(serviceDescriptor); applicationDescriptors[i] = applicationDescriptor; i++; } applicationDescriptorList.setApplicationDescriptors(applicationDescriptors); if (applicationDeploymentDescriptionMap.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(applicationDescriptorList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Application descriptor does not exist..."); return builder.build(); } } catch (MalformedDescriptorException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve all the application descriptors available * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_ALL_DESCRIPTORS) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getApplicationDescriptors() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { Map<String[], ApplicationDeploymentDescription> applicationDeploymentDescriptionMap = airavataRegistry.getApplicationDescriptors(); ApplicationDescriptorList applicationDescriptorList = new ApplicationDescriptorList(); ApplicationDescriptor[] applicationDescriptors = new ApplicationDescriptor[applicationDeploymentDescriptionMap.size()]; int i = 0; for (String[] descriptors : applicationDeploymentDescriptionMap.keySet()) { ApplicationDeploymentDescription applicationDeploymentDescription = applicationDeploymentDescriptionMap.get(descriptors); ApplicationDescriptor applicationDescriptor = DescriptorUtil.createApplicationDescriptor(applicationDeploymentDescription); applicationDescriptor.setHostdescName(descriptors[1]); ServiceDescription serviceDescription = airavataRegistry.getServiceDescriptor(descriptors[0]); if (serviceDescription == null) { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); applicationDescriptor.setServiceDescriptor(serviceDescriptor); applicationDescriptors[i] = applicationDescriptor; i++; } applicationDescriptorList.setApplicationDescriptors(applicationDescriptors); if (applicationDeploymentDescriptionMap.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(applicationDescriptorList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No application descriptors available..."); return builder.build(); } } catch (MalformedDescriptorException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all the application names available * @return HTTP response */ @GET @Path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_NAMES) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getApplicationDescriptorNames() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { Map<String[], ApplicationDeploymentDescription> applicationDeploymentDescriptionMap = airavataRegistry.getApplicationDescriptors(); DescriptorNameList descriptorNameList = new DescriptorNameList(); List<String> appDesNames = new ArrayList<String>(); for (String[] descriptors : applicationDeploymentDescriptionMap.keySet()) { ApplicationDeploymentDescription applicationDeploymentDescription = applicationDeploymentDescriptionMap.get(descriptors); appDesNames.add(applicationDeploymentDescription.getType().getApplicationName().getStringValue()); } descriptorNameList.setDescriptorNames(appDesNames); if (applicationDeploymentDescriptionMap.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(descriptorNameList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No application descriptors available..."); return builder.build(); } } catch (MalformedDescriptorException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method wil remove an application descriptor according to given service name, host name * and application name * @param serviceName service name * @param hostName host name * @param appName application name * @return HTTP response */ @DELETE @Path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_DELETE) @Produces(MediaType.TEXT_PLAIN) public Response removeApplicationDescriptor(@QueryParam("serviceName") String serviceName, @QueryParam("hostName") String hostName, @QueryParam("appName") String appName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.removeApplicationDescriptor(serviceName, hostName, appName); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Application descriptor deleted successfully..."); return builder.build(); } catch (DescriptorDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } }
8,652
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/ConfigurationRegistryResource.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.services.registry.rest.resources; import org.apache.airavata.registry.api.AiravataRegistry2; import org.apache.airavata.services.registry.rest.resourcemappings.ConfigurationList; import org.apache.airavata.services.registry.rest.resourcemappings.URLList; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.apache.airavata.services.registry.rest.utils.RestServicesConstants; import javax.servlet.ServletContext; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.net.URI; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * This class is a REST interface to all the methods related to Configuration which are exposed by * Airavata Registry API */ @Path(ResourcePathConstants.ConfigResourcePathConstants.CONFIGURATION_REGISTRY_RESOURCE) public class ConfigurationRegistryResource { private AiravataRegistry2 airavataRegistry; @Context ServletContext context; /** * ---------------------------------Configuration Registry----------------------------------* */ /** * This method will return the configuration value corrosponding to given config key * @param key configuration key * @return HTTP Response */ @Path(ResourcePathConstants.ConfigResourcePathConstants.GET_CONFIGURATION) @GET @Produces(MediaType.TEXT_PLAIN) public Response getConfiguration(@QueryParam("key") String key) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { Object configuration = airavataRegistry.getConfiguration(key); if (configuration != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(configuration); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Configuration does not exist..."); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return configuration list for given configuration key * @param key configuration key * @return HTTP response */ @GET @Path(ResourcePathConstants.ConfigResourcePathConstants.GET_CONFIGURATION_LIST) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getConfigurationList(@QueryParam("key") String key) { try { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); List<Object> configurationList = airavataRegistry.getConfigurationList(key); ConfigurationList list = new ConfigurationList(); Object[] configValList = new Object[configurationList.size()]; for (int i = 0; i < configurationList.size(); i++) { configValList[i] = configurationList.get(i); } list.setConfigValList(configValList); if (configurationList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(list); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No configuration available with given config key..."); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will add a configuration with given config key, config value and expiration date * @param key configuration key * @param value configuration value * @param date configuration expire data * @return HTTP response */ @POST @Path(ResourcePathConstants.ConfigResourcePathConstants.SAVE_CONFIGURATION) @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response setConfiguration(@FormParam("key") String key, @FormParam("value") String value, @FormParam("date") String date) { try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(date); airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); airavataRegistry.setConfiguration(key, value, formattedDate); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Configuration saved successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update the configuration according to the given config value and expire * date * @param key config key * @param value config value * @param date expiration date * @return HTTP response */ @POST @Path(ResourcePathConstants.ConfigResourcePathConstants.UPDATE_CONFIGURATION) @Produces(MediaType.TEXT_PLAIN) public Response addConfiguration(@FormParam("key") String key, @FormParam("value") String value, @FormParam("date") String date) { try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(date); airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); airavataRegistry.addConfiguration(key, value, formattedDate); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Configuration updated successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will delete all configuration of the given config key * @param key configuration key * @return HTTP response */ @DELETE @Path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_ALL_CONFIGURATION) @Produces(MediaType.TEXT_PLAIN) public Response removeAllConfiguration(@QueryParam("key") String key) { try { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); airavataRegistry.removeAllConfiguration(key); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("All configurations with given config key removed successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will delete the configuration with the given config key and config value * @param key configuration key * @param value configuration value * @return HTTP response */ @DELETE @Path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_CONFIGURATION) @Produces(MediaType.TEXT_PLAIN) public Response removeConfiguration(@QueryParam("key") String key, @QueryParam("value") String value) { try { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); airavataRegistry.removeConfiguration(key, value); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Configuration removed successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve all the GFac URIs * @return HTTP response */ @GET @Path(ResourcePathConstants.ConfigResourcePathConstants.GET_GFAC_URI_LIST) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getGFacURIs() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<URI> uris = airavataRegistry.getGFacURIs(); URLList list = new URLList(); String[] urs = new String[uris.size()]; for (int i = 0; i < uris.size(); i++) { urs[i] = uris.get(i).toString(); } list.setUris(urs); if (urs.length != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(list); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No GFac URIs available..."); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve all the workflow interpreter URIs * @return HTTP response */ @GET @Path(ResourcePathConstants.ConfigResourcePathConstants.GET_WFINTERPRETER_URI_LIST) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getWorkflowInterpreterURIs() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<URI> uris = airavataRegistry.getWorkflowInterpreterURIs(); URLList list = new URLList(); String[] urs = new String[uris.size()]; for (int i = 0; i < uris.size(); i++) { urs[i] = uris.get(i).toString(); } list.setUris(urs); if (urs.length != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(list); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No Workflow Interpreter URIs available..."); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve eventing URI * @return HTTP response */ @GET @Path(ResourcePathConstants.ConfigResourcePathConstants.GET_EVENTING_URI) @Produces(MediaType.TEXT_PLAIN) public Response getEventingServiceURI() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI eventingServiceURI = airavataRegistry.getEventingServiceURI(); if (eventingServiceURI != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(eventingServiceURI.toString()); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No eventing URI available..."); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve messagebox URI * @return HTTP response */ @GET @Path(ResourcePathConstants.ConfigResourcePathConstants.GET_MESSAGE_BOX_URI) @Produces(MediaType.TEXT_PLAIN) public Response getMessageBoxURI() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI eventingServiceURI = airavataRegistry.getMessageBoxURI(); if (eventingServiceURI != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(eventingServiceURI.toString()); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No message box URI available..."); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will add new GFac URI * @param uri gfac URI * @return HTTP response */ @POST @Path(ResourcePathConstants.ConfigResourcePathConstants.ADD_GFAC_URI) @Produces(MediaType.TEXT_PLAIN) public Response addGFacURI(@FormParam("uri") String uri) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI gfacURI = new URI(uri); airavataRegistry.addGFacURI(gfacURI); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("GFac URI added successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will add new workflow interpreter URI * @param uri workflow interpreter URI * @return HTTP response */ @POST @Path(ResourcePathConstants.ConfigResourcePathConstants.ADD_WFINTERPRETER_URI) @Produces(MediaType.TEXT_PLAIN) public Response addWorkflowInterpreterURI(@FormParam("uri") String uri) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI interpreterURI = new URI(uri); airavataRegistry.addWorkflowInterpreterURI(interpreterURI); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow interpreter URI added successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will set a new eventing URI * @param uri eventing URI * @return HTTP response */ @POST @Path(ResourcePathConstants.ConfigResourcePathConstants.ADD_EVENTING_URI) @Produces(MediaType.TEXT_PLAIN) public Response setEventingURI(@FormParam("uri") String uri) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI eventingURI = new URI(uri); airavataRegistry.setEventingURI(eventingURI); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Eventing URI set successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will set message box URI * @param uri message box URI * @return HTTP response */ @POST @Path(ResourcePathConstants.ConfigResourcePathConstants.ADD_MESSAGE_BOX_URI) @Produces(MediaType.TEXT_PLAIN) public Response setMessageBoxURI(@FormParam("uri") String uri) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI msgBoxURI = new URI(uri); airavataRegistry.setMessageBoxURI(msgBoxURI); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("MessageBox URI set successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update GFac URI expiring date * @param uri GFac URI * @param date Expiration date * @return HTTP response */ @POST @Path(ResourcePathConstants.ConfigResourcePathConstants.ADD_GFAC_URI_DATE) @Produces(MediaType.TEXT_PLAIN) public Response addGFacURIByDate(@FormParam("uri") String uri, @FormParam("date") String date) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(date); URI gfacURI = new URI(uri); airavataRegistry.addGFacURI(gfacURI, formattedDate); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("GFac URI added successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update workflow interpreter URI expiration date * @param uri workflow interpreter URI * @param date workflow interpreter expiration date * @return HTTP response */ @POST @Path(ResourcePathConstants.ConfigResourcePathConstants.ADD_WFINTERPRETER_URI_DATE) @Produces(MediaType.TEXT_PLAIN) public Response addWorkflowInterpreterURI(@FormParam("uri") String uri, @FormParam("date") String date) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(date); URI interpreterURI = new URI(uri); airavataRegistry.addWorkflowInterpreterURI(interpreterURI, formattedDate); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow interpreter URI added successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update Eventing URI expiration date * @param uri eventing URI * @param date eventing URI expiration date * @return HTTP response */ @POST @Path(ResourcePathConstants.ConfigResourcePathConstants.ADD_EVENTING_URI_DATE) @Produces(MediaType.TEXT_PLAIN) public Response setEventingURIByDate(@FormParam("uri") String uri, @FormParam("date") String date) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(date); URI eventingURI = new URI(uri); airavataRegistry.setEventingURI(eventingURI, formattedDate); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Eventing URI added successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update expiration date of Message box URI * @param uri message box URI * @param date message box expiration date * @return HTTP response */ @POST @Path(ResourcePathConstants.ConfigResourcePathConstants.ADD_MSG_BOX_URI_DATE) @Produces(MediaType.TEXT_PLAIN) public Response setMessageBoxURIByDate(@FormParam("uri") String uri, @FormParam("date") String date) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(date); URI msgBoxURI = new URI(uri); airavataRegistry.setMessageBoxURI(msgBoxURI, formattedDate); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Message box URI retrieved successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will remove GFac URI * @param uri GFac URI * @return HTTP response */ @DELETE @Path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_GFAC_URI) @Produces(MediaType.TEXT_PLAIN) public Response removeGFacURI(@QueryParam("uri") String uri) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI gfacURI = new URI(uri); airavataRegistry.removeGFacURI(gfacURI); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("GFac URI deleted successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will remove all the GFac URIs * @return HTTP response */ @DELETE @Path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_ALL_GFAC_URIS) @Produces(MediaType.TEXT_PLAIN) public Response removeAllGFacURI() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.removeAllGFacURI(); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("All GFac URIs deleted successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will remove workflow interpreter URI * @param uri workflow interpreter URI * @return HTTP response */ @DELETE @Path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_WFINTERPRETER_URI) @Produces(MediaType.TEXT_PLAIN) public Response removeWorkflowInterpreterURI(@QueryParam("uri") String uri) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI intURI = new URI(uri); airavataRegistry.removeWorkflowInterpreterURI(intURI); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow Interpreter URI deleted successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will remove all the workflow interpreter URIs * @return HTTP response */ @DELETE @Path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_ALL_WFINTERPRETER_URIS) @Produces(MediaType.TEXT_PLAIN) public Response removeAllWorkflowInterpreterURI() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.removeAllWorkflowInterpreterURI(); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("All workflow interpreter URIs deleted successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will remove eventing URI * @return HTTP response */ @DELETE @Path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_EVENTING_URI) @Produces(MediaType.TEXT_PLAIN) public Response unsetEventingURI() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.unsetEventingURI(); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Eventing URI deleted successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will remove message box URI * @return HTTP response */ @DELETE @Path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_MSG_BOX_URI) @Produces(MediaType.TEXT_PLAIN) public Response unsetMessageBoxURI() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.unsetMessageBoxURI(); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("MessageBox URI deleted successfully..."); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } }
8,653
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/RegistryResource.java
package org.apache.airavata.services.registry.rest.resources; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.registry.api.*; import org.apache.airavata.registry.api.exception.RegistryException; import org.apache.airavata.registry.api.exception.gateway.*; import org.apache.airavata.registry.api.exception.worker.*; import org.apache.airavata.registry.api.impl.ExperimentDataImpl; import org.apache.airavata.registry.api.workflow.*; import org.apache.airavata.services.registry.rest.resourcemappings.*; import org.apache.airavata.services.registry.rest.utils.DescriptorUtil; import org.apache.airavata.services.registry.rest.utils.RestServicesConstants; import javax.servlet.ServletContext; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.net.URI; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; /** * RegistryResource for REST interface of Registry API * */ @Path("/registry/api") //public class RegistryResource implements ConfigurationRegistryService, // ProjectsRegistryService, ProvenanceRegistryService, UserWorkflowRegistryService, // PublishedWorkflowRegistryService, DescriptorRegistryService{ public class RegistryResource { private AiravataRegistry2 airavataRegistry; @Context ServletContext context; public String getVersion() { return null; } /** * ---------------------------------Configuration Registry----------------------------------* */ @Path("/configuration") @GET @Produces(MediaType.TEXT_PLAIN) public Response getConfiguration(@QueryParam("key") String key) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { Object configuration = airavataRegistry.getConfiguration(key); if (configuration != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(configuration); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("/configurationlist") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getConfigurationList(@QueryParam("key") String key) { try { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); List<Object> configurationList = airavataRegistry.getConfigurationList(key); ConfigurationList list = new ConfigurationList(); Object[] configValList = new Object[configurationList.size()]; for (int i = 0; i < configurationList.size(); i++) { configValList[i] = configurationList.get(i); } list.setConfigValList(configValList); if (configurationList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(list); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("save/configuration") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response setConfiguration(@FormParam("key") String key, @FormParam("value") String value, @FormParam("date") String date) { try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(date); airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); airavataRegistry.setConfiguration(key, value, formattedDate); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("update/configuration") @Produces(MediaType.TEXT_PLAIN) public Response addConfiguration(@FormParam("key") String key, @FormParam("value") String value, @FormParam("date") String date) { try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(date); airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); airavataRegistry.addConfiguration(key, value, formattedDate); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("delete/allconfiguration") @Produces(MediaType.TEXT_PLAIN) public Response removeAllConfiguration(@QueryParam("key") String key) { try { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); airavataRegistry.removeAllConfiguration(key); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("delete/configuration") @Produces(MediaType.TEXT_PLAIN) public Response removeConfiguration(@QueryParam("key") String key, @QueryParam("value") String value) { try { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); airavataRegistry.removeConfiguration(key, value); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("gfac/urilist") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getGFacURIs() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<URI> uris = airavataRegistry.getGFacURIs(); URLList list = new URLList(); String[] urs = new String[uris.size()]; for (int i = 0; i < uris.size(); i++) { urs[i] = uris.get(i).toString(); } list.setUris(urs); if (urs.length != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(list); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("workflowinterpreter/urilist") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getWorkflowInterpreterURIs() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<URI> uris = airavataRegistry.getWorkflowInterpreterURIs(); URLList list = new URLList(); String[] urs = new String[uris.size()]; for (int i = 0; i < uris.size(); i++) { urs[i] = uris.get(i).toString(); } list.setUris(urs); if (urs.length != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(list); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("eventingservice/uri") @Produces(MediaType.TEXT_PLAIN) public Response getEventingServiceURI() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI eventingServiceURI = airavataRegistry.getEventingServiceURI(); if (eventingServiceURI != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(eventingServiceURI.toString()); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("messagebox/uri") @Produces(MediaType.TEXT_PLAIN) public Response getMessageBoxURI() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI eventingServiceURI = airavataRegistry.getMessageBoxURI(); if (eventingServiceURI != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(eventingServiceURI.toString()); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("add/gfacuri") @Produces(MediaType.TEXT_PLAIN) public Response addGFacURI(@FormParam("uri") String uri) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI gfacURI = new URI(uri); airavataRegistry.addGFacURI(gfacURI); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("add/workflowinterpreteruri") @Produces(MediaType.TEXT_PLAIN) public Response addWorkflowInterpreterURI(@FormParam("uri") String uri) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI interpreterURI = new URI(uri); airavataRegistry.addWorkflowInterpreterURI(interpreterURI); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("add/eventinguri") @Produces(MediaType.TEXT_PLAIN) public Response setEventingURI(@FormParam("uri") String uri) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI eventingURI = new URI(uri); airavataRegistry.setEventingURI(eventingURI); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("add/msgboxuri") @Produces(MediaType.TEXT_PLAIN) public Response setMessageBoxURI(@FormParam("uri") String uri) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI msgBoxURI = new URI(uri); airavataRegistry.setMessageBoxURI(msgBoxURI); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("add/gfacuri/date") @Produces(MediaType.TEXT_PLAIN) public Response addGFacURIByDate(@FormParam("uri") String uri, @FormParam("date") String date) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(date); URI gfacURI = new URI(uri); airavataRegistry.addGFacURI(gfacURI, formattedDate); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("add/workflowinterpreteruri/date") @Produces(MediaType.TEXT_PLAIN) public Response addWorkflowInterpreterURI(@FormParam("uri") String uri, @FormParam("date") String date) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(date); URI interpreterURI = new URI(uri); airavataRegistry.addWorkflowInterpreterURI(interpreterURI, formattedDate); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("add/eventinguri/date") @Produces(MediaType.TEXT_PLAIN) public Response setEventingURIByDate(@FormParam("uri") String uri, @FormParam("date") String date) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(date); URI eventingURI = new URI(uri); airavataRegistry.setEventingURI(eventingURI, formattedDate); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("add/msgboxuri/date") @Produces(MediaType.TEXT_PLAIN) public Response setMessageBoxURIByDate(@FormParam("uri") String uri, @FormParam("date") String date) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(date); URI msgBoxURI = new URI(uri); airavataRegistry.setMessageBoxURI(msgBoxURI, formattedDate); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("delete/gfacuri") @Produces(MediaType.TEXT_PLAIN) public Response removeGFacURI(@QueryParam("uri") String uri) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI gfacURI = new URI(uri); airavataRegistry.removeGFacURI(gfacURI); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("delete/allgfacuris") @Produces(MediaType.TEXT_PLAIN) public Response removeAllGFacURI() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.removeAllGFacURI(); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("delete/workflowinterpreteruri") @Produces(MediaType.TEXT_PLAIN) public Response removeWorkflowInterpreterURI(@QueryParam("uri") String uri) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { URI intURI = new URI(uri); airavataRegistry.removeWorkflowInterpreterURI(intURI); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("delete/allworkflowinterpreteruris") @Produces(MediaType.TEXT_PLAIN) public Response removeAllWorkflowInterpreterURI() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.removeAllWorkflowInterpreterURI(); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("delete/eventinguri") @Produces(MediaType.TEXT_PLAIN) public Response unsetEventingURI() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.unsetEventingURI(); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("delete/msgboxuri") @Produces(MediaType.TEXT_PLAIN) public Response unsetMessageBoxURI() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.unsetMessageBoxURI(); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (Exception e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } /** * ---------------------------------Descriptor Registry----------------------------------* */ @GET @Path("hostdescriptor/exist") @Produces(MediaType.TEXT_PLAIN) public Response isHostDescriptorExists(@QueryParam("descriptorName") String descriptorName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); boolean state; try { state = airavataRegistry.isHostDescriptorExists(descriptorName); if (state) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("hostdescriptor/save/test") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response addHostDescriptor(@FormParam("hostName") String hostName, @FormParam("hostAddress") String hostAddress, @FormParam("hostEndpoint") String hostEndpoint, @FormParam("gatekeeperEndpoint") String gatekeeperEndpoint) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { HostDescription hostDescription = DescriptorUtil.createHostDescription(hostName, hostAddress, hostEndpoint, gatekeeperEndpoint); airavataRegistry.addHostDescriptor(hostDescription); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (DescriptorAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); // TODO : Use WEbapplicationExcpetion return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("hostdescriptor/save") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response addJSONHostDescriptor(HostDescriptor host) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { HostDescription hostDescription = DescriptorUtil.createHostDescription(host); airavataRegistry.addHostDescriptor(hostDescription); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (DescriptorAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("hostdescriptor/update") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateHostDescriptor(HostDescriptor host) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { HostDescription hostDescription = DescriptorUtil.createHostDescription(host); airavataRegistry.updateHostDescriptor(hostDescription); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (DescriptorDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("host/description") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getHostDescriptor(@QueryParam("hostName") String hostName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { HostDescription hostDescription = airavataRegistry.getHostDescriptor(hostName); HostDescriptor hostDescriptor = DescriptorUtil.createHostDescriptor(hostDescription); if (hostDescription != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(hostDescriptor); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("hostdescriptor/delete") @Produces(MediaType.TEXT_PLAIN) public Response removeHostDescriptor(@QueryParam("hostName") String hostName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.removeHostDescriptor(hostName); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (DescriptorDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/hostdescriptors") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getHostDescriptors() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<HostDescription> hostDescriptionList = airavataRegistry.getHostDescriptors(); HostDescriptionList list = new HostDescriptionList(); HostDescriptor[] hostDescriptions = new HostDescriptor[hostDescriptionList.size()]; for (int i = 0; i < hostDescriptionList.size(); i++) { HostDescriptor hostDescriptor = DescriptorUtil.createHostDescriptor(hostDescriptionList.get(i)); hostDescriptions[i] = hostDescriptor; } list.setHostDescriptions(hostDescriptions); if (hostDescriptionList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(list); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("servicedescriptor/exist") @Produces(MediaType.TEXT_PLAIN) public Response isServiceDescriptorExists(@QueryParam("descriptorName") String descriptorName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); boolean state; try { state = airavataRegistry.isServiceDescriptorExists(descriptorName); if (state) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("servicedescriptor/save") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response addJSONServiceDescriptor(ServiceDescriptor service) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { ServiceDescription serviceDescription = DescriptorUtil.createServiceDescription(service); airavataRegistry.addServiceDescriptor(serviceDescription); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (DescriptorAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("servicedescriptor/update") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response updateServiceDescriptor(ServiceDescriptor service) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { ServiceDescription serviceDescription = DescriptorUtil.createServiceDescription(service); airavataRegistry.updateServiceDescriptor(serviceDescription); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (DescriptorAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("servicedescriptor/description") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getServiceDescriptor(@QueryParam("serviceName") String serviceName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { ServiceDescription serviceDescription = airavataRegistry.getServiceDescriptor(serviceName); ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); if (serviceDescription != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(serviceDescriptor); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("servicedescriptor/delete") @Produces(MediaType.TEXT_PLAIN) public Response removeServiceDescriptor(@QueryParam("serviceName") String serviceName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.removeServiceDescriptor(serviceName); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (DescriptorDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/servicedescriptors") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getServiceDescriptors() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<ServiceDescription> serviceDescriptors = airavataRegistry.getServiceDescriptors(); ServiceDescriptionList list = new ServiceDescriptionList(); ServiceDescriptor[] serviceDescriptions = new ServiceDescriptor[serviceDescriptors.size()]; for (int i = 0; i < serviceDescriptors.size(); i++) { ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescriptors.get(i)); serviceDescriptions[i] = serviceDescriptor; } list.setServiceDescriptions(serviceDescriptions); if (serviceDescriptors.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(list); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("applicationdescriptor/exist") @Produces(MediaType.TEXT_PLAIN) public Response isApplicationDescriptorExists(@QueryParam("serviceName") String serviceName, @QueryParam("hostName") String hostName, @QueryParam("descriptorName") String descriptorName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); boolean state; try { state = airavataRegistry.isApplicationDescriptorExists(serviceName, hostName, descriptorName); if (state) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("applicationdescriptor/build/save/test") @Produces(MediaType.TEXT_PLAIN) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response addApplicationDescriptorTest(@FormParam("appName") String appName, @FormParam("exeuctableLocation") String exeuctableLocation, @FormParam("scratchWorkingDirectory") String scratchWorkingDirectory, @FormParam("hostName") String hostName, @FormParam("projAccNumber") String projAccNumber, @FormParam("queueName") String queueName, @FormParam("cpuCount") String cpuCount, @FormParam("nodeCount") String nodeCount, @FormParam("maxMemory") String maxMemory, @FormParam("serviceName") String serviceName, @FormParam("inputName1") String inputName1, @FormParam("inputType1") String inputType1, @FormParam("outputName") String outputName, @FormParam("outputType") String outputType) throws Exception { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); System.out.println("application descriptor save started ..."); ServiceDescription serv = DescriptorUtil.getServiceDescription(serviceName, inputName1, inputType1, outputName, outputType); // Creating the descriptor as a temporary measure. ApplicationDeploymentDescription app = DescriptorUtil.registerApplication(appName, exeuctableLocation, scratchWorkingDirectory, hostName, projAccNumber, queueName, cpuCount, nodeCount, maxMemory); try { if (!airavataRegistry.isHostDescriptorExists(hostName)) { System.out.println(hostName + " host not exist"); // Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); // return builder.build(); } if (airavataRegistry.isServiceDescriptorExists(serv.getType().getName())) { System.out.println(serviceName + " service updated "); airavataRegistry.updateServiceDescriptor(serv); } else { System.out.println(serviceName + " service created "); airavataRegistry.addServiceDescriptor(serv); } if (airavataRegistry.isApplicationDescriptorExists(serv.getType().getName(), hostName, app.getType().getApplicationName().getStringValue())) { System.out.println(appName + " app already exists. retruning an error"); // Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); // return builder.build(); } else { System.out.println(appName + " adding the app"); airavataRegistry.addApplicationDescriptor(serv.getType().getName(), hostName, app); } // airavataRegistry.addApplicationDescriptor(serviceName, hostName, app); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (DescriptorAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("applicationdescriptor/build/save") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response addJSONApplicationDescriptor(ApplicationDescriptor applicationDescriptor) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { String hostdescName = applicationDescriptor.getHostdescName(); if (!airavataRegistry.isHostDescriptorExists(hostdescName)) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } ApplicationDeploymentDescription applicationDeploymentDescription = DescriptorUtil.createApplicationDescription(applicationDescriptor); ServiceDescriptor serviceDescriptor = applicationDescriptor.getServiceDescriptor(); String serviceName; if (serviceDescriptor != null) { if (serviceDescriptor.getServiceName() == null) { serviceName = applicationDescriptor.getName(); serviceDescriptor.setServiceName(serviceName); } else { serviceName = serviceDescriptor.getServiceName(); } ServiceDescription serviceDescription = DescriptorUtil.createServiceDescription(serviceDescriptor); if (!airavataRegistry.isServiceDescriptorExists(serviceName)) { airavataRegistry.addServiceDescriptor(serviceDescription); } } else { serviceName = applicationDescriptor.getName(); } airavataRegistry.addApplicationDescriptor(serviceName, hostdescName, applicationDeploymentDescription); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (DescriptorAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } // // @POST // @Path("applicationdescriptor/save") // @Consumes(MediaType.TEXT_XML) // @Produces(MediaType.TEXT_PLAIN) // public Response addApplicationDesc(@FormParam("serviceName") String serviceName, // @FormParam("hostName") String hostName, // String application) { // airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); // try{ // ApplicationDeploymentDescription applicationDeploymentDescription = ApplicationDeploymentDescription.fromXML(application); // airavataRegistry.addApplicationDescriptor(serviceName, hostName, applicationDeploymentDescription); // Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); // return builder.build(); // } catch (DescriptorAlreadyExistsException e){ // Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); // return builder.build(); // } catch (XmlException e) { // Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); // return builder.build(); // } catch (RegistryException e) { // Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); // return builder.build(); // } // // } @POST @Path("applicationdescriptor/update") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response udpateApplicationDescriptorByDescriptors(ApplicationDescriptor applicationDescriptor) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { String hostdescName = applicationDescriptor.getHostdescName(); if (!airavataRegistry.isHostDescriptorExists(hostdescName)) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } ApplicationDeploymentDescription applicationDeploymentDescription = DescriptorUtil.createApplicationDescription(applicationDescriptor); ServiceDescriptor serviceDescriptor = applicationDescriptor.getServiceDescriptor(); String serviceName; if (serviceDescriptor != null) { if (serviceDescriptor.getServiceName() == null) { serviceName = applicationDescriptor.getName(); serviceDescriptor.setServiceName(serviceName); } else { serviceName = serviceDescriptor.getServiceName(); } ServiceDescription serviceDescription = DescriptorUtil.createServiceDescription(serviceDescriptor); if (airavataRegistry.isServiceDescriptorExists(serviceName)) { airavataRegistry.updateServiceDescriptor(serviceDescription); } else { airavataRegistry.addServiceDescriptor(serviceDescription); } } else { serviceName = applicationDescriptor.getName(); } airavataRegistry.updateApplicationDescriptor(serviceName, hostdescName, applicationDeploymentDescription); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (DescriptorAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("applicationdescriptor/description") @Produces("text/xml") public Response getApplicationDescriptor(@QueryParam("serviceName") String serviceName, @QueryParam("hostName") String hostName, @QueryParam("applicationName") String applicationName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { ApplicationDeploymentDescription applicationDeploymentDescription = airavataRegistry.getApplicationDescriptor(serviceName, hostName, applicationName); ApplicationDescriptor applicationDescriptor = DescriptorUtil.createApplicationDescriptor(applicationDeploymentDescription); applicationDescriptor.setHostdescName(hostName); ServiceDescription serviceDescription = airavataRegistry.getServiceDescriptor(serviceName); ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); applicationDescriptor.setServiceDescriptor(serviceDescriptor); if (applicationDeploymentDescription != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(applicationDescriptor); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("applicationdescriptors/alldescriptors/host/service") @Produces("text/xml") public Response getApplicationDescriptors(@QueryParam("serviceName") String serviceName, @QueryParam("hostName") String hostName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { ApplicationDeploymentDescription applicationDeploymentDescription = airavataRegistry.getApplicationDescriptors(serviceName, hostName); ApplicationDescriptor applicationDescriptor = DescriptorUtil.createApplicationDescriptor(applicationDeploymentDescription); applicationDescriptor.setHostdescName(hostName); ServiceDescription serviceDescription = airavataRegistry.getServiceDescriptor(serviceName); ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); applicationDescriptor.setServiceDescriptor(serviceDescriptor); if (applicationDeploymentDescription != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(applicationDescriptor); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("applicationdescriptor/alldescriptors/service") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getApplicationDescriptors(@QueryParam("serviceName") String serviceName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { Map<String, ApplicationDeploymentDescription> applicationDeploymentDescriptionMap = airavataRegistry.getApplicationDescriptors(serviceName); ApplicationDescriptorList applicationDescriptorList = new ApplicationDescriptorList(); ApplicationDescriptor[] applicationDescriptors = new ApplicationDescriptor[applicationDeploymentDescriptionMap.size()]; int i = 0; for (String hostName : applicationDeploymentDescriptionMap.keySet()) { ApplicationDeploymentDescription applicationDeploymentDescription = applicationDeploymentDescriptionMap.get(hostName); ApplicationDescriptor applicationDescriptor = DescriptorUtil.createApplicationDescriptor(applicationDeploymentDescription); applicationDescriptor.setHostdescName(hostName); ServiceDescription serviceDescription = airavataRegistry.getServiceDescriptor(serviceName); ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); applicationDescriptor.setServiceDescriptor(serviceDescriptor); applicationDescriptors[i] = applicationDescriptor; i++; } applicationDescriptorList.setApplicationDescriptors(applicationDescriptors); if (applicationDeploymentDescriptionMap.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(applicationDescriptorList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (MalformedDescriptorException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("applicationdescriptor/alldescriptors") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getApplicationDescriptors() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { Map<String[], ApplicationDeploymentDescription> applicationDeploymentDescriptionMap = airavataRegistry.getApplicationDescriptors(); ApplicationDescriptorList applicationDescriptorList = new ApplicationDescriptorList(); ApplicationDescriptor[] applicationDescriptors = new ApplicationDescriptor[applicationDeploymentDescriptionMap.size()]; int i = 0; for (String[] descriptors : applicationDeploymentDescriptionMap.keySet()) { ApplicationDeploymentDescription applicationDeploymentDescription = applicationDeploymentDescriptionMap.get(descriptors); ApplicationDescriptor applicationDescriptor = DescriptorUtil.createApplicationDescriptor(applicationDeploymentDescription); applicationDescriptor.setHostdescName(descriptors[1]); ServiceDescription serviceDescription = airavataRegistry.getServiceDescriptor(descriptors[0]); if (serviceDescription == null) { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); applicationDescriptor.setServiceDescriptor(serviceDescriptor); applicationDescriptors[i] = applicationDescriptor; i++; } applicationDescriptorList.setApplicationDescriptors(applicationDescriptors); if (applicationDeploymentDescriptionMap.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(applicationDescriptorList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (MalformedDescriptorException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("applicationdescriptor/delete") @Produces(MediaType.TEXT_PLAIN) public Response removeApplicationDescriptor(@QueryParam("serviceName") String serviceName, @QueryParam("hostName") String hostName, @QueryParam("appName") String appName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.removeApplicationDescriptor(serviceName, hostName, appName); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (DescriptorDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } /** * ---------------------------------Project Registry----------------------------------* */ @GET @Path("project/exist") @Produces(MediaType.TEXT_PLAIN) public Response isWorkspaceProjectExists(@QueryParam("projectName") String projectName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { boolean result = airavataRegistry.isWorkspaceProjectExists(projectName); if (result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity("False"); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("project/exist") @Produces(MediaType.TEXT_PLAIN) public Response isWorkspaceProjectExists(@FormParam("projectName") String projectName, @FormParam("createIfNotExists") String createIfNotExists) { boolean createIfNotExistStatus = false; if (createIfNotExists.equals("true")) { createIfNotExistStatus = true; } airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { boolean result = airavataRegistry.isWorkspaceProjectExists(projectName, createIfNotExistStatus); if (result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity("False"); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity("False"); return builder.build(); } } @POST @Path("add/project") @Produces(MediaType.TEXT_PLAIN) public Response addWorkspaceProject(@FormParam("projectName") String projectName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkspaceProject workspaceProject = new WorkspaceProject(projectName, airavataRegistry); airavataRegistry.addWorkspaceProject(workspaceProject); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (WorkspaceProjectAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("update/project") @Produces(MediaType.TEXT_PLAIN) public Response updateWorkspaceProject(@FormParam("projectName") String projectName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkspaceProject workspaceProject = new WorkspaceProject(projectName, airavataRegistry); airavataRegistry.updateWorkspaceProject(workspaceProject); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (WorkspaceProjectDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @DELETE @Path("delete/project") @Produces(MediaType.TEXT_PLAIN) public Response deleteWorkspaceProject(@QueryParam("projectName") String projectName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.deleteWorkspaceProject(projectName); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (WorkspaceProjectDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/project") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getWorkspaceProject(@QueryParam("projectName") String projectName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkspaceProject workspaceProject = airavataRegistry.getWorkspaceProject(projectName); if (workspaceProject != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workspaceProject); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } catch (WorkspaceProjectDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/projects") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getWorkspaceProjects() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<WorkspaceProject> workspaceProjects = airavataRegistry.getWorkspaceProjects(); WorkspaceProjectList workspaceProjectList = new WorkspaceProjectList(); WorkspaceProject[] workspaceProjectSet = new WorkspaceProject[workspaceProjects.size()]; for (int i = 0; i < workspaceProjects.size(); i++) { workspaceProjectSet[i] = workspaceProjects.get(i); } workspaceProjectList.setWorkspaceProjects(workspaceProjectSet); if (workspaceProjects.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workspaceProjectList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } /** * ---------------------------------Experiments----------------------------------* */ @DELETE @Path("delete/experiment") @Produces(MediaType.TEXT_PLAIN) public Response removeExperiment(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.removeExperiment(experimentId); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (ExperimentDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } @GET @Path("get/experiments/all") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperiments() throws RegistryException { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<AiravataExperiment> airavataExperimentList = airavataRegistry.getExperiments(); ExperimentList experimentList = new ExperimentList(); AiravataExperiment[] experiments = new AiravataExperiment[airavataExperimentList.size()]; for (int i = 0; i < airavataExperimentList.size(); i++) { experiments[i] = airavataExperimentList.get(i); } experimentList.setExperiments(experiments); if (airavataExperimentList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/experiments/project") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperimentsByProject(@QueryParam("projectName") String projectName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<AiravataExperiment> airavataExperimentList = airavataRegistry.getExperiments(projectName); ExperimentList experimentList = new ExperimentList(); AiravataExperiment[] experiments = new AiravataExperiment[airavataExperimentList.size()]; for (int i = 0; i < airavataExperimentList.size(); i++) { experiments[i] = airavataExperimentList.get(i); } experimentList.setExperiments(experiments); if (airavataExperimentList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/experiments/date") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperimentsByDate(@QueryParam("fromDate") String fromDate, @QueryParam("toDate") String toDate) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedFromDate = dateFormat.parse(fromDate); Date formattedToDate = dateFormat.parse(toDate); List<AiravataExperiment> airavataExperimentList = airavataRegistry.getExperiments(formattedFromDate, formattedToDate); ExperimentList experimentList = new ExperimentList(); AiravataExperiment[] experiments = new AiravataExperiment[airavataExperimentList.size()]; for (int i = 0; i < airavataExperimentList.size(); i++) { experiments[i] = airavataExperimentList.get(i); } experimentList.setExperiments(experiments); if (airavataExperimentList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (ParseException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/experiments/project/date") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperimentsByProjectDate(@QueryParam("projectName") String projectName, @QueryParam("fromDate") String fromDate, @QueryParam("toDate") String toDate) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedFromDate = dateFormat.parse(fromDate); Date formattedToDate = dateFormat.parse(toDate); List<AiravataExperiment> airavataExperimentList = airavataRegistry.getExperiments(projectName, formattedFromDate, formattedToDate); ExperimentList experimentList = new ExperimentList(); AiravataExperiment[] experiments = new AiravataExperiment[airavataExperimentList.size()]; for (int i = 0; i < airavataExperimentList.size(); i++) { experiments[i] = airavataExperimentList.get(i); } experimentList.setExperiments(experiments); if (airavataExperimentList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (ParseException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("add/experiment") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) public Response addExperiment(@FormParam("projectName") String projectName, @FormParam("experimentID") String experimentID, @FormParam("submittedDate") String submittedDate) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId(experimentID); Gateway gateway = (Gateway) context.getAttribute(RestServicesConstants.GATEWAY); AiravataUser airavataUser = (AiravataUser) context.getAttribute(RestServicesConstants.REGISTRY_USER); experiment.setGateway(gateway); experiment.setUser(airavataUser); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(submittedDate); experiment.setSubmittedDate(formattedDate); airavataRegistry.addExperiment(projectName, experiment); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (ExperimentDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } catch (WorkspaceProjectDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } catch (ParseException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("experiment/exist") @Produces(MediaType.TEXT_PLAIN) public Response isExperimentExists(@QueryParam("experimentId") String experimentId) throws RegistryException { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.isExperimentExists(experimentId); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("True"); return builder.build(); } catch (ExperimentDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity("False"); return builder.build(); } } @GET @Path("experiment/notexist/create") @Produces(MediaType.TEXT_PLAIN) public Response isExperimentExistsThenCreate(@QueryParam("experimentId") String experimentId, @QueryParam("createIfNotPresent") String createIfNotPresent) { boolean createIfNotPresentStatus = false; if (createIfNotPresent.equals("true")) { createIfNotPresentStatus = true; } airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.isExperimentExists(experimentId, createIfNotPresentStatus); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("True"); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } /** * --------------------------------- Provenance Registry ----------------------------------* */ @POST @Path("update/experiment") @Produces(MediaType.TEXT_PLAIN) public Response updateExperimentExecutionUser(@FormParam("experimentId") String experimentId, @FormParam("user") String user) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.updateExperimentExecutionUser(experimentId, user); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } @GET @Path("get/experiment/executionuser") @Produces(MediaType.TEXT_PLAIN) public Response getExperimentExecutionUser(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { String user = airavataRegistry.getExperimentExecutionUser(experimentId); if (user != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(user); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/experiment/name") @Produces(MediaType.TEXT_PLAIN) public Response getExperimentName(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { String result = airavataRegistry.getExperimentName(experimentId); if (result != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("update/experimentname") @Produces(MediaType.TEXT_PLAIN) public Response updateExperimentName(@FormParam("experimentId") String experimentId, @FormParam("experimentName") String experimentName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.updateExperimentName(experimentId, experimentName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } @GET @Path("get/experimentmetadata") @Produces(MediaType.TEXT_PLAIN) public Response getExperimentMetadata(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { String result = airavataRegistry.getExperimentMetadata(experimentId); if (result != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("update/experimentmetadata") @Produces(MediaType.TEXT_PLAIN) public Response updateExperimentMetadata(@FormParam("experimentId") String experimentId, @FormParam("metadata") String metadata) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.updateExperimentMetadata(experimentId, metadata); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } /** * --------------------------------- Provenance Registry ----------------------------------* */ @GET @Path("get/workflowtemplatename") @Produces(MediaType.TEXT_PLAIN) public Response getWorkflowExecutionTemplateName(@QueryParam("workflowInstanceId") String workflowInstanceId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { String result = airavataRegistry.getWorkflowExecutionTemplateName(workflowInstanceId); if (result != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("update/workflowinstancetemplatename") @Produces(MediaType.TEXT_PLAIN) public Response setWorkflowInstanceTemplateName(@FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("templateName") String templateName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.setWorkflowInstanceTemplateName(workflowInstanceId, templateName); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } @GET @Path("get/experimentworkflowinstances") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperimentWorkflowInstances(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<WorkflowInstance> experimentWorkflowInstances = airavataRegistry.getExperimentWorkflowInstances(experimentId); WorkflowInstancesList workflowInstancesList = new WorkflowInstancesList(); WorkflowInstance[] workflowInstanceMappings = new WorkflowInstance[experimentWorkflowInstances.size()]; for (int i = 0; i < experimentWorkflowInstances.size(); i++) { workflowInstanceMappings[i] = experimentWorkflowInstances.get(i); } workflowInstancesList.setWorkflowInstances(workflowInstanceMappings); if (experimentWorkflowInstances.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowInstancesList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("workflowinstance/exist/check") @Produces(MediaType.TEXT_PLAIN) public Response isWorkflowInstanceExists(@QueryParam("instanceId") String instanceId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { Boolean result = airavataRegistry.isWorkflowInstanceExists(instanceId); if (result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity("False"); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } @GET @Path("workflowinstance/exist/create") @Produces(MediaType.TEXT_PLAIN) public Response isWorkflowInstanceExistsThenCreate(@QueryParam("instanceId") String instanceId, @QueryParam("createIfNotPresent") boolean createIfNotPresent) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { Boolean result = airavataRegistry.isWorkflowInstanceExists(instanceId, createIfNotPresent); if (result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } @POST @Path("update/workflowinstancestatus/instanceid") @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowInstanceStatusByInstance(@FormParam("instanceId") String instanceId, @FormParam("executionStatus") String executionStatus) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkflowInstanceStatus.ExecutionStatus status = WorkflowInstanceStatus.ExecutionStatus.valueOf(executionStatus); airavataRegistry.updateWorkflowInstanceStatus(instanceId, status); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } @POST @Path("update/workflowinstancestatus") @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowInstanceStatus(@FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("executionStatus") String executionStatus, @FormParam("statusUpdateTime") String statusUpdateTime) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(statusUpdateTime); WorkflowInstance workflowInstance = airavataRegistry.getWorkflowInstanceData(workflowInstanceId).getWorkflowInstance(); WorkflowInstanceStatus.ExecutionStatus status = WorkflowInstanceStatus.ExecutionStatus.valueOf(executionStatus); WorkflowInstanceStatus workflowInstanceStatus = new WorkflowInstanceStatus(workflowInstance, status, formattedDate); airavataRegistry.updateWorkflowInstanceStatus(workflowInstanceStatus); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } catch (ParseException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } @GET @Path("get/workflowinstancestatus") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getWorkflowInstanceStatus(@QueryParam("instanceId") String instanceId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkflowInstanceStatus workflowInstanceStatus = airavataRegistry.getWorkflowInstanceStatus(instanceId); if (workflowInstanceStatus != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowInstanceStatus); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("update/workflownodeinput") @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowNodeInput(@FormParam("nodeID") String nodeID, @FormParam("workflowInstanceId") String workflowInstanceID, @FormParam("data") String data) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkflowInstanceData workflowInstanceData = airavataRegistry.getWorkflowInstanceData(workflowInstanceID); WorkflowInstanceNode workflowInstanceNode = workflowInstanceData.getNodeData(nodeID).getWorkflowInstanceNode(); airavataRegistry.updateWorkflowNodeInput(workflowInstanceNode, data); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } @POST @Path("update/workflownodeoutput") @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowNodeOutput(@FormParam("nodeID") String nodeID, @FormParam("workflowInstanceId") String workflowInstanceID, @FormParam("data") String data) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkflowInstanceData workflowInstanceData = airavataRegistry.getWorkflowInstanceData(workflowInstanceID); WorkflowInstanceNode workflowInstanceNode = workflowInstanceData.getNodeData(nodeID).getWorkflowInstanceNode(); airavataRegistry.updateWorkflowNodeOutput(workflowInstanceNode, data); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); return builder.build(); } } /* @GET @Path("search/workflowinstancenodeinput") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response searchWorkflowInstanceNodeInput(@QueryParam("experimentIdRegEx") String experimentIdRegEx, @QueryParam("workflowNameRegEx") String workflowNameRegEx, @QueryParam("nodeNameRegEx") String nodeNameRegEx) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<WorkflowNodeIOData> workflowNodeIODataList = airavataRegistry.searchWorkflowInstanceNodeInput(experimentIdRegEx, workflowNameRegEx, nodeNameRegEx); WorkflowNodeIODataMapping[] workflowNodeIODataCollection = new WorkflowNodeIODataMapping[workflowNodeIODataList.size()]; WorkflowNodeIODataList workflowNodeIOData = new WorkflowNodeIODataList(); for (int i = 0; i < workflowNodeIODataList.size(); i++) { WorkflowNodeIOData nodeIOData = workflowNodeIODataList.get(i); WorkflowNodeIODataMapping workflowNodeIODataMapping = new WorkflowNodeIODataMapping(); workflowNodeIODataMapping.setExperimentId(nodeIOData.getExperimentId()); workflowNodeIODataMapping.setWorkflowId(nodeIOData.getWorkflowId()); workflowNodeIODataMapping.setWorkflowInstanceId(nodeIOData.getWorkflowInstanceId()); workflowNodeIODataMapping.setWorkflowName(nodeIOData.getWorkflowName()); workflowNodeIODataMapping.setWorkflowNodeType(nodeIOData.getNodeType().toString()); workflowNodeIODataCollection[i] = workflowNodeIODataMapping; } workflowNodeIOData.setWorkflowNodeIOData(workflowNodeIODataCollection); if (workflowNodeIODataList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowNodeIOData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("search/workflowinstancenodeoutput") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response searchWorkflowInstanceNodeOutput(@QueryParam("experimentIdRegEx") String experimentIdRegEx, @QueryParam("workflowNameRegEx") String workflowNameRegEx, @QueryParam("nodeNameRegEx") String nodeNameRegEx) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<WorkflowNodeIOData> workflowNodeIODataList = airavataRegistry.searchWorkflowInstanceNodeOutput(experimentIdRegEx, workflowNameRegEx, nodeNameRegEx); WorkflowNodeIODataMapping[] workflowNodeIODataCollection = new WorkflowNodeIODataMapping[workflowNodeIODataList.size()]; WorkflowNodeIODataList workflowNodeIOData = new WorkflowNodeIODataList(); for (int i = 0; i < workflowNodeIODataList.size(); i++) { WorkflowNodeIOData nodeIOData = workflowNodeIODataList.get(i); WorkflowNodeIODataMapping workflowNodeIODataMapping = new WorkflowNodeIODataMapping(); workflowNodeIODataMapping.setExperimentId(nodeIOData.getExperimentId()); workflowNodeIODataMapping.setWorkflowId(nodeIOData.getWorkflowId()); workflowNodeIODataMapping.setWorkflowInstanceId(nodeIOData.getWorkflowInstanceId()); workflowNodeIODataMapping.setWorkflowName(nodeIOData.getWorkflowName()); workflowNodeIODataMapping.setWorkflowNodeType(nodeIOData.getNodeType().toString()); workflowNodeIODataCollection[i] = workflowNodeIODataMapping; } workflowNodeIOData.setWorkflowNodeIOData(workflowNodeIODataCollection); if (workflowNodeIODataList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowNodeIOData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/workflowinstancenodeinput") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getWorkflowInstanceNodeInput(@QueryParam("workflowInstanceId") String workflowInstanceId, @QueryParam("nodeType") String nodeType) { // Airavata JPA Registry method returns null at the moment airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<WorkflowNodeIOData> workflowNodeIODataList = airavataRegistry.getWorkflowInstanceNodeInput(workflowInstanceId, nodeType); WorkflowNodeIODataMapping[] workflowNodeIODataCollection = new WorkflowNodeIODataMapping[workflowNodeIODataList.size()]; WorkflowNodeIODataList workflowNodeIOData = new WorkflowNodeIODataList(); for (int i = 0; i < workflowNodeIODataList.size(); i++) { WorkflowNodeIOData nodeIOData = workflowNodeIODataList.get(i); WorkflowNodeIODataMapping workflowNodeIODataMapping = new WorkflowNodeIODataMapping(); workflowNodeIODataMapping.setExperimentId(nodeIOData.getExperimentId()); workflowNodeIODataMapping.setWorkflowId(nodeIOData.getWorkflowId()); workflowNodeIODataMapping.setWorkflowInstanceId(nodeIOData.getWorkflowInstanceId()); workflowNodeIODataMapping.setWorkflowName(nodeIOData.getWorkflowName()); workflowNodeIODataMapping.setWorkflowNodeType(nodeIOData.getNodeType().toString()); workflowNodeIODataCollection[i] = workflowNodeIODataMapping; } workflowNodeIOData.setWorkflowNodeIOData(workflowNodeIODataCollection); if (workflowNodeIODataList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowNodeIOData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/workflowinstancenodeoutput") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getWorkflowInstanceNodeOutput(@QueryParam("workflowInstanceId") String workflowInstanceId, @QueryParam("nodeType") String nodeType) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<WorkflowNodeIOData> workflowNodeIODataList = airavataRegistry.getWorkflowInstanceNodeOutput(workflowInstanceId, nodeType); WorkflowNodeIODataMapping[] workflowNodeIODataCollection = new WorkflowNodeIODataMapping[workflowNodeIODataList.size()]; WorkflowNodeIODataList workflowNodeIOData = new WorkflowNodeIODataList(); for (int i = 0; i < workflowNodeIODataList.size(); i++) { WorkflowNodeIOData nodeIOData = workflowNodeIODataList.get(i); WorkflowNodeIODataMapping workflowNodeIODataMapping = new WorkflowNodeIODataMapping(); workflowNodeIODataMapping.setExperimentId(nodeIOData.getExperimentId()); workflowNodeIODataMapping.setWorkflowId(nodeIOData.getWorkflowId()); workflowNodeIODataMapping.setWorkflowInstanceId(nodeIOData.getWorkflowInstanceId()); workflowNodeIODataMapping.setWorkflowName(nodeIOData.getWorkflowName()); workflowNodeIODataMapping.setWorkflowNodeType(nodeIOData.getNodeType().toString()); workflowNodeIODataCollection[i] = workflowNodeIODataMapping; } workflowNodeIOData.setWorkflowNodeIOData(workflowNodeIODataCollection); if (workflowNodeIODataList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowNodeIOData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } */ @GET @Path("get/experiment") @Produces(MediaType.APPLICATION_XML) public Response getExperiment(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ ExperimentDataImpl experimentData = (ExperimentDataImpl)airavataRegistry.getExperiment(experimentId); if (experimentData != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/experimentId/user") @Produces(MediaType.APPLICATION_XML) public Response getExperimentIdByUser(@QueryParam("username") String username) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ ArrayList<String> experiments = (ArrayList)airavataRegistry.getExperimentIdByUser(username); ExperimentIDList experimentIDList = new ExperimentIDList(); experimentIDList.setExperimentIDList(experiments); if (experiments.size() != 0){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentIDList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/experiment/user") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperimentByUser(@QueryParam("username") String username) throws RegistryException { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ List<ExperimentData> experimentDataList = airavataRegistry.getExperimentByUser(username); ExperimentDataList experimentData = new ExperimentDataList(); List<ExperimentDataImpl> experimentDatas = new ArrayList<ExperimentDataImpl>(); for (int i = 0; i < experimentDataList.size(); i ++){ experimentDatas.add((ExperimentDataImpl)experimentDataList.get(i)); } experimentData.setExperimentDataList(experimentDatas); if (experimentDataList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @POST @Path("update/workflownode/status") @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowNodeStatus(@FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("nodeId") String nodeId, @FormParam("executionStatus") String executionStatus) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceStatus.ExecutionStatus status = WorkflowInstanceStatus.ExecutionStatus.valueOf(executionStatus); airavataRegistry.updateWorkflowNodeStatus(workflowInstanceId, nodeId, status); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/workflownode/status") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getWorkflowNodeStatus(@QueryParam("workflowInstanceId") String workflowInstanceId, @QueryParam("nodeId") String nodeId){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceData workflowInstanceData = airavataRegistry.getWorkflowInstanceData(workflowInstanceId); WorkflowInstanceNode workflowInstanceNode = workflowInstanceData.getNodeData(nodeId).getWorkflowInstanceNode(); WorkflowInstanceNodeStatus workflowNodeStatus = airavataRegistry.getWorkflowNodeStatus(workflowInstanceNode); if(workflowNodeStatus != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowNodeStatus); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/workflownode/starttime") @Produces(MediaType.TEXT_PLAIN) public Response getWorkflowNodeStartTime(@QueryParam("workflowInstanceId") String workflowInstanceId, @QueryParam("nodeId") String nodeId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceData workflowInstanceData = airavataRegistry.getWorkflowInstanceData(workflowInstanceId); WorkflowInstanceNode workflowInstanceNode = workflowInstanceData.getNodeData(nodeId).getWorkflowInstanceNode(); Date workflowNodeStartTime = airavataRegistry.getWorkflowNodeStartTime(workflowInstanceNode); if(workflowNodeStartTime != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowNodeStartTime.toString()); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/workflow/starttime") @Produces(MediaType.TEXT_PLAIN) public Response getWorkflowStartTime(@QueryParam("workflowInstanceId") String workflowInstanceId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceData workflowInstanceData = airavataRegistry.getWorkflowInstanceData(workflowInstanceId); WorkflowInstance workflowInstance = workflowInstanceData.getWorkflowInstance(); Date workflowStartTime = airavataRegistry.getWorkflowStartTime(workflowInstance); if(workflowStartTime != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowStartTime.toString()); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("update/workflownode/gramdata") @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowNodeGramData(WorkflowNodeGramData workflowNodeGramData) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.updateWorkflowNodeGramData(workflowNodeGramData); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/workflowinstancedata") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getWorkflowInstanceData(@QueryParam("workflowInstanceId") String workflowInstanceId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceData workflowInstanceData = airavataRegistry.getWorkflowInstanceData(workflowInstanceId); if (workflowInstanceData != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowInstanceData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("workflowinstance/exist") @Produces(MediaType.TEXT_PLAIN) public Response isWorkflowInstanceNodePresent(@QueryParam("workflowInstanceId") String workflowInstanceId, @QueryParam("nodeId") String nodeId){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ boolean workflowInstanceNodePresent = airavataRegistry.isWorkflowInstanceNodePresent(workflowInstanceId, nodeId); if (workflowInstanceNodePresent){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("False"); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @GET @Path("workflowinstance/nodeData") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getWorkflowInstanceNodeData(@QueryParam("workflowInstanceId") String workflowInstanceId, @QueryParam("nodeId") String nodeId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceNodeData workflowInstanceNodeData = airavataRegistry.getWorkflowInstanceNodeData(workflowInstanceId, nodeId); if (workflowInstanceNodeData != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowInstanceNodeData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity(e.getMessage()); return builder.build(); } } @POST @Path("add/workflowinstance") @Produces(MediaType.TEXT_PLAIN) public Response addWorkflowInstance(@FormParam("experimentId") String experimentId, @FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("templateName") String templateName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.addWorkflowInstance(experimentId, workflowInstanceId, templateName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity(e.getMessage()); return builder.build(); } } @POST @Path("update/workflownodetype") @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowNodeType(@FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("nodeId") String nodeId, @FormParam("nodeType") String nodeType) throws RegistryException { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceNodeData workflowInstanceNodeData = airavataRegistry.getWorkflowInstanceData(workflowInstanceId).getNodeData(nodeId); WorkflowInstanceNode workflowInstanceNode = workflowInstanceNodeData.getWorkflowInstanceNode(); WorkflowNodeType workflowNodeType = new WorkflowNodeType(); //currently from API only service node is being used workflowNodeType.setNodeType(WorkflowNodeType.WorkflowNode.SERVICENODE); // workflowNodeType.setNodeType(nodeType); airavataRegistry.updateWorkflowNodeType(workflowInstanceNode, workflowNodeType); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @POST @Path("add/workflowinstancenode") @Produces(MediaType.TEXT_PLAIN) public Response addWorkflowInstanceNode(@FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("nodeId") String nodeId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.addWorkflowInstanceNode(workflowInstanceId, nodeId); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /**---------------------------------User Workflow Registry----------------------------------**/ @GET @Path("workflow/exist") @Produces(MediaType.TEXT_PLAIN) public Response isWorkflowExists(@QueryParam("workflowName") String workflowName){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ boolean workflowExists = airavataRegistry.isWorkflowExists(workflowName); if (workflowExists){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); }else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("False"); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @POST @Path("add/workflow") @Produces(MediaType.TEXT_PLAIN) public Response addWorkflow(@FormParam("workflowName") String workflowName, @FormParam("workflowGraphXml") String workflowGraphXml) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.addWorkflow(workflowName, workflowGraphXml); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (UserWorkflowAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @POST @Path("update/workflow") @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflow(@FormParam("workflowName") String workflowName, @FormParam("workflowGraphXml") String workflowGraphXml){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.updateWorkflow(workflowName, workflowGraphXml); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (UserWorkflowAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @GET @Path("get/workflowgraph") @Produces(MediaType.TEXT_PLAIN) public Response getWorkflowGraphXML(@QueryParam("workflowName") String workflowName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ String workflowGraphXML = airavataRegistry.getWorkflowGraphXML(workflowName); if (workflowGraphXML != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowGraphXML); return builder.build(); }else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (UserWorkflowDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @GET @Path("get/workflows") @Produces(MediaType.TEXT_PLAIN) public Response getWorkflows() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ Map<String, String> workflows = airavataRegistry.getWorkflows(); WorkflowList workflowList = new WorkflowList(); List<Workflow> workflowsModels = new ArrayList<Workflow>(); for (String workflowName : workflows.keySet()){ Workflow workflow = new Workflow(); workflow.setWorkflowName(workflowName); workflow.setWorkflowGraph(workflows.get(workflowName)); workflowsModels.add(workflow); } workflowList.setWorkflowList(workflowsModels); if(workflows.size() != 0 ){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @GET @Path("remove/workflow") @Produces(MediaType.TEXT_PLAIN) public Response removeWorkflow(@QueryParam("workflowName") String workflowName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.removeWorkflow(workflowName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (UserWorkflowDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /**---------------------------------Published Workflow Registry----------------------------------**/ @GET @Path("publishwf/exist") @Produces(MediaType.TEXT_PLAIN) public Response isPublishedWorkflowExists(@QueryParam("workflowname") String workflowname) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ boolean workflowExists = airavataRegistry.isPublishedWorkflowExists(workflowname); if (workflowExists){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("True"); return builder.build(); }else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("False"); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @POST @Path("publish/workflow") @Produces(MediaType.TEXT_PLAIN) public Response publishWorkflow(@FormParam("workflowName") String workflowName, @FormParam("publishWorkflowName") String publishWorkflowName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.publishWorkflow(workflowName, publishWorkflowName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (UserWorkflowDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (PublishedWorkflowAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @POST @Path("publish/default/workflow") @Produces(MediaType.TEXT_PLAIN) public Response publishWorkflow(@FormParam("workflowName") String workflowName){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.publishWorkflow(workflowName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (UserWorkflowDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (PublishedWorkflowAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @GET @Path("get/publishworkflowgraph") @Produces(MediaType.TEXT_PLAIN) public Response getPublishedWorkflowGraphXML(@QueryParam("workflowName") String workflowName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ String publishedWorkflowGraphXML = airavataRegistry.getPublishedWorkflowGraphXML(workflowName); if (publishedWorkflowGraphXML !=null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(publishedWorkflowGraphXML); return builder.build(); }else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (PublishedWorkflowDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @GET @Path("get/publishworkflownames") @Produces(MediaType.TEXT_PLAIN) public Response getPublishedWorkflowNames() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ List<String> publishedWorkflowNames = airavataRegistry.getPublishedWorkflowNames(); PublishWorkflowNamesList publishWorkflowNamesList = new PublishWorkflowNamesList(); publishWorkflowNamesList.setPublishWorkflowNames(publishedWorkflowNames); if (publishedWorkflowNames.size() != 0){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(publishWorkflowNamesList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @GET @Path("get/publishworkflows") @Produces(MediaType.TEXT_PLAIN) public Response getPublishedWorkflows() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ Map<String, String> publishedWorkflows = airavataRegistry.getPublishedWorkflows(); WorkflowList workflowList = new WorkflowList(); List<Workflow> workflowsModels = new ArrayList<Workflow>(); for (String workflowName : publishedWorkflows.keySet()){ Workflow workflow = new Workflow(); workflow.setWorkflowName(workflowName); workflow.setWorkflowGraph(publishedWorkflows.get(workflowName)); workflowsModels.add(workflow); } workflowList.setWorkflowList(workflowsModels); if(publishedWorkflows.size() != 0 ){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } @GET @Path("remove/publishworkflow") @Produces(MediaType.TEXT_PLAIN) public Response removePublishedWorkflow(@QueryParam("workflowName") String workflowName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.removePublishedWorkflow(workflowName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); return builder.build(); } catch (PublishedWorkflowDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } }
8,654
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/ApplicationRegistration.java
package org.apache.airavata.services.registry.rest.resources; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletContext; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.airavata.registry.api.AiravataRegistry2; import org.apache.airavata.services.registry.rest.resourcemappings.ApplicationDescriptor; import org.apache.airavata.services.registry.rest.resourcemappings.ServiceDescriptor; import org.apache.airavata.services.registry.rest.resourcemappings.ServiceParameters; @Path("/api/application") public class ApplicationRegistration { protected static AiravataRegistry2 airavataRegistry; @Context ServletContext context; public ApplicationRegistration() { // airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); } // Sample JSON is : {"applicationName":"Testing","cpuCount":"12","maxMemory":"0","maxWallTime":"0","minMemory":"0","nodeCount":"0","processorsPerNode":"0"} @POST @Path("save") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response addServiceDescriptor(ApplicationDescriptor application){ try{ application.getName(); Response.ResponseBuilder builder = Response.status(Response.Status.ACCEPTED); return builder.build(); } catch (Exception e) { throw new WebApplicationException(e,Response.Status.INTERNAL_SERVER_ERROR); } } @GET @Path("get") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public ApplicationDescriptor getServiceDescriptor(String applicationName){ try{ ApplicationDescriptor application = new ApplicationDescriptor(); application.setName(applicationName); ServiceDescriptor descriptor = new ServiceDescriptor(); ServiceParameters parameters = new ServiceParameters(); parameters.setName("myinput"); parameters.setDataType("input"); parameters.setDescription("my input"); parameters.setType("String"); ServiceParameters parameters1 = new ServiceParameters(); parameters1.setName("myinput"); parameters1.setDataType("input"); parameters1.setDescription("my input"); parameters1.setType("String"); List<ServiceParameters> inputlist = new ArrayList<ServiceParameters>(); inputlist.add(parameters); inputlist.add(parameters1); ServiceParameters parameters2 = new ServiceParameters(); parameters2.setName("myoutput"); parameters2.setDataType("output"); parameters2.setDescription("my output"); parameters2.setType("String"); ServiceParameters parameters3 = new ServiceParameters(); parameters3.setName("myoutput"); parameters3.setDataType("output"); parameters3.setDescription("my output"); parameters3.setType("String"); List<ServiceParameters> outputlist = new ArrayList<ServiceParameters>(); outputlist.add(parameters2); outputlist.add(parameters3); descriptor.setInputParams(inputlist); descriptor.setOutputParams(outputlist); application.setName("service1"); application.setHostdescName("localhost"); return application; } catch (Exception e) { throw new WebApplicationException(e,Response.Status.INTERNAL_SERVER_ERROR); } } }
8,655
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/RegistryApplication.java
package org.apache.airavata.services.registry.rest.resources; import javax.ws.rs.core.Application; import java.util.HashSet; import java.util.Set; public class RegistryApplication extends Application { @Override public Set<Class<?>> getClasses() { final Set<Class<?>> classes = new HashSet<Class<?>>(); // register root resource classes.add(RegistryResource.class); return classes; } @Override public Set<Object> getSingletons() { return super.getSingletons(); } }
8,656
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/PublishWorkflowRegistryResource.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.services.registry.rest.resources; import org.apache.airavata.registry.api.AiravataRegistry2; import org.apache.airavata.registry.api.exception.RegistryException; import org.apache.airavata.registry.api.exception.gateway.PublishedWorkflowAlreadyExistsException; import org.apache.airavata.registry.api.exception.gateway.PublishedWorkflowDoesNotExistsException; import org.apache.airavata.registry.api.exception.worker.UserWorkflowDoesNotExistsException; import org.apache.airavata.services.registry.rest.resourcemappings.PublishWorkflowNamesList; import org.apache.airavata.services.registry.rest.resourcemappings.Workflow; import org.apache.airavata.services.registry.rest.resourcemappings.WorkflowList; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.apache.airavata.services.registry.rest.utils.RestServicesConstants; import javax.servlet.ServletContext; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * This class is the REST interface for all the operations related to published workflows that has * been exposed by Airavata Registry API */ @Path(ResourcePathConstants.PublishedWFConstants.REGISTRY_API_PUBLISHWFREGISTRY) public class PublishWorkflowRegistryResource { private AiravataRegistry2 airavataRegistry; @Context ServletContext context; /**---------------------------------Published Workflow Registry----------------------------------**/ /** * This method will check whether a given published workflow name already exists * @param workflowname publish workflow name * @return HTTP response */ @GET @Path(ResourcePathConstants.PublishedWFConstants.PUBLISHWF_EXIST) @Produces(MediaType.TEXT_PLAIN) public Response isPublishedWorkflowExists(@QueryParam("workflowname") String workflowname) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ boolean workflowExists = airavataRegistry.isPublishedWorkflowExists(workflowname); if (workflowExists){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Publish workflow exists..."); return builder.build(); }else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Publish workflow does not exists..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will make a user workflow as a published workflow with the given name * @param workflowName user workflow name * @param publishWorkflowName name need to save the published workflow as * @return HTTP response */ @POST @Path(ResourcePathConstants.PublishedWFConstants.PUBLISH_WORKFLOW) @Produces(MediaType.TEXT_PLAIN) public Response publishWorkflow(@FormParam("workflowName") String workflowName, @FormParam("publishWorkflowName") String publishWorkflowName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.publishWorkflow(workflowName, publishWorkflowName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow published successfully..."); return builder.build(); } catch (UserWorkflowDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (PublishedWorkflowAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will publish a workflow with the default workflow name * @param workflowName workflow name * @return HTTP response */ @POST @Path(ResourcePathConstants.PublishedWFConstants.PUBLISH_DEFAULT_WORKFLOW) @Produces(MediaType.TEXT_PLAIN) public Response publishWorkflow(@FormParam("workflowName") String workflowName){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.publishWorkflow(workflowName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow published successfully..."); return builder.build(); } catch (UserWorkflowDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (PublishedWorkflowAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return the worklflow graph * @param workflowName workflow name * @return HTTP response */ @GET @Path(ResourcePathConstants.PublishedWFConstants.GET_PUBLISHWORKFLOWGRAPH) @Produces(MediaType.TEXT_PLAIN) public Response getPublishedWorkflowGraphXML(@QueryParam("workflowName") String workflowName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ String publishedWorkflowGraphXML = airavataRegistry.getPublishedWorkflowGraphXML(workflowName); if (publishedWorkflowGraphXML !=null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(publishedWorkflowGraphXML); return builder.build(); }else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Could not find workflow graph..."); return builder.build(); } } catch (PublishedWorkflowDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all the published workflow names * @return HTTP response */ @GET @Path(ResourcePathConstants.PublishedWFConstants.GET_PUBLISHWORKFLOWNAMES) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getPublishedWorkflowNames() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ List<String> publishedWorkflowNames = airavataRegistry.getPublishedWorkflowNames(); PublishWorkflowNamesList publishWorkflowNamesList = new PublishWorkflowNamesList(); publishWorkflowNamesList.setPublishWorkflowNames(publishedWorkflowNames); if (publishedWorkflowNames.size() != 0){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(publishWorkflowNamesList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No published workflows available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all the published workflows * @return HTTP response */ @GET @Path(ResourcePathConstants.PublishedWFConstants.GET_PUBLISHWORKFLOWS) @Produces(MediaType.TEXT_PLAIN) public Response getPublishedWorkflows() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ Map<String, String> publishedWorkflows = airavataRegistry.getPublishedWorkflows(); WorkflowList workflowList = new WorkflowList(); List<Workflow> workflowsModels = new ArrayList<Workflow>(); for (String workflowName : publishedWorkflows.keySet()){ Workflow workflow = new Workflow(); workflow.setWorkflowName(workflowName); workflow.setWorkflowGraph(publishedWorkflows.get(workflowName)); workflowsModels.add(workflow); } workflowList.setWorkflowList(workflowsModels); if(publishedWorkflows.size() != 0 ){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Publish workflows does not exists..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will delete a published workflow with the given published workflow name * @param workflowName published workflow name * @return HTTP response */ @GET @Path(ResourcePathConstants.PublishedWFConstants.REMOVE_PUBLISHWORKFLOW) @Produces(MediaType.TEXT_PLAIN) public Response removePublishedWorkflow(@QueryParam("workflowName") String workflowName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.removePublishedWorkflow(workflowName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Publish workflow removed successfully..."); return builder.build(); } catch (PublishedWorkflowDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } }
8,657
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/UserWorkflowRegistryResource.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.services.registry.rest.resources; import org.apache.airavata.registry.api.AiravataRegistry2; import org.apache.airavata.registry.api.exception.RegistryException; import org.apache.airavata.registry.api.exception.worker.UserWorkflowAlreadyExistsException; import org.apache.airavata.registry.api.exception.worker.UserWorkflowDoesNotExistsException; import org.apache.airavata.services.registry.rest.resourcemappings.Workflow; import org.apache.airavata.services.registry.rest.resourcemappings.WorkflowList; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.apache.airavata.services.registry.rest.utils.RestServicesConstants; import javax.servlet.ServletContext; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * This class is a REST interface to all the operations related to user workflows that has been * exposed by Airavata Registry API */ @Path(ResourcePathConstants.UserWFConstants.REGISTRY_API_USERWFREGISTRY) public class UserWorkflowRegistryResource { private AiravataRegistry2 airavataRegistry; @Context ServletContext context; /**---------------------------------User Workflow Registry----------------------------------**/ /** * This method will check whether a given user workflow name already exists * @param workflowName workflow name * @return HTTP response */ @GET @Path(ResourcePathConstants.UserWFConstants.WORKFLOW_EXIST) @Produces(MediaType.TEXT_PLAIN) public Response isWorkflowExists(@QueryParam("workflowName") String workflowName){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ boolean workflowExists = airavataRegistry.isWorkflowExists(workflowName); if (workflowExists){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("User workflow exists..."); return builder.build(); }else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("User workflow does not exists..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will add a new workflow * @param workflowName workflow name * @param workflowGraphXml workflow content * @return HTTP response */ @POST @Path(ResourcePathConstants.UserWFConstants.ADD_WORKFLOW) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) public Response addWorkflow(@FormParam("workflowName") String workflowName, @FormParam("workflowGraphXml") String workflowGraphXml) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.addWorkflow(workflowName, workflowGraphXml); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow added successfully..."); return builder.build(); } catch (UserWorkflowAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update the workflow * @param workflowName workflow name * @param workflowGraphXml workflow content * @return HTTP response */ @POST @Path(ResourcePathConstants.UserWFConstants.UPDATE_WORKFLOW) @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflow(@FormParam("workflowName") String workflowName, @FormParam("workflowGraphXml") String workflowGraphXml){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.updateWorkflow(workflowName, workflowGraphXml); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow updated successfully..."); return builder.build(); } catch (UserWorkflowAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return the content of the given workflow * @param workflowName workflow name * @return HTTP response */ @GET @Path(ResourcePathConstants.UserWFConstants.GET_WORKFLOWGRAPH) @Produces(MediaType.TEXT_PLAIN) public Response getWorkflowGraphXML(@QueryParam("workflowName") String workflowName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ String workflowGraphXML = airavataRegistry.getWorkflowGraphXML(workflowName); if (workflowGraphXML != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowGraphXML); return builder.build(); }else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Could not get workflow graph..."); return builder.build(); } } catch (UserWorkflowDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all the user workflows * @return HTTP response */ @GET @Path(ResourcePathConstants.UserWFConstants.GET_WORKFLOWS) @Produces(MediaType.TEXT_PLAIN) public Response getWorkflows() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ Map<String, String> workflows = airavataRegistry.getWorkflows(); WorkflowList workflowList = new WorkflowList(); List<Workflow> workflowsModels = new ArrayList<Workflow>(); for (String workflowName : workflows.keySet()){ Workflow workflow = new Workflow(); workflow.setWorkflowName(workflowName); workflow.setWorkflowGraph(workflows.get(workflowName)); workflowsModels.add(workflow); } workflowList.setWorkflowList(workflowsModels); if(workflows.size() != 0 ){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("User workflows do not exists..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will delete a user workflow with the given user workflow name * @param workflowName user workflow name * @return HTTP response */ @GET @Path(ResourcePathConstants.UserWFConstants.REMOVE_WORKFLOW) @Produces(MediaType.TEXT_PLAIN) public Response removeWorkflow(@QueryParam("workflowName") String workflowName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.removeWorkflow(workflowName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow removed successfully..."); return builder.build(); } catch (UserWorkflowDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } }
8,658
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/ProjectRegistryResource.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.services.registry.rest.resources; import org.apache.airavata.registry.api.AiravataRegistry2; import org.apache.airavata.registry.api.WorkspaceProject; import org.apache.airavata.registry.api.exception.RegistryException; import org.apache.airavata.registry.api.exception.worker.WorkspaceProjectAlreadyExistsException; import org.apache.airavata.registry.api.exception.worker.WorkspaceProjectDoesNotExistsException; import org.apache.airavata.services.registry.rest.resourcemappings.WorkspaceProjectList; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.apache.airavata.services.registry.rest.utils.RestServicesConstants; import javax.servlet.ServletContext; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; /** * This class is a REST interface for all the operations related to Project that are exposed in * Airavata Registry API */ @Path(ResourcePathConstants.ProjectResourcePathConstants.REGISTRY_API_PROJECTREGISTRY) public class ProjectRegistryResource { private AiravataRegistry2 airavataRegistry; @Context ServletContext context; /** * ---------------------------------Project Registry----------------------------------* */ /** * This method will check whether a given project name exists * @param projectName project name * @return HTTP response */ @GET @Path(ResourcePathConstants.ProjectResourcePathConstants.PROJECT_EXIST) @Produces(MediaType.TEXT_PLAIN) public Response isWorkspaceProjectExists(@QueryParam("projectName") String projectName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { boolean result = airavataRegistry.isWorkspaceProjectExists(projectName); if (result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Project exists..."); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity("Project does not exist..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will check whether a project exists and create according to the createIfNotExists * flag * @param projectName project name * @param createIfNotExists flag to check whether a new project should be created or not * @return HTTP response */ @POST @Path(ResourcePathConstants.ProjectResourcePathConstants.PROJECT_EXIST_CREATE) @Produces(MediaType.TEXT_PLAIN) public Response isWorkspaceProjectExistsCreate(@FormParam("projectName") String projectName, @FormParam("createIfNotExists") String createIfNotExists) { boolean createIfNotExistStatus = false; if (createIfNotExists.equals("true")) { createIfNotExistStatus = true; } airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { boolean result = airavataRegistry.isWorkspaceProjectExists(projectName, createIfNotExistStatus); if (result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("New project has been created..."); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity("Could not create the project..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will add new workspace project * @param projectName project name * @return HTTP response */ @POST @Path(ResourcePathConstants.ProjectResourcePathConstants.ADD_PROJECT) @Produces(MediaType.TEXT_PLAIN) public Response addWorkspaceProject(@FormParam("projectName") String projectName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkspaceProject workspaceProject = new WorkspaceProject(projectName, airavataRegistry); airavataRegistry.addWorkspaceProject(workspaceProject); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workspace project added successfully..."); return builder.build(); } catch (WorkspaceProjectAlreadyExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update the workspace project * @param projectName project name * @return HTTP response */ @POST @Path(ResourcePathConstants.ProjectResourcePathConstants.UPDATE_PROJECT) @Produces(MediaType.TEXT_PLAIN) public Response updateWorkspaceProject(@FormParam("projectName") String projectName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkspaceProject workspaceProject = new WorkspaceProject(projectName, airavataRegistry); airavataRegistry.updateWorkspaceProject(workspaceProject); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workspace project updated successfully..."); return builder.build(); } catch (WorkspaceProjectDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will delete workspace project * @param projectName project name * @return HTTP response */ @DELETE @Path(ResourcePathConstants.ProjectResourcePathConstants.DELETE_PROJECT) @Produces(MediaType.TEXT_PLAIN) public Response deleteWorkspaceProject(@QueryParam("projectName") String projectName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.deleteWorkspaceProject(projectName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workspace project deleted successfully..."); return builder.build(); } catch (WorkspaceProjectDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve the workspace project * @param projectName project name * @return HTTP response */ @GET @Path(ResourcePathConstants.ProjectResourcePathConstants.GET_PROJECT) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getWorkspaceProject(@QueryParam("projectName") String projectName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkspaceProject workspaceProject = airavataRegistry.getWorkspaceProject(projectName); if (workspaceProject != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workspaceProject); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity("No workspace projects available..."); return builder.build(); } } catch (WorkspaceProjectDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve all the workspace projects * @return HTTP response */ @GET @Path(ResourcePathConstants.ProjectResourcePathConstants.GET_PROJECTS) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getWorkspaceProjects() { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<WorkspaceProject> workspaceProjects = airavataRegistry.getWorkspaceProjects(); WorkspaceProjectList workspaceProjectList = new WorkspaceProjectList(); WorkspaceProject[] workspaceProjectSet = new WorkspaceProject[workspaceProjects.size()]; for (int i = 0; i < workspaceProjects.size(); i++) { workspaceProjectSet[i] = workspaceProjects.get(i); } workspaceProjectList.setWorkspaceProjects(workspaceProjectSet); if (workspaceProjects.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workspaceProjectList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No workspace projects available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } }
8,659
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/ProvenanceRegistryResource.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.services.registry.rest.resources; import org.apache.airavata.registry.api.AiravataRegistry2; import org.apache.airavata.registry.api.exception.RegistryException; import org.apache.airavata.registry.api.impl.ExperimentDataImpl; import org.apache.airavata.registry.api.workflow.*; import org.apache.airavata.services.registry.rest.resourcemappings.ExperimentDataList; import org.apache.airavata.services.registry.rest.resourcemappings.ExperimentIDList; import org.apache.airavata.services.registry.rest.resourcemappings.WorkflowInstancesList; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.apache.airavata.services.registry.rest.utils.RestServicesConstants; import javax.servlet.ServletContext; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * This class is the REST interface for all the provenance data related methods that are exposed * by Airavata Registry API */ @Path(ResourcePathConstants.ProvenanceResourcePathConstants.REGISTRY_API_PROVENANCEREGISTRY) public class ProvenanceRegistryResource { private AiravataRegistry2 airavataRegistry; @Context ServletContext context; /** * --------------------------------- Provenance Registry ----------------------------------* */ /** * This method will update the experiment execution user * @param experimentId experiment ID * @param user experiment execution user * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_EXPERIMENT_EXECUTIONUSER) @Produces(MediaType.TEXT_PLAIN) public Response updateExperimentExecutionUser(@FormParam("experimentId") String experimentId, @FormParam("user") String user) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.updateExperimentExecutionUser(experimentId, user); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Experiment execution user updated successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve experiment execution user * @param experimentId experiment ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENT_EXECUTIONUSER) @Produces(MediaType.TEXT_PLAIN) public Response getExperimentExecutionUser(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { String user = airavataRegistry.getExperimentExecutionUser(experimentId); if (user != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(user); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); builder.entity("Could not get experiment execution user..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve the experiment name for a given experiment ID * @param experimentId experiment ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENT_NAME) @Produces(MediaType.TEXT_PLAIN) public Response getExperimentName(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { String result = airavataRegistry.getExperimentName(experimentId); if (result != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_MODIFIED); builder.entity("Experiment name not available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update the experiment name * @param experimentId experiment ID * @param experimentName experiment name * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_EXPERIMENTNAME) @Produces(MediaType.TEXT_PLAIN) public Response updateExperimentName(@FormParam("experimentId") String experimentId, @FormParam("experimentName") String experimentName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.updateExperimentName(experimentId, experimentName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Experiment Name updated successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve the experiment metadata * @param experimentId experiment ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENTMETADATA) @Produces(MediaType.TEXT_PLAIN) public Response getExperimentMetadata(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { String result = airavataRegistry.getExperimentMetadata(experimentId); if (result != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Experiment metadata not available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update the experiment metadata * @param experimentId experiment ID * @param metadata experiment metadata * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_EXPERIMENTMETADATA) @Produces(MediaType.TEXT_PLAIN) public Response updateExperimentMetadata(@FormParam("experimentId") String experimentId, @FormParam("metadata") String metadata) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.updateExperimentMetadata(experimentId, metadata); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Experiment metadata updated successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve workflow execution name * @param workflowInstanceId workflow instance ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_WORKFLOWTEMPLATENAME) @Produces(MediaType.TEXT_PLAIN) public Response getWorkflowExecutionTemplateName(@QueryParam("workflowInstanceId") String workflowInstanceId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { String result = airavataRegistry.getWorkflowExecutionTemplateName(workflowInstanceId); if (result != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(result); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Workflow template name not available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will set the workflow instance template name * @param workflowInstanceId workflow instance id * @param templateName template name * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWINSTANCETEMPLATENAME) @Produces(MediaType.TEXT_PLAIN) public Response setWorkflowInstanceTemplateName(@FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("templateName") String templateName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.setWorkflowInstanceTemplateName(workflowInstanceId, templateName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow template name updated successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will get experiment workflow instances for a given experiment ID * @param experimentId experiment ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENTWORKFLOWINSTANCES) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperimentWorkflowInstances(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<WorkflowInstance> experimentWorkflowInstances = airavataRegistry.getExperimentWorkflowInstances(experimentId); WorkflowInstancesList workflowInstancesList = new WorkflowInstancesList(); WorkflowInstance[] workflowInstances = new WorkflowInstance[experimentWorkflowInstances.size()]; for (int i = 0; i < experimentWorkflowInstances.size(); i++) { workflowInstances[i] = experimentWorkflowInstances.get(i); } workflowInstancesList.setWorkflowInstances(workflowInstances); if (experimentWorkflowInstances.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowInstancesList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No workflow instances available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will check whether a workflow instance exists * @param instanceId workflow instance ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.WORKFLOWINSTANCE_EXIST_CHECK) @Produces(MediaType.TEXT_PLAIN) public Response isWorkflowInstanceExists(@QueryParam("instanceId") String instanceId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { Boolean result = airavataRegistry.isWorkflowInstanceExists(instanceId); if (result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow instance available..."); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity("Workflow instance does not exist..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will check whether a workflow instance exist and create the workflow instance * according to createIfNotPresent flag * @param instanceId workflow instance ID * @param createIfNotPresent flag whether to create a new workflow instance or not * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.WORKFLOWINSTANCE_NODE_EXIST_CREATE) @Produces(MediaType.TEXT_PLAIN) public Response isWorkflowInstanceExistsThenCreate(@QueryParam("instanceId") String instanceId, @QueryParam("createIfNotPresent") boolean createIfNotPresent) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { Boolean result = airavataRegistry.isWorkflowInstanceExists(instanceId, createIfNotPresent); if (result) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("New workflow instance has been created..."); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity("Could not create workflow instance..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update workflow instance status * @param instanceId workflow instance ID * @param executionStatus workflow execution status * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWINSTANCESTATUS_INSTANCEID) @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowInstanceStatusByInstance(@FormParam("instanceId") String instanceId, @FormParam("executionStatus") String executionStatus) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkflowInstanceStatus.ExecutionStatus status = WorkflowInstanceStatus.ExecutionStatus.valueOf(executionStatus); airavataRegistry.updateWorkflowInstanceStatus(instanceId, status); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow instance status updated successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update the workflow instance status * @param workflowInstanceId workflow instance ID * @param executionStatus workflow execution status * @param statusUpdateTime workflow status update time * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWINSTANCESTATUS) @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowInstanceStatus(@FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("executionStatus") String executionStatus, @FormParam("statusUpdateTime") String statusUpdateTime) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(statusUpdateTime); WorkflowInstance workflowInstance = airavataRegistry.getWorkflowInstanceData(workflowInstanceId).getWorkflowInstance(); WorkflowInstanceStatus.ExecutionStatus status = WorkflowInstanceStatus.ExecutionStatus.valueOf(executionStatus); WorkflowInstanceStatus workflowInstanceStatus = new WorkflowInstanceStatus(workflowInstance, status, formattedDate); airavataRegistry.updateWorkflowInstanceStatus(workflowInstanceStatus); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow instance status updated successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } catch (ParseException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve workflow instance statuse for a given workflow instance ID * @param instanceId workflow instance ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_WORKFLOWINSTANCESTATUS) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getWorkflowInstanceStatus(@QueryParam("instanceId") String instanceId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkflowInstanceStatus workflowInstanceStatus = airavataRegistry.getWorkflowInstanceStatus(instanceId); if (workflowInstanceStatus != null) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowInstanceStatus); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Could not get workflow instance status..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update workflowNodeInput * @param nodeID workflow node ID * @param workflowInstanceID workflow instance ID * @param data input data * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWNODEINPUT) @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowNodeInput(@FormParam("nodeID") String nodeID, @FormParam("workflowInstanceId") String workflowInstanceID, @FormParam("data") String data) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkflowInstanceData workflowInstanceData = airavataRegistry.getWorkflowInstanceData(workflowInstanceID); WorkflowInstanceNode workflowInstanceNode = workflowInstanceData.getNodeData(nodeID).getWorkflowInstanceNode(); airavataRegistry.updateWorkflowNodeInput(workflowInstanceNode, data); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow node input saved successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update workflow node output * @param nodeID workflow node ID * @param workflowInstanceID workflow instance ID * @param data workflow node output data * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWNODEOUTPUT) @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowNodeOutput(@FormParam("nodeID") String nodeID, @FormParam("workflowInstanceId") String workflowInstanceID, @FormParam("data") String data) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { WorkflowInstanceData workflowInstanceData = airavataRegistry.getWorkflowInstanceData(workflowInstanceID); WorkflowInstanceNode workflowInstanceNode = workflowInstanceData.getNodeData(nodeID).getWorkflowInstanceNode(); airavataRegistry.updateWorkflowNodeOutput(workflowInstanceNode, data); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow node output saved successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /* @GET @Path("search/workflowinstancenodeinput") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response searchWorkflowInstanceNodeInput(@QueryParam("experimentIdRegEx") String experimentIdRegEx, @QueryParam("workflowNameRegEx") String workflowNameRegEx, @QueryParam("nodeNameRegEx") String nodeNameRegEx) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<WorkflowNodeIOData> workflowNodeIODataList = airavataRegistry.searchWorkflowInstanceNodeInput(experimentIdRegEx, workflowNameRegEx, nodeNameRegEx); WorkflowNodeIODataMapping[] workflowNodeIODataCollection = new WorkflowNodeIODataMapping[workflowNodeIODataList.size()]; WorkflowNodeIODataList workflowNodeIOData = new WorkflowNodeIODataList(); for (int i = 0; i < workflowNodeIODataList.size(); i++) { WorkflowNodeIOData nodeIOData = workflowNodeIODataList.get(i); WorkflowNodeIODataMapping workflowNodeIODataMapping = new WorkflowNodeIODataMapping(); workflowNodeIODataMapping.setExperimentId(nodeIOData.getExperimentId()); workflowNodeIODataMapping.setWorkflowId(nodeIOData.getWorkflowId()); workflowNodeIODataMapping.setWorkflowInstanceId(nodeIOData.getWorkflowInstanceId()); workflowNodeIODataMapping.setWorkflowName(nodeIOData.getWorkflowName()); workflowNodeIODataMapping.setWorkflowNodeType(nodeIOData.getNodeType().toString()); workflowNodeIODataCollection[i] = workflowNodeIODataMapping; } workflowNodeIOData.setWorkflowNodeIOData(workflowNodeIODataCollection); if (workflowNodeIODataList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowNodeIOData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("search/workflowinstancenodeoutput") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response searchWorkflowInstanceNodeOutput(@QueryParam("experimentIdRegEx") String experimentIdRegEx, @QueryParam("workflowNameRegEx") String workflowNameRegEx, @QueryParam("nodeNameRegEx") String nodeNameRegEx) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<WorkflowNodeIOData> workflowNodeIODataList = airavataRegistry.searchWorkflowInstanceNodeOutput(experimentIdRegEx, workflowNameRegEx, nodeNameRegEx); WorkflowNodeIODataMapping[] workflowNodeIODataCollection = new WorkflowNodeIODataMapping[workflowNodeIODataList.size()]; WorkflowNodeIODataList workflowNodeIOData = new WorkflowNodeIODataList(); for (int i = 0; i < workflowNodeIODataList.size(); i++) { WorkflowNodeIOData nodeIOData = workflowNodeIODataList.get(i); WorkflowNodeIODataMapping workflowNodeIODataMapping = new WorkflowNodeIODataMapping(); workflowNodeIODataMapping.setExperimentId(nodeIOData.getExperimentId()); workflowNodeIODataMapping.setWorkflowId(nodeIOData.getWorkflowId()); workflowNodeIODataMapping.setWorkflowInstanceId(nodeIOData.getWorkflowInstanceId()); workflowNodeIODataMapping.setWorkflowName(nodeIOData.getWorkflowName()); workflowNodeIODataMapping.setWorkflowNodeType(nodeIOData.getNodeType().toString()); workflowNodeIODataCollection[i] = workflowNodeIODataMapping; } workflowNodeIOData.setWorkflowNodeIOData(workflowNodeIODataCollection); if (workflowNodeIODataList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowNodeIOData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/workflowinstancenodeinput") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getWorkflowInstanceNodeInput(@QueryParam("workflowInstanceId") String workflowInstanceId, @QueryParam("nodeType") String nodeType) { // Airavata JPA Registry method returns null at the moment airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<WorkflowNodeIOData> workflowNodeIODataList = airavataRegistry.getWorkflowInstanceNodeInput(workflowInstanceId, nodeType); WorkflowNodeIODataMapping[] workflowNodeIODataCollection = new WorkflowNodeIODataMapping[workflowNodeIODataList.size()]; WorkflowNodeIODataList workflowNodeIOData = new WorkflowNodeIODataList(); for (int i = 0; i < workflowNodeIODataList.size(); i++) { WorkflowNodeIOData nodeIOData = workflowNodeIODataList.get(i); WorkflowNodeIODataMapping workflowNodeIODataMapping = new WorkflowNodeIODataMapping(); workflowNodeIODataMapping.setExperimentId(nodeIOData.getExperimentId()); workflowNodeIODataMapping.setWorkflowId(nodeIOData.getWorkflowId()); workflowNodeIODataMapping.setWorkflowInstanceId(nodeIOData.getWorkflowInstanceId()); workflowNodeIODataMapping.setWorkflowName(nodeIOData.getWorkflowName()); workflowNodeIODataMapping.setWorkflowNodeType(nodeIOData.getNodeType().toString()); workflowNodeIODataCollection[i] = workflowNodeIODataMapping; } workflowNodeIOData.setWorkflowNodeIOData(workflowNodeIODataCollection); if (workflowNodeIODataList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowNodeIOData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } @GET @Path("get/workflowinstancenodeoutput") @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getWorkflowInstanceNodeOutput(@QueryParam("workflowInstanceId") String workflowInstanceId, @QueryParam("nodeType") String nodeType) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<WorkflowNodeIOData> workflowNodeIODataList = airavataRegistry.getWorkflowInstanceNodeOutput(workflowInstanceId, nodeType); WorkflowNodeIODataMapping[] workflowNodeIODataCollection = new WorkflowNodeIODataMapping[workflowNodeIODataList.size()]; WorkflowNodeIODataList workflowNodeIOData = new WorkflowNodeIODataList(); for (int i = 0; i < workflowNodeIODataList.size(); i++) { WorkflowNodeIOData nodeIOData = workflowNodeIODataList.get(i); WorkflowNodeIODataMapping workflowNodeIODataMapping = new WorkflowNodeIODataMapping(); workflowNodeIODataMapping.setExperimentId(nodeIOData.getExperimentId()); workflowNodeIODataMapping.setWorkflowId(nodeIOData.getWorkflowId()); workflowNodeIODataMapping.setWorkflowInstanceId(nodeIOData.getWorkflowInstanceId()); workflowNodeIODataMapping.setWorkflowName(nodeIOData.getWorkflowName()); workflowNodeIODataMapping.setWorkflowNodeType(nodeIOData.getNodeType().toString()); workflowNodeIODataCollection[i] = workflowNodeIODataMapping; } workflowNodeIOData.setWorkflowNodeIOData(workflowNodeIODataCollection); if (workflowNodeIODataList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowNodeIOData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); return builder.build(); } } */ /** * This method will return all the data related to a given experiment. This will include workflow * status, input values, output values to the workflow, node statuses etc. * @param experimentId experiment ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENT) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperiment(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ ExperimentDataImpl experimentData = (ExperimentDataImpl)airavataRegistry.getExperiment(experimentId); if (experimentData != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No experiments available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all the experiment IDs for a given user * @param username experiment execution user * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENT_ID_USER) @Produces(MediaType.APPLICATION_XML) public Response getExperimentIdByUser(@QueryParam("username") String username) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ ArrayList<String> experiments = (ArrayList)airavataRegistry.getExperimentIdByUser(username); ExperimentIDList experimentIDList = new ExperimentIDList(); experimentIDList.setExperimentIDList(experiments); if (experiments.size() != 0){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentIDList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No experiments available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all the experiments for a given user * @param username experiment execution user * @return HTTP response * */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENT_USER) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperimentByUser(@QueryParam("username") String username){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ List<ExperimentData> experimentDataList = airavataRegistry.getExperimentByUser(username); ExperimentDataList experimentData = new ExperimentDataList(); List<ExperimentDataImpl> experimentDatas = new ArrayList<ExperimentDataImpl>(); for (int i = 0; i < experimentDataList.size(); i ++){ experimentDatas.add((ExperimentDataImpl)experimentDataList.get(i)); } experimentData.setExperimentDataList(experimentDatas); if (experimentDataList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No experiments available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update the workflow node status * @param workflowInstanceId workflow instance ID * @param nodeId node ID * @param executionStatus node execution status * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWNODE_STATUS) @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowNodeStatus(@FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("nodeId") String nodeId, @FormParam("executionStatus") String executionStatus) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceStatus.ExecutionStatus status = WorkflowInstanceStatus.ExecutionStatus.valueOf(executionStatus); airavataRegistry.updateWorkflowNodeStatus(workflowInstanceId, nodeId, status); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow node status updated successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve workflow status for a given workflow instance and node * @param workflowInstanceId workflow instance ID * @param nodeId node ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_WORKFLOWNODE_STATUS) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getWorkflowNodeStatus(@QueryParam("workflowInstanceId") String workflowInstanceId, @QueryParam("nodeId") String nodeId){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceData workflowInstanceData = airavataRegistry.getWorkflowInstanceData(workflowInstanceId); WorkflowInstanceNode workflowInstanceNode = workflowInstanceData.getNodeData(nodeId).getWorkflowInstanceNode(); WorkflowInstanceNodeStatus workflowNodeStatus = airavataRegistry.getWorkflowNodeStatus(workflowInstanceNode); if(workflowNodeStatus != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowNodeStatus); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Could not retrieve workflow node status..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will retrieve workflow node started time * @param workflowInstanceId workflow instance ID * @param nodeId node ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_WORKFLOWNODE_STARTTIME) @Produces(MediaType.TEXT_PLAIN) public Response getWorkflowNodeStartTime(@QueryParam("workflowInstanceId") String workflowInstanceId, @QueryParam("nodeId") String nodeId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceData workflowInstanceData = airavataRegistry.getWorkflowInstanceData(workflowInstanceId); WorkflowInstanceNode workflowInstanceNode = workflowInstanceData.getNodeData(nodeId).getWorkflowInstanceNode(); Date workflowNodeStartTime = airavataRegistry.getWorkflowNodeStartTime(workflowInstanceNode); if(workflowNodeStartTime != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowNodeStartTime.toString()); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Could not retrieve workflow node started time..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return workflow started time * @param workflowInstanceId workflow instance ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_WORKFLOW_STARTTIME) @Produces(MediaType.TEXT_PLAIN) public Response getWorkflowStartTime(@QueryParam("workflowInstanceId") String workflowInstanceId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceData workflowInstanceData = airavataRegistry.getWorkflowInstanceData(workflowInstanceId); WorkflowInstance workflowInstance = workflowInstanceData.getWorkflowInstance(); Date workflowStartTime = airavataRegistry.getWorkflowStartTime(workflowInstance); if(workflowStartTime != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowStartTime.toString()); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Could not retrieve workflow start time..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update workflow node Gram data * @param workflowNodeGramData workflow node gram data object as a JSON input * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWNODE_GRAMDATA) @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowNodeGramData(WorkflowNodeGramData workflowNodeGramData) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.updateWorkflowNodeGramData(workflowNodeGramData); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow node Gram data updated successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all the information regarding a workflow instance * @param workflowInstanceId workflow instance ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_WORKFLOWINSTANCEDATA) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getWorkflowInstanceData(@QueryParam("workflowInstanceId") String workflowInstanceId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceData workflowInstanceData = airavataRegistry.getWorkflowInstanceData(workflowInstanceId); if (workflowInstanceData != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowInstanceData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Could not retrieve workflow instance data..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method wil check whether a workflow node present * @param workflowInstanceId workflow instance ID * @param nodeId node ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.WORKFLOWINSTANCE_NODE_EXIST) @Produces(MediaType.TEXT_PLAIN) public Response isWorkflowInstanceNodePresent(@QueryParam("workflowInstanceId") String workflowInstanceId, @QueryParam("nodeId") String nodeId){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ boolean workflowInstanceNodePresent = airavataRegistry.isWorkflowInstanceNodePresent(workflowInstanceId, nodeId); if (workflowInstanceNodePresent){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow instance node exists..."); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Workflow instance node does not exist..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method wil check whether a workflow node present and create a new workflow node according * to createIfNotPresent flag * @param workflowInstanceId workflow instance Id * @param nodeId node Id * @param createIfNotPresent flag whether to create a new node or not * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.WORKFLOWINSTANCE_NODE_EXIST_CREATE) @Produces(MediaType.TEXT_PLAIN) public Response isWorkflowInstanceNodePresentCreate(@FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("nodeId") String nodeId, @FormParam("createIfNotPresent") boolean createIfNotPresent){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ boolean workflowInstanceNodePresent = airavataRegistry.isWorkflowInstanceNodePresent(workflowInstanceId, nodeId, createIfNotPresent); if (workflowInstanceNodePresent){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow instance node exists..."); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Workflow instance node does not exist..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return data related to the workflow instance node * @param workflowInstanceId workflow instance ID * @param nodeId node ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.WORKFLOWINSTANCE_NODE_DATA) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getWorkflowInstanceNodeData(@QueryParam("workflowInstanceId") String workflowInstanceId, @QueryParam("nodeId") String nodeId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceNodeData workflowInstanceNodeData = airavataRegistry.getWorkflowInstanceNodeData(workflowInstanceId, nodeId); if (workflowInstanceNodeData != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(workflowInstanceNodeData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Could not retrieve workflow instance node data..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will add a workflow instance * @param experimentId experiment ID * @param workflowInstanceId workflow instance ID * @param templateName workflow template name * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.ADD_WORKFLOWINSTANCE) @Produces(MediaType.TEXT_PLAIN) public Response addWorkflowInstance(@FormParam("experimentId") String experimentId, @FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("templateName") String templateName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.addWorkflowInstance(experimentId, workflowInstanceId, templateName); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow instance added successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will update the workflow node type * @param workflowInstanceId workflow instance ID * @param nodeId node ID * @param nodeType node type * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWNODETYPE) @Produces(MediaType.TEXT_PLAIN) public Response updateWorkflowNodeType(@FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("nodeId") String nodeId, @FormParam("nodeType") String nodeType) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ WorkflowInstanceNodeData workflowInstanceNodeData = airavataRegistry.getWorkflowInstanceData(workflowInstanceId).getNodeData(nodeId); WorkflowInstanceNode workflowInstanceNode = workflowInstanceNodeData.getWorkflowInstanceNode(); WorkflowNodeType workflowNodeType = new WorkflowNodeType(); //currently from API only service node is being used workflowNodeType.setNodeType(WorkflowNodeType.WorkflowNode.SERVICENODE); // workflowNodeType.setNodeType(nodeType); airavataRegistry.updateWorkflowNodeType(workflowInstanceNode, workflowNodeType); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow instance node type updated successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will add a new node to workflow instance * @param workflowInstanceId workflow instance ID * @param nodeId node ID * @return HTTP response */ @POST @Path(ResourcePathConstants.ProvenanceResourcePathConstants.ADD_WORKFLOWINSTANCENODE) @Produces(MediaType.TEXT_PLAIN) public Response addWorkflowInstanceNode(@FormParam("workflowInstanceId") String workflowInstanceId, @FormParam("nodeId") String nodeId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ airavataRegistry.addWorkflowInstanceNode(workflowInstanceId, nodeId); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Workflow instance node added successfully..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method wil check whether the experiment name exists * @param experimentName experiment name * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.EXPERIMENTNAME_EXISTS) @Produces(MediaType.TEXT_PLAIN) public Response isExperimentNameExist(@QueryParam("experimentName") String experimentName){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ boolean experimentNameExist = airavataRegistry.isExperimentNameExist(experimentName); if (experimentNameExist){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Experiment name exists..."); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Experiment name does not exists..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return only information regarding to the experiment. Node information will * not be retrieved * @param experimentId experiment ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENT_METAINFORMATION) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getExperimentMetaInformation(@QueryParam("experimentId") String experimentId){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ ExperimentDataImpl experimentMetaInformation = (ExperimentDataImpl)airavataRegistry.getExperimentMetaInformation(experimentId); if (experimentMetaInformation != null){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentMetaInformation); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Could not retrieve experiment meta information..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all meta information for all the experiments * @param user experiment execution user * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_ALL_EXPERIMENT_METAINFORMATION) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response getAllExperimentMetaInformation(@QueryParam("user") String user){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ List<ExperimentData> allExperimentMetaInformation = airavataRegistry.getAllExperimentMetaInformation(user); ExperimentDataList experimentDataList = new ExperimentDataList(); List<ExperimentDataImpl> experimentDatas = new ArrayList<ExperimentDataImpl>(); for (ExperimentData experimentData : allExperimentMetaInformation){ experimentDatas.add((ExperimentDataImpl)experimentData); } experimentDataList.setExperimentDataList(experimentDatas); if (allExperimentMetaInformation.size() != 0){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentDataList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No experiment data available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will search all the experiments which has the name like given experiment name for * a given experiment execution user * @param user experiment execution user * @param experimentNameRegex experiment name * @return HTTP response */ @GET @Path(ResourcePathConstants.ProvenanceResourcePathConstants.SEARCH_EXPERIMENTS) @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Response searchExperiments(@QueryParam("user") String user, @QueryParam("experimentNameRegex") String experimentNameRegex){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try{ List<ExperimentData> experimentDataList = airavataRegistry.searchExperiments(user, experimentNameRegex); ExperimentDataList experimentData = new ExperimentDataList(); List<ExperimentDataImpl> experimentDatas = new ArrayList<ExperimentDataImpl>(); for (ExperimentData experimentData1 : experimentDataList){ experimentDatas.add((ExperimentDataImpl)experimentData1); } experimentData.setExperimentDataList(experimentDatas); if (experimentDataList.size() != 0){ Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentData); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No experiment data available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } }
8,660
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resources/ExperimentRegistryResource.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.services.registry.rest.resources; import org.apache.airavata.registry.api.AiravataExperiment; import org.apache.airavata.registry.api.AiravataRegistry2; import org.apache.airavata.registry.api.AiravataUser; import org.apache.airavata.registry.api.Gateway; import org.apache.airavata.registry.api.exception.RegistryException; import org.apache.airavata.registry.api.exception.worker.ExperimentDoesNotExistsException; import org.apache.airavata.registry.api.exception.worker.WorkspaceProjectDoesNotExistsException; import org.apache.airavata.services.registry.rest.resourcemappings.ExperimentList; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.apache.airavata.services.registry.rest.utils.RestServicesConstants; import javax.servlet.ServletContext; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * This class is a REST interface all the methods related to experiments that are exposed by * Airavata Registry API */ @Path(ResourcePathConstants.ExperimentResourcePathConstants.EXP_RESOURCE_PATH) public class ExperimentRegistryResource { private AiravataRegistry2 airavataRegistry; @Context ServletContext context; /** * ---------------------------------Experiments----------------------------------* */ /** * This method will delete an experiment with given experiment ID * @param experimentId experiment ID * @return HTTP response */ @DELETE @Path(ResourcePathConstants.ExperimentResourcePathConstants.DELETE_EXP) @Produces(MediaType.TEXT_PLAIN) public Response removeExperiment(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.removeExperiment(experimentId); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Experiment removed successfully..."); return builder.build(); } catch (ExperimentDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all the experiments available * @return HTTP response * */ @GET @Path(ResourcePathConstants.ExperimentResourcePathConstants.GET_ALL_EXPS) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperiments(){ airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<AiravataExperiment> airavataExperimentList = airavataRegistry.getExperiments(); ExperimentList experimentList = new ExperimentList(); AiravataExperiment[] experiments = new AiravataExperiment[airavataExperimentList.size()]; for (int i = 0; i < airavataExperimentList.size(); i++) { experiments[i] = airavataExperimentList.get(i); } experimentList.setExperiments(experiments); if (airavataExperimentList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No experiments found..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all the experiments for a given project * @param projectName project name * @return HTTP response */ @GET @Path(ResourcePathConstants.ExperimentResourcePathConstants.GET_EXPS_BY_PROJECT) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperimentsByProject(@QueryParam("projectName") String projectName) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { List<AiravataExperiment> airavataExperimentList = airavataRegistry.getExperiments(projectName); ExperimentList experimentList = new ExperimentList(); AiravataExperiment[] experiments = new AiravataExperiment[airavataExperimentList.size()]; for (int i = 0; i < airavataExperimentList.size(); i++) { experiments[i] = airavataExperimentList.get(i); } experimentList.setExperiments(experiments); if (airavataExperimentList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No experiments available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all the experiments in a given period of time * @param fromDate starting date * @param toDate end date * @return HTTP response */ @GET @Path(ResourcePathConstants.ExperimentResourcePathConstants.GET_EXPS_BY_DATE) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperimentsByDate(@QueryParam("fromDate") String fromDate, @QueryParam("toDate") String toDate) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedFromDate = dateFormat.parse(fromDate); Date formattedToDate = dateFormat.parse(toDate); List<AiravataExperiment> airavataExperimentList = airavataRegistry.getExperiments(formattedFromDate, formattedToDate); ExperimentList experimentList = new ExperimentList(); AiravataExperiment[] experiments = new AiravataExperiment[airavataExperimentList.size()]; for (int i = 0; i < airavataExperimentList.size(); i++) { experiments[i] = airavataExperimentList.get(i); } experimentList.setExperiments(experiments); if (airavataExperimentList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No experiments available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (ParseException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will return all the experiments for a given project in a given period of time * @param projectName project name * @param fromDate starting date * @param toDate end date * @return HTTP response */ @GET @Path(ResourcePathConstants.ExperimentResourcePathConstants.GET_EXPS_PER_PROJECT_BY_DATE) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response getExperimentsByProjectDate(@QueryParam("projectName") String projectName, @QueryParam("fromDate") String fromDate, @QueryParam("toDate") String toDate) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedFromDate = dateFormat.parse(fromDate); Date formattedToDate = dateFormat.parse(toDate); List<AiravataExperiment> airavataExperimentList = airavataRegistry.getExperiments(projectName, formattedFromDate, formattedToDate); ExperimentList experimentList = new ExperimentList(); AiravataExperiment[] experiments = new AiravataExperiment[airavataExperimentList.size()]; for (int i = 0; i < airavataExperimentList.size(); i++) { experiments[i] = airavataExperimentList.get(i); } experimentList.setExperiments(experiments); if (airavataExperimentList.size() != 0) { Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity(experimentList); return builder.build(); } else { Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("No experiments available..."); return builder.build(); } } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (ParseException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will add a new experiment * @param projectName project name * @param experimentID experiment ID * @param submittedDate submitted date * @return HTTP response */ @POST @Path(ResourcePathConstants.ExperimentResourcePathConstants.ADD_EXP) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces(MediaType.TEXT_PLAIN) public Response addExperiment(@FormParam("projectName") String projectName, @FormParam("experimentID") String experimentID, @FormParam("submittedDate") String submittedDate) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { AiravataExperiment experiment = new AiravataExperiment(); experiment.setExperimentId(experimentID); Gateway gateway = (Gateway) context.getAttribute(RestServicesConstants.GATEWAY); AiravataUser airavataUser = (AiravataUser) context.getAttribute(RestServicesConstants.REGISTRY_USER); experiment.setGateway(gateway); experiment.setUser(airavataUser); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date formattedDate = dateFormat.parse(submittedDate); experiment.setSubmittedDate(formattedDate); airavataRegistry.addExperiment(projectName, experiment); Response.ResponseBuilder builder = Response.status(Response.Status.OK); builder.entity("Experiment added successfully..."); return builder.build(); } catch (ExperimentDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } catch (WorkspaceProjectDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } catch (ParseException e) { Response.ResponseBuilder builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR); builder.entity(e.getMessage()); return builder.build(); } } /** * This method will check whether the given experiment ID exists * @param experimentId experiment ID * @return HTTP response */ @GET @Path(ResourcePathConstants.ExperimentResourcePathConstants.EXP_EXISTS) @Produces(MediaType.TEXT_PLAIN) public Response isExperimentExists(@QueryParam("experimentId") String experimentId) { airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.isExperimentExists(experimentId); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("Experiment exists..."); return builder.build(); } catch (ExperimentDoesNotExistsException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity("Exprtiment does not exist..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity("Exprtiment does not exist..."); return builder.build(); } } /** * This method will check whether an experiment exist and create if not exists according to the * createIfNotPresent flag * @param experimentId experiment ID * @param createIfNotPresent flag to check whether to create a new experiment or not * @return HTTP response */ @GET @Path(ResourcePathConstants.ExperimentResourcePathConstants.EXP_EXISTS_CREATE) @Produces(MediaType.TEXT_PLAIN) public Response isExperimentExistsThenCreate(@QueryParam("experimentId") String experimentId, @QueryParam("createIfNotPresent") String createIfNotPresent) { boolean createIfNotPresentStatus = false; if (createIfNotPresent.equals("true")) { createIfNotPresentStatus = true; } airavataRegistry = (AiravataRegistry2) context.getAttribute(RestServicesConstants.AIRAVATA_REGISTRY); try { airavataRegistry.isExperimentExists(experimentId, createIfNotPresentStatus); Response.ResponseBuilder builder = Response.status(Response.Status.NO_CONTENT); builder.entity("New experiment created..."); return builder.build(); } catch (RegistryException e) { Response.ResponseBuilder builder = Response.status(Response.Status.NOT_FOUND); builder.entity(e.getMessage()); return builder.build(); } } }
8,661
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/utils/ApplicationDescriptorTypes.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.services.registry.rest.utils; public class ApplicationDescriptorTypes { public static final String APP_DEP_DESC_TYPE = "Default"; public static final String BATCH_APP_DEP_DESC_TYPE = "Batch"; public static final String GRAM_APP_DEP_DESC_TYPE = "Gram"; public static final String HADOOP_APP_DEP_DESC_TYPE = "Hadoop"; }
8,662
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/utils/RestServicesConstants.java
package org.apache.airavata.services.registry.rest.utils; public class RestServicesConstants { public static final String AIRAVATA_SERVER_PROPERTIES = "airavata-server.properties"; public static final String GATEWAY_ID = "gateway.id"; public static final String GATEWAY = "gateway"; public static final String REGISTRY_USERNAME = "registry.user"; public static final String REGISTRY_USER = "airavata.user"; public static final String AIRAVATA_REGISTRY = "airavataRegistry"; public static final String AIRAVATA_API = "airavataAPI"; }
8,663
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/utils/DescriptorUtil.java
package org.apache.airavata.services.registry.rest.utils; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.schemas.gfac.*; import org.apache.airavata.schemas.gfac.impl.GramApplicationDeploymentTypeImpl; import org.apache.airavata.services.registry.rest.resourcemappings.ApplicationDescriptor; import org.apache.airavata.services.registry.rest.resourcemappings.HostDescriptor; import org.apache.airavata.services.registry.rest.resourcemappings.ServiceDescriptor; import org.apache.airavata.services.registry.rest.resourcemappings.ServiceParameters; import java.util.ArrayList; import java.util.List; public class DescriptorUtil { public static HostDescription createHostDescription(String hostName, String hostAddress, String hostEndpoint, String gatekeeperEndpoint) { HostDescription host = new HostDescription(); if("".equalsIgnoreCase(gatekeeperEndpoint) || "".equalsIgnoreCase(hostEndpoint)) { host.getType().changeType(GlobusHostType.type); host.getType().setHostName(hostName); host.getType().setHostAddress(hostAddress); ((GlobusHostType) host.getType()). setGridFTPEndPointArray(new String[]{hostEndpoint}); ((GlobusHostType) host.getType()). setGlobusGateKeeperEndPointArray(new String[]{gatekeeperEndpoint}); } else { host.getType().setHostName(hostName); host.getType().setHostAddress(hostAddress); } return host; } public static ApplicationDeploymentDescription registerApplication(String appName, String exeuctableLocation, String scratchWorkingDirectory, String hostName, String projAccNumber, String queueName, String cpuCount, String nodeCount, String maxMemory) throws Exception { // Create Application Description ApplicationDeploymentDescription appDesc = new ApplicationDeploymentDescription(GramApplicationDeploymentType.type); GramApplicationDeploymentType app = (GramApplicationDeploymentType) appDesc.getType(); app.setCpuCount(Integer.parseInt(cpuCount)); app.setNodeCount(Integer.parseInt(nodeCount)); ApplicationDeploymentDescriptionType.ApplicationName name = appDesc.getType().addNewApplicationName(); name.setStringValue(appName); app.setExecutableLocation(exeuctableLocation); app.setScratchWorkingDirectory(scratchWorkingDirectory); ProjectAccountType projectAccountType = ((GramApplicationDeploymentType) appDesc.getType()).addNewProjectAccount(); projectAccountType.setProjectAccountNumber(projAccNumber); QueueType queueType = app.addNewQueue(); queueType.setQueueName(queueName); app.setMaxMemory(Integer.parseInt(maxMemory)); return appDesc; } public static ServiceDescription getServiceDescription(String serviceName, String inputName, String inputType, String outputName, String outputType) { // Create Service Description ServiceDescription serv = new ServiceDescription(); serv.getType().setName(serviceName); InputParameterType input = InputParameterType.Factory.newInstance(); input.setParameterName(inputName); ParameterType parameterType = input.addNewParameterType(); parameterType.setType(DataType.Enum.forString(inputType)); parameterType.setName(inputName); List<InputParameterType> inputList = new ArrayList<InputParameterType>(); inputList.add(input); InputParameterType[] inputParamList = inputList.toArray(new InputParameterType[inputList .size()]); OutputParameterType output = OutputParameterType.Factory.newInstance(); output.setParameterName(outputName); ParameterType parameterType1 = output.addNewParameterType(); parameterType1.setType(DataType.Enum.forString(outputType)); parameterType1.setName(outputName); List<OutputParameterType> outputList = new ArrayList<OutputParameterType>(); outputList.add(output); OutputParameterType[] outputParamList = outputList .toArray(new OutputParameterType[outputList.size()]); serv.getType().setInputParametersArray(inputParamList); serv.getType().setOutputParametersArray(outputParamList); return serv; } public static HostDescriptor createHostDescriptor (HostDescription hostDescription){ List<String> hostType = new ArrayList<String>(); List<String> gridFTPEndPoint = new ArrayList<String>(); List<String> globusGateKeeperEndPoint = new ArrayList<String>(); List<String> imageID = new ArrayList<String>(); List<String> instanceID = new ArrayList<String>(); HostDescriptor hostDescriptor = new HostDescriptor(); hostDescriptor.setHostname(hostDescription.getType().getHostName()); hostDescriptor.setHostAddress(hostDescription.getType().getHostAddress()); HostDescriptionType hostDescriptionType = hostDescription.getType(); if (hostDescriptionType instanceof GlobusHostType){ GlobusHostType globusHostType = (GlobusHostType) hostDescriptionType; hostType.add(HostTypes.GLOBUS_HOST_TYPE); String[] globusGateKeeperEndPointArray = globusHostType.getGlobusGateKeeperEndPointArray(); for (int i = 0; i < globusGateKeeperEndPointArray.length ; i++){ globusGateKeeperEndPoint.add(globusGateKeeperEndPointArray[i]); } String[] gridFTPEndPointArray = globusHostType.getGridFTPEndPointArray(); for (int i = 0; i < gridFTPEndPointArray.length ; i++){ gridFTPEndPoint.add(globusGateKeeperEndPointArray[i]); } }else if (hostDescriptionType instanceof GsisshHostType){ GsisshHostType gsisshHostType = (GsisshHostType) hostDescriptionType; hostType.add(HostTypes.GSISSH_HOST_TYPE); String[] gridFTPEndPointArray = gsisshHostType.getGridFTPEndPointArray(); for (int i = 0; i < gridFTPEndPointArray.length ; i++){ gridFTPEndPoint.add(gridFTPEndPointArray[i]); } } else if (hostDescriptionType instanceof Ec2HostType) { Ec2HostType ec2HostType = (Ec2HostType) hostDescriptionType; hostType.add(HostTypes.EC2_HOST_TYPE); String[] imageIDArray = ec2HostType.getImageIDArray(); for (int i = 0; i < imageIDArray.length ; i++){ imageID.add(imageIDArray[i]); } String[] instanceIDArray = ec2HostType.getInstanceIDArray(); for (int i = 0; i < instanceIDArray.length ; i++){ instanceID.add(instanceIDArray[i]); } } else { hostType.add(HostTypes.HOST_DESCRIPTION_TYPE); } hostDescriptor.setGlobusGateKeeperEndPoint(globusGateKeeperEndPoint); hostDescriptor.setGridFTPEndPoint(gridFTPEndPoint); hostDescriptor.setImageID(imageID); hostDescriptor.setInstanceID(instanceID); hostDescriptor.setHostType(hostType); return hostDescriptor; } public static HostDescription createHostDescription (HostDescriptor hostDescriptor){ HostDescription hostDescription = new HostDescription(); hostDescription.getType().setHostAddress(hostDescriptor.getHostAddress()); hostDescription.getType().setHostName(hostDescriptor.getHostname()); if (hostDescriptor.getHostType() != null && !hostDescriptor.getHostType().isEmpty()) { if (hostDescriptor.getHostType().equals(HostTypes.GLOBUS_HOST_TYPE)) { ((GlobusHostType) hostDescription.getType()).addGlobusGateKeeperEndPoint(hostDescriptor.getGlobusGateKeeperEndPoint().get(0)); ((GlobusHostType) hostDescription.getType()).addGridFTPEndPoint(hostDescriptor.getGridFTPEndPoint().get(0)); } else if (hostDescriptor.getHostType().equals(HostTypes.GSISSH_HOST_TYPE)) { ((GsisshHostType) hostDescription).addGridFTPEndPoint(hostDescriptor.getGridFTPEndPoint().get(0)); } else if (hostDescriptor.getHostType().equals(HostTypes.EC2_HOST_TYPE)) { ((Ec2HostType) hostDescription).addImageID(hostDescriptor.getImageID().get(0)); ((Ec2HostType) hostDescription).addInstanceID(hostDescriptor.getInstanceID().get(0)); } } return hostDescription; } public static ServiceDescription createServiceDescription (ServiceDescriptor serviceDescriptor){ ServiceDescription serviceDescription = new ServiceDescription(); serviceDescription.getType().setName(serviceDescriptor.getServiceName()); serviceDescription.getType().setDescription(serviceDescriptor.getDescription()); List<ServiceParameters> inputParams = serviceDescriptor.getInputParams(); InputParameterType[] inputParameterTypeArray = new InputParameterType[inputParams.size()]; for (int i = 0; i < inputParams.size(); i++){ InputParameterType parameter = InputParameterType.Factory.newInstance(); parameter.setParameterName(inputParams.get(i).getName()); parameter.setParameterValueArray(new String[]{inputParams.get(i).getName()}); ParameterType parameterType = parameter.addNewParameterType(); parameterType.setType(DataType.Enum.forString(inputParams.get(i).getType())); parameterType.setName(inputParams.get(i).getType()); parameter.setParameterType(parameterType); inputParameterTypeArray[i] = parameter; } serviceDescription.getType().setInputParametersArray(inputParameterTypeArray); List<ServiceParameters> outputParams = serviceDescriptor.getOutputParams(); OutputParameterType[] outputParameterTypeArray = new OutputParameterType[outputParams.size()]; for (int i = 0; i < outputParams.size(); i++){ OutputParameterType parameter = OutputParameterType.Factory.newInstance(); parameter.setParameterName(outputParams.get(i).getName()); ParameterType parameterType = parameter.addNewParameterType(); parameterType.setType(DataType.Enum.forString(outputParams.get(i).getType())); parameterType.setName(outputParams.get(i).getType()); parameter.setParameterType(parameterType); outputParameterTypeArray[i] = parameter; } serviceDescription.getType().setOutputParametersArray(outputParameterTypeArray); return serviceDescription; } public static ServiceDescriptor createServiceDescriptor(ServiceDescription serviceDescription){ ServiceDescriptor serviceDescriptor = new ServiceDescriptor(); serviceDescriptor.setServiceName(serviceDescription.getType().getName()); serviceDescriptor.setDescription(serviceDescription.getType().getDescription()); InputParameterType[] inputParametersArray = serviceDescription.getType().getInputParametersArray(); OutputParameterType[] outputParametersArray = serviceDescription.getType().getOutputParametersArray(); List<ServiceParameters> inputParams = new ArrayList<ServiceParameters>(); List<ServiceParameters> outputParams = new ArrayList<ServiceParameters>(); for (int i = 0; i < inputParametersArray.length; i++){ ServiceParameters serviceParameters = new ServiceParameters(); serviceParameters.setType(inputParametersArray[i].getParameterType().getType().toString()); // String[] parameterValueArray = inputParametersArray[i].getParameterValueArray(); // if (parameterValueArray.length != 0){ // serviceParameters.setName(parameterValueArray[0]); // } serviceParameters.setName(inputParametersArray[i].getParameterName()); serviceParameters.setDescription(inputParametersArray[i].getParameterDescription()); // serviceParameters.set(inputParametersArray[i].getParameterType().getType().toString()); inputParams.add(serviceParameters); } serviceDescriptor.setInputParams(inputParams); for (int i = 0; i < outputParametersArray.length; i++){ ServiceParameters serviceParameters = new ServiceParameters(); serviceParameters.setType(outputParametersArray[i].getParameterType().getType().toString()); serviceParameters.setName(outputParametersArray[i].getParameterName()); serviceParameters.setDescription(outputParametersArray[i].getParameterDescription()); // serviceParameters.setDataType(outputParametersArray[i].getParameterType().getType().toString()); outputParams.add(serviceParameters); } serviceDescriptor.setOutputParams(outputParams); return serviceDescriptor; } public static ApplicationDeploymentDescription createApplicationDescription(ApplicationDescriptor applicationDescriptor){ ApplicationDeploymentDescription applicationDeploymentDescription = new ApplicationDeploymentDescription(); ApplicationDeploymentDescriptionType.ApplicationName name = ApplicationDeploymentDescriptionType.ApplicationName.Factory.newInstance(); name.setStringValue(applicationDescriptor.getName()); applicationDeploymentDescription.getType().setApplicationName(name); applicationDeploymentDescription.getType().setExecutableLocation(applicationDescriptor.getExecutablePath()); applicationDeploymentDescription.getType().setOutputDataDirectory(applicationDescriptor.getWorkingDir()); //set advanced options according app desc type if(applicationDescriptor.getApplicationDescType() != null && !applicationDescriptor.getApplicationDescType().isEmpty()){ if (applicationDescriptor.getApplicationDescType().equals(ApplicationDescriptorTypes.GRAM_APP_DEP_DESC_TYPE)){ ApplicationDeploymentDescription appDesc = new ApplicationDeploymentDescription(GramApplicationDeploymentType.type); appDesc.getType().setApplicationName(name); appDesc.getType().setExecutableLocation(applicationDescriptor.getExecutablePath()); appDesc.getType().setOutputDataDirectory(applicationDescriptor.getWorkingDir()); GramApplicationDeploymentType app = (GramApplicationDeploymentType) appDesc.getType(); app.setCpuCount(applicationDescriptor.getCpuCount()); app.setJobType(JobTypeType.Enum.forString(applicationDescriptor.getJobType())); app.setMaxMemory(applicationDescriptor.getMaxMemory()); app.setMinMemory(applicationDescriptor.getMinMemory()); app.setMaxWallTime(applicationDescriptor.getMaxWallTime()); app.setNodeCount(applicationDescriptor.getNodeCount()); app.setProcessorsPerNode(applicationDescriptor.getProcessorsPerNode()); return appDesc; } else if (applicationDescriptor.getApplicationDescType().equals(ApplicationDescriptorTypes.BATCH_APP_DEP_DESC_TYPE)){ ApplicationDeploymentDescription appDesc = new ApplicationDeploymentDescription(BatchApplicationDeploymentDescriptionType.type); appDesc.getType().setApplicationName(name); appDesc.getType().setExecutableLocation(applicationDescriptor.getExecutablePath()); appDesc.getType().setOutputDataDirectory(applicationDescriptor.getWorkingDir()); BatchApplicationDeploymentDescriptionType applicationDeploymentType = (BatchApplicationDeploymentDescriptionType) appDesc.getType(); applicationDeploymentType.setCpuCount(applicationDescriptor.getCpuCount()); applicationDeploymentType.setJobType(JobTypeType.Enum.forString(applicationDescriptor.getJobType())); applicationDeploymentType.setMaxMemory(applicationDescriptor.getMaxMemory()); applicationDeploymentType.setMinMemory(applicationDescriptor.getMinMemory()); applicationDeploymentType.setMaxWallTime(applicationDescriptor.getMaxWallTime()); applicationDeploymentType.setNodeCount(applicationDescriptor.getNodeCount()); applicationDeploymentType.setProcessorsPerNode(applicationDescriptor.getProcessorsPerNode()); return appDesc; } } return applicationDeploymentDescription; } public static ApplicationDescriptor createApplicationDescriptor (ApplicationDeploymentDescription applicationDeploymentDescription){ ApplicationDescriptor applicationDescriptor = new ApplicationDescriptor(); applicationDescriptor.setName(applicationDeploymentDescription.getType().getApplicationName().getStringValue()); applicationDescriptor.setExecutablePath(applicationDeploymentDescription.getType().getExecutableLocation()); applicationDescriptor.setWorkingDir(applicationDeploymentDescription.getType().getOutputDataDirectory()); if(applicationDeploymentDescription.getType() != null){ if(applicationDeploymentDescription.getType() instanceof GramApplicationDeploymentType){ GramApplicationDeploymentType gramApplicationDeploymentType = (GramApplicationDeploymentType)applicationDeploymentDescription.getType(); if(gramApplicationDeploymentType != null){ applicationDescriptor.setCpuCount(gramApplicationDeploymentType.getCpuCount()); applicationDescriptor.setNodeCount(gramApplicationDeploymentType.getNodeCount()); applicationDescriptor.setMaxMemory(gramApplicationDeploymentType.getMaxMemory()); applicationDescriptor.setMinMemory(gramApplicationDeploymentType.getMinMemory()); applicationDescriptor.setMaxWallTime(gramApplicationDeploymentType.getMaxWallTime()); if(gramApplicationDeploymentType.getQueue() != null){ applicationDescriptor.setQueueName(gramApplicationDeploymentType.getQueue().getQueueName()); } } } else if (applicationDeploymentDescription.getType() instanceof BatchApplicationDeploymentDescriptionType){ BatchApplicationDeploymentDescriptionType batchApplicationDeploymentDescriptionType = (BatchApplicationDeploymentDescriptionType)applicationDeploymentDescription.getType(); if (batchApplicationDeploymentDescriptionType != null){ applicationDescriptor.setCpuCount(batchApplicationDeploymentDescriptionType.getCpuCount()); applicationDescriptor.setNodeCount(batchApplicationDeploymentDescriptionType.getNodeCount()); applicationDescriptor.setMaxMemory(batchApplicationDeploymentDescriptionType.getMaxMemory()); applicationDescriptor.setMinMemory(batchApplicationDeploymentDescriptionType.getMinMemory()); applicationDescriptor.setMaxWallTime(batchApplicationDeploymentDescriptionType.getMaxWallTime()); if (batchApplicationDeploymentDescriptionType.getQueue() != null){ applicationDescriptor.setQueueName(batchApplicationDeploymentDescriptionType.getQueue().getQueueName()); } } } } return applicationDescriptor; } }
8,664
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/utils/HostTypes.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.services.registry.rest.utils; public class HostTypes { public static final String GLOBUS_HOST_TYPE = "GlobusHostType"; public static final String GSISSH_HOST_TYPE = "GsisshHostType"; public static final String EC2_HOST_TYPE = "Ec2HostType"; public static final String HOST_DESCRIPTION_TYPE = "HostDescriptionType"; }
8,665
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/utils/RegistryListener.java
package org.apache.airavata.services.registry.rest.utils; import org.apache.airavata.registry.api.AiravataRegistry2; import org.apache.airavata.registry.api.AiravataRegistryFactory; import org.apache.airavata.registry.api.AiravataUser; import org.apache.airavata.registry.api.Gateway; //import org.apache.airavata.client.AiravataClient; //import org.apache.airavata.client.AiravataClientUtils; //import org.apache.airavata.client.api.AiravataAPI; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.io.IOException; import java.net.URL; import java.util.Properties; public class RegistryListener implements ServletContextListener { private static AiravataRegistry2 airavataRegistry; public void contextInitialized(ServletContextEvent servletContextEvent) { try { ServletContext servletContext = servletContextEvent.getServletContext(); URL url = this.getClass().getClassLoader(). getResource(RestServicesConstants.AIRAVATA_SERVER_PROPERTIES); Properties properties = new Properties(); try { properties.load(url.openStream()); } catch (IOException e) { e.printStackTrace(); } String gatewayID = properties.getProperty(RestServicesConstants.GATEWAY_ID); String registryUser = properties.getProperty(RestServicesConstants.REGISTRY_USERNAME); Gateway gateway = new Gateway(gatewayID); AiravataUser airavataUser = new AiravataUser(registryUser) ; airavataRegistry = AiravataRegistryFactory.getRegistry(gateway, airavataUser); servletContext.setAttribute(RestServicesConstants.AIRAVATA_REGISTRY, airavataRegistry); servletContext.setAttribute(RestServicesConstants.GATEWAY, gateway); servletContext.setAttribute(RestServicesConstants.REGISTRY_USER, airavataUser); // AiravataAPI airavataAPI = AiravataClientUtils.getAPI(url.getPath()); // servletContext.setAttribute(RestServicesConstants.AIRAVATA_API, airavataAPI); } catch (Exception e) { e.printStackTrace(); } } public void contextDestroyed(ServletContextEvent servletContextEvent) { } }
8,666
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/utils/ResourcePathConstants.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.services.registry.rest.utils; public class ResourcePathConstants { public final class ConfigResourcePathConstants { public static final String CONFIGURATION_REGISTRY_RESOURCE = "/registry/api/congfigregistry/"; public static final String GET_CONFIGURATION = "get/configuration"; public static final String GET_CONFIGURATION_LIST = "get/configurationlist"; public static final String SAVE_CONFIGURATION = "save/configuration"; public static final String UPDATE_CONFIGURATION = "update/configuration"; public static final String DELETE_ALL_CONFIGURATION = "delete/allconfiguration"; public static final String DELETE_CONFIGURATION ="delete/configuration"; public static final String GET_GFAC_URI_LIST = "get/gfac/urilist"; public static final String GET_WFINTERPRETER_URI_LIST = "get/workflowinterpreter/urilist"; public static final String GET_EVENTING_URI = "get/eventingservice/uri"; public static final String GET_MESSAGE_BOX_URI = "get/messagebox/uri"; public static final String ADD_GFAC_URI = "add/gfacuri"; public static final String ADD_WFINTERPRETER_URI = "add/workflowinterpreteruri"; public static final String ADD_EVENTING_URI = "add/eventinguri"; public static final String ADD_MESSAGE_BOX_URI = "add/msgboxuri"; public static final String ADD_GFAC_URI_DATE = "add/gfacuri/date"; public static final String ADD_WFINTERPRETER_URI_DATE = "add/workflowinterpreteruri/date"; public static final String ADD_EVENTING_URI_DATE = "add/eventinguri/date"; public static final String ADD_MSG_BOX_URI_DATE = "add/msgboxuri/date"; public static final String DELETE_GFAC_URI = "delete/gfacuri"; public static final String DELETE_ALL_GFAC_URIS = "delete/allgfacuris"; public static final String DELETE_WFINTERPRETER_URI = "delete/workflowinterpreteruri"; public static final String DELETE_ALL_WFINTERPRETER_URIS = "delete/allworkflowinterpreteruris"; public static final String DELETE_EVENTING_URI = "delete/eventinguri"; public static final String DELETE_MSG_BOX_URI = "delete/msgboxuri"; } public final class DecResourcePathConstants { public static final String DESC_RESOURCE_PATH = "/registry/api/descriptors/"; public static final String HOST_DESC_EXISTS = "hostdescriptor/exist"; public static final String HOST_DESC_SAVE = "hostdescriptor/save"; public static final String HOST_DESC_UPDATE = "hostdescriptor/update"; public static final String HOST_DESC = "host/description"; public static final String HOST_DESC_DELETE = "hostdescriptor/delete"; public static final String GET_HOST_DESCS = "get/hostdescriptors"; public static final String GET_HOST_DESCS_NAMES = "get/hostdescriptor/names"; public static final String SERVICE_DESC_EXISTS = "servicedescriptor/exist"; public static final String SERVICE_DESC_SAVE = "servicedescriptor/save"; public static final String SERVICE_DESC_UPDATE = "servicedescriptor/update"; public static final String SERVICE_DESC = "servicedescriptor/description"; public static final String SERVICE_DESC_DELETE = "servicedescriptor/delete"; public static final String GET_SERVICE_DESCS = "get/servicedescriptors"; public static final String APPL_DESC_EXIST = "applicationdescriptor/exist"; public static final String APP_DESC_BUILD_SAVE = "applicationdescriptor/build/save"; public static final String APP_DESC_UPDATE = "applicationdescriptor/update"; public static final String APP_DESC_DESCRIPTION = "applicationdescriptor/description"; public static final String APP_DESC_PER_HOST_SERVICE = "applicationdescriptors/alldescriptors/host/service"; public static final String APP_DESC_ALL_DESCS_SERVICE = "applicationdescriptor/alldescriptors/service"; public static final String APP_DESC_ALL_DESCRIPTORS = "applicationdescriptor/alldescriptors"; public static final String APP_DESC_NAMES = "applicationdescriptor/names"; public static final String APP_DESC_DELETE = "applicationdescriptor/delete"; } public final class ExperimentResourcePathConstants { public static final String EXP_RESOURCE_PATH = "/registry/api/experimentregistry/"; public static final String DELETE_EXP = "delete/experiment"; public static final String GET_ALL_EXPS = "get/experiments/all" ; public static final String GET_EXPS_BY_PROJECT = "get/experiments/project" ; public static final String GET_EXPS_BY_DATE = "get/experiments/date"; public static final String GET_EXPS_PER_PROJECT_BY_DATE = "get/experiments/project/date"; public static final String ADD_EXP = "add/experiment" ; public static final String EXP_EXISTS = "experiment/exist" ; public static final String EXP_EXISTS_CREATE = "experiment/notexist/create" ; } public final class ProjectResourcePathConstants { public static final String REGISTRY_API_PROJECTREGISTRY = "/registry/api/projectregistry/"; public static final String PROJECT_EXIST = "project/exist"; public static final String PROJECT_EXIST_CREATE = "project/exist"; public static final String ADD_PROJECT = "add/project"; public static final String UPDATE_PROJECT = "update/project"; public static final String DELETE_PROJECT = "delete/project"; public static final String GET_PROJECT = "get/project"; public static final String GET_PROJECTS = "get/projects"; } public final class ProvenanceResourcePathConstants { public static final String REGISTRY_API_PROVENANCEREGISTRY = "/registry/api/provenanceregistry/"; public static final String UPDATE_EXPERIMENT_EXECUTIONUSER = "update/experiment/executionuser"; public static final String GET_EXPERIMENT_EXECUTIONUSER = "get/experiment/executionuser"; public static final String GET_EXPERIMENT_NAME = "get/experiment/name"; public static final String UPDATE_EXPERIMENTNAME = "update/experimentname"; public static final String GET_EXPERIMENTMETADATA = "get/experimentmetadata"; public static final String UPDATE_EXPERIMENTMETADATA = "update/experimentmetadata"; public static final String GET_WORKFLOWTEMPLATENAME = "get/workflowtemplatename"; public static final String UPDATE_WORKFLOWINSTANCETEMPLATENAME = "update/workflowinstancetemplatename"; public static final String GET_EXPERIMENTWORKFLOWINSTANCES = "get/experimentworkflowinstances"; public static final String WORKFLOWINSTANCE_EXIST_CHECK = "workflowinstance/exist/check"; public static final String WORKFLOWINSTANCE_EXIST_CREATE = "workflowinstance/exist/create"; public static final String UPDATE_WORKFLOWINSTANCESTATUS_INSTANCEID = "update/workflowinstancestatus/instanceid"; public static final String UPDATE_WORKFLOWINSTANCESTATUS = "update/workflowinstancestatus"; public static final String GET_WORKFLOWINSTANCESTATUS = "get/workflowinstancestatus"; public static final String UPDATE_WORKFLOWNODEINPUT = "update/workflownodeinput"; public static final String UPDATE_WORKFLOWNODEOUTPUT = "update/workflownodeoutput"; public static final String GET_EXPERIMENT = "get/experiment"; public static final String GET_EXPERIMENT_ID_USER = "get/experimentId/user"; public static final String GET_EXPERIMENT_USER = "get/experiment/user"; public static final String UPDATE_WORKFLOWNODE_STATUS = "update/workflownode/status"; public static final String GET_WORKFLOWNODE_STATUS = "get/workflownode/status"; public static final String GET_WORKFLOWNODE_STARTTIME = "get/workflownode/starttime"; public static final String GET_WORKFLOW_STARTTIME = "get/workflow/starttime"; public static final String UPDATE_WORKFLOWNODE_GRAMDATA = "update/workflownode/gramdata"; public static final String GET_WORKFLOWINSTANCEDATA = "get/workflowinstancedata"; public static final String WORKFLOWINSTANCE_NODE_EXIST = "wfnode/exist"; public static final String WORKFLOWINSTANCE_NODE_EXIST_CREATE = "wfnode/exist/create"; public static final String WORKFLOWINSTANCE_NODE_DATA = "workflowinstance/nodeData"; public static final String ADD_WORKFLOWINSTANCE = "add/workflowinstance"; public static final String UPDATE_WORKFLOWNODETYPE = "update/workflownodetype"; public static final String ADD_WORKFLOWINSTANCENODE = "add/workflowinstancenode"; public static final String EXPERIMENTNAME_EXISTS = "experimentname/exists"; public static final String GET_EXPERIMENT_METAINFORMATION = "get/experiment/metainformation"; public static final String GET_ALL_EXPERIMENT_METAINFORMATION = "get/all/experiment/metainformation"; public static final String SEARCH_EXPERIMENTS = "search/experiments"; } public final class PublishedWFConstants { public static final String REGISTRY_API_PUBLISHWFREGISTRY = "/registry/api/publishwfregistry/"; public static final String PUBLISHWF_EXIST = "publishwf/exist"; public static final String PUBLISH_WORKFLOW = "publish/workflow"; public static final String PUBLISH_DEFAULT_WORKFLOW = "publish/default/workflow"; public static final String GET_PUBLISHWORKFLOWGRAPH = "get/publishworkflowgraph"; public static final String GET_PUBLISHWORKFLOWNAMES = "get/publishworkflownames"; public static final String GET_PUBLISHWORKFLOWS = "get/publishworkflows"; public static final String REMOVE_PUBLISHWORKFLOW = "remove/publishworkflow"; } public final class UserWFConstants { public static final String REGISTRY_API_USERWFREGISTRY = "/registry/api/userwfregistry/"; public static final String WORKFLOW_EXIST = "workflow/exist"; public static final String ADD_WORKFLOW = "add/workflow"; public static final String UPDATE_WORKFLOW = "update/workflow"; public static final String GET_WORKFLOWGRAPH = "get/workflowgraph"; public static final String GET_WORKFLOWS = "get/workflows"; public static final String REMOVE_WORKFLOW = "remove/workflow"; } }
8,667
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/ExperimentIDList.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.services.registry.rest.resourcemappings; import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; @XmlRootElement(name = "experiments") public class ExperimentIDList { List<String> experimentIDList = new ArrayList<String>(); public ExperimentIDList() { } public List<String> getExperimentIDList() { return experimentIDList; } public void setExperimentIDList(List<String> experimentIDList) { this.experimentIDList = experimentIDList; } }
8,668
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/WorkflowNodeIODataList.java
package org.apache.airavata.services.registry.rest.resourcemappings; import org.apache.airavata.registry.api.workflow.WorkflowNodeIOData; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class WorkflowNodeIODataList { WorkflowNodeIOData[] workflowNodeIOData = new WorkflowNodeIOData[]{}; public WorkflowNodeIOData[] getWorkflowNodeIOData() { return workflowNodeIOData; } public void setWorkflowNodeIOData(WorkflowNodeIOData[] workflowNodeIOData) { this.workflowNodeIOData = workflowNodeIOData; } }
8,669
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/PublishWorkflowNamesList.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.services.registry.rest.resourcemappings; import java.util.ArrayList; import java.util.List; public class PublishWorkflowNamesList { private List<String> publishWorkflowNames = new ArrayList<String>(); public PublishWorkflowNamesList() { } public List<String> getPublishWorkflowNames() { return publishWorkflowNames; } public void setPublishWorkflowNames(List<String> publishWorkflowNames) { this.publishWorkflowNames = publishWorkflowNames; } }
8,670
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/DescriptorNameList.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.services.registry.rest.resourcemappings; import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; @XmlRootElement public class DescriptorNameList { private List<String> descriptorNames = new ArrayList<String>(); public DescriptorNameList() { } public List<String> getDescriptorNames() { return descriptorNames; } public void setDescriptorNames(List<String> descriptorNames) { this.descriptorNames = descriptorNames; } }
8,671
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/HostDescriptionList.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.services.registry.rest.resourcemappings; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class HostDescriptionList { private HostDescriptor[] hostDescriptions = new HostDescriptor[]{}; public HostDescriptor[] getHostDescriptions() { return hostDescriptions; } public void setHostDescriptions(HostDescriptor[] hostDescriptions) { this.hostDescriptions = hostDescriptions; } }
8,672
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/ServiceDescriptor.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.services.registry.rest.resourcemappings; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "service") public class ServiceDescriptor { private String serviceName; private String description; private List<ServiceParameters> inputParams = new ArrayList<ServiceParameters>(); private List<ServiceParameters> outputParams = new ArrayList<ServiceParameters>(); public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public List<ServiceParameters> getInputParams() { return inputParams; } public void setInputParams(List<ServiceParameters> inputParams) { this.inputParams = inputParams; } public List<ServiceParameters> getOutputParams() { return outputParams; } public void setOutputParams(List<ServiceParameters> outputParams) { this.outputParams = outputParams; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
8,673
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/ApplicationDescriptorList.java
package org.apache.airavata.services.registry.rest.resourcemappings; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class ApplicationDescriptorList { private ApplicationDescriptor[] applicationDescriptors = new ApplicationDescriptor[]{}; public ApplicationDescriptorList() { } public ApplicationDescriptor[] getApplicationDescriptors() { return applicationDescriptors; } public void setApplicationDescriptors(ApplicationDescriptor[] applicationDescriptors) { this.applicationDescriptors = applicationDescriptors; } }
8,674
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/URLList.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.services.registry.rest.resourcemappings; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class URLList { private String[] uris = new String[]{}; public String[] getUris() { return uris; } public void setUris(String[] uris) { this.uris = uris; } }
8,675
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/ServiceDescriptionList.java
package org.apache.airavata.services.registry.rest.resourcemappings; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class ServiceDescriptionList { private ServiceDescriptor[] serviceDescriptions = new ServiceDescriptor[]{}; public ServiceDescriptor[] getServiceDescriptions() { return serviceDescriptions; } public void setServiceDescriptions(ServiceDescriptor[] serviceDescriptions) { this.serviceDescriptions = serviceDescriptions; } }
8,676
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/WorkspaceProjectList.java
package org.apache.airavata.services.registry.rest.resourcemappings; import org.apache.airavata.registry.api.WorkspaceProject; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class WorkspaceProjectList { private WorkspaceProject[] workspaceProjects = new WorkspaceProject[]{}; public WorkspaceProjectList() { } public WorkspaceProject[] getWorkspaceProjects() { return workspaceProjects; } public void setWorkspaceProjects(WorkspaceProject[] workspaceProjects) { this.workspaceProjects = workspaceProjects; } }
8,677
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/HostDescriptor.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.services.registry.rest.resourcemappings; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; @XmlRootElement(name = "host") @XmlAccessorType(XmlAccessType.FIELD) public class HostDescriptor { private String hostname; private String hostAddress; private List<String> hostType = new ArrayList<String>(); private List<String> gridFTPEndPoint = new ArrayList<String>(); private List<String> globusGateKeeperEndPoint = new ArrayList<String>(); private List<String> imageID = new ArrayList<String>(); private List<String> instanceID = new ArrayList<String>(); public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public String getHostAddress() { return hostAddress; } public void setHostAddress(String hostAddress) { this.hostAddress = hostAddress; } public List<String> getHostType() { return hostType; } public void setHostType(List<String> hostType) { this.hostType = hostType; } public List<String> getGridFTPEndPoint() { return gridFTPEndPoint; } public void setGridFTPEndPoint(List<String> gridFTPEndPoint) { this.gridFTPEndPoint = gridFTPEndPoint; } public List<String> getGlobusGateKeeperEndPoint() { return globusGateKeeperEndPoint; } public void setGlobusGateKeeperEndPoint(List<String> globusGateKeeperEndPoint) { this.globusGateKeeperEndPoint = globusGateKeeperEndPoint; } public List<String> getImageID() { return imageID; } public void setImageID(List<String> imageID) { this.imageID = imageID; } public List<String> getInstanceID() { return instanceID; } public void setInstanceID(List<String> instanceID) { this.instanceID = instanceID; } }
8,678
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/WorkflowList.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.services.registry.rest.resourcemappings; import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; @XmlRootElement public class WorkflowList { private List<Workflow> workflowList = new ArrayList<Workflow>(); public WorkflowList() { } public List<Workflow> getWorkflowList() { return workflowList; } public void setWorkflowList(List<Workflow> workflowList) { this.workflowList = workflowList; } }
8,679
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/ExperimentDataList.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.services.registry.rest.resourcemappings; import org.apache.airavata.registry.api.impl.ExperimentDataImpl; import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; @XmlRootElement public class ExperimentDataList { private List<ExperimentDataImpl> experimentDataList = new ArrayList<ExperimentDataImpl>(); public ExperimentDataList() { } public List<ExperimentDataImpl> getExperimentDataList() { return experimentDataList; } public void setExperimentDataList(List<ExperimentDataImpl> experimentDataList) { this.experimentDataList = experimentDataList; } }
8,680
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/ServiceParameters.java
package org.apache.airavata.services.registry.rest.resourcemappings; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class ServiceParameters { // whether string or other type String type; String name; //whether it is input or output String dataType; String description; public String getType() { return type; } public void setType(String type) { this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
8,681
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/ExperimentList.java
package org.apache.airavata.services.registry.rest.resourcemappings; import org.apache.airavata.registry.api.AiravataExperiment; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class ExperimentList { private AiravataExperiment[] experiments = new AiravataExperiment[]{}; public ExperimentList() { } public AiravataExperiment[] getExperiments() { return experiments; } public void setExperiments(AiravataExperiment[] experiments) { this.experiments = experiments; } }
8,682
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/ConfigurationList.java
package org.apache.airavata.services.registry.rest.resourcemappings; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class ConfigurationList { private Object[] configValList = new Object[]{}; public Object[] getConfigValList() { return configValList; } public void setConfigValList(Object[] configValList) { this.configValList = configValList; } }
8,683
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/WorkflowInstancesList.java
package org.apache.airavata.services.registry.rest.resourcemappings; import org.apache.airavata.registry.api.workflow.WorkflowInstance; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class WorkflowInstancesList { WorkflowInstance[] workflowInstances = new WorkflowInstance[]{}; public WorkflowInstance[] getWorkflowInstances() { return workflowInstances; } public void setWorkflowInstances(WorkflowInstance[] workflowInstances) { this.workflowInstances = workflowInstances; } }
8,684
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/Workflow.java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.services.registry.rest.resourcemappings; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Workflow { private String workflowName; private String workflowGraph; public Workflow() { } public String getWorkflowName() { return workflowName; } public String getWorkflowGraph() { return workflowGraph; } public void setWorkflowName(String workflowName) { this.workflowName = workflowName; } public void setWorkflowGraph(String workflowGraph) { this.workflowGraph = workflowGraph; } }
8,685
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/resourcemappings/ApplicationDescriptor.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.services.registry.rest.resourcemappings; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "application") public class ApplicationDescriptor { private String name; private String hostdescName; // private String serviceName; private String executablePath; private String workingDir; private String jobType; private String projectNumber; private String queueName; private int maxWallTime; private int cpuCount; private int nodeCount; private int processorsPerNode; private int minMemory; private int maxMemory; private String applicationDescType; private ServiceDescriptor serviceDescriptor; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHostdescName() { return hostdescName; } public void setHostdescName(String hostdescName) { this.hostdescName = hostdescName; } // public String getServiceName() { // return serviceName; // } // // public void setServiceName(String serviceName) { // this.serviceName = serviceName; // } public String getExecutablePath() { return executablePath; } public void setExecutablePath(String executablePath) { this.executablePath = executablePath; } public String getWorkingDir() { return workingDir; } public void setWorkingDir(String workingDir) { this.workingDir = workingDir; } public String getJobType() { return jobType; } public void setJobType(String jobType) { this.jobType = jobType; } public String getProjectNumber() { return projectNumber; } public void setProjectNumber(String projectNumber) { this.projectNumber = projectNumber; } public String getQueueName() { return queueName; } public void setQueueName(String queueName) { this.queueName = queueName; } public int getMaxWallTime() { return maxWallTime; } public void setMaxWallTime(int maxWallTime) { this.maxWallTime = maxWallTime; } public int getCpuCount() { return cpuCount; } public void setCpuCount(int cpuCount) { this.cpuCount = cpuCount; } public int getNodeCount() { return nodeCount; } public void setNodeCount(int nodeCount) { this.nodeCount = nodeCount; } public int getProcessorsPerNode() { return processorsPerNode; } public void setProcessorsPerNode(int processorsPerNode) { this.processorsPerNode = processorsPerNode; } public int getMinMemory() { return minMemory; } public void setMinMemory(int minMemory) { this.minMemory = minMemory; } public int getMaxMemory() { return maxMemory; } public void setMaxMemory(int maxMemory) { this.maxMemory = maxMemory; } public String getApplicationDescType() { return applicationDescType; } public void setApplicationDescType(String applicationDescType) { this.applicationDescType = applicationDescType; } public ServiceDescriptor getServiceDescriptor() { return serviceDescriptor; } public void setServiceDescriptor(ServiceDescriptor serviceDescriptor) { this.serviceDescriptor = serviceDescriptor; } }
8,686
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/client/PublishedWorkflowResourceClient.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.services.registry.rest.client; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.airavata.services.registry.rest.resourcemappings.PublishWorkflowNamesList; import org.apache.airavata.services.registry.rest.resourcemappings.Workflow; import org.apache.airavata.services.registry.rest.resourcemappings.WorkflowList; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; public class PublishedWorkflowResourceClient { private WebResource webResource; private final static Logger logger = LoggerFactory.getLogger(PublishedWorkflowResourceClient.class); private URI getBaseURI() { logger.info("Creating Base URI"); return UriBuilder.fromUri("http://localhost:9080/airavata-services/").build(); } private WebResource getPublishedWFRegistryBaseResource (){ ClientConfig config = new DefaultClientConfig(); config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(config); WebResource baseWebResource = client.resource(getBaseURI()); webResource = baseWebResource.path(ResourcePathConstants.PublishedWFConstants.REGISTRY_API_PUBLISHWFREGISTRY); return webResource; } public boolean isPublishedWorkflowExists(String workflowName){ webResource = getPublishedWFRegistryBaseResource().path(ResourcePathConstants.PublishedWFConstants.PUBLISHWF_EXIST); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowname", workflowName); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } return true; } public void publishWorkflow(String workflowName, String publishWorkflowName){ webResource = getPublishedWFRegistryBaseResource().path(ResourcePathConstants.PublishedWFConstants.PUBLISH_WORKFLOW); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("workflowName", workflowName); formParams.add("publishWorkflowName", publishWorkflowName); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void publishWorkflow(String workflowName){ webResource = getPublishedWFRegistryBaseResource().path(ResourcePathConstants.PublishedWFConstants.PUBLISH_DEFAULT_WORKFLOW); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("workflowName", workflowName); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public String getPublishedWorkflowGraphXML(String workflowName){ webResource = getPublishedWFRegistryBaseResource().path(ResourcePathConstants.PublishedWFConstants.GET_PUBLISHWORKFLOWGRAPH); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowname", workflowName); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } String wfGraph = response.getEntity(String.class); return wfGraph; } public List<String> getPublishedWorkflowNames(){ webResource = getPublishedWFRegistryBaseResource().path(ResourcePathConstants.PublishedWFConstants.GET_PUBLISHWORKFLOWNAMES); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } PublishWorkflowNamesList workflowNamesList = response.getEntity(PublishWorkflowNamesList.class); List<String> publishWorkflowNames = workflowNamesList.getPublishWorkflowNames(); return publishWorkflowNames; } public Map<String, String> getPublishedWorkflows(){ webResource = getPublishedWFRegistryBaseResource().path(ResourcePathConstants.PublishedWFConstants.GET_PUBLISHWORKFLOWS); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } Map<String, String> publishWFmap = new HashMap<String, String>(); WorkflowList workflowList = response.getEntity(WorkflowList.class); List<Workflow> workflows = workflowList.getWorkflowList(); for (Workflow workflow : workflows){ publishWFmap.put(workflow.getWorkflowName(), workflow.getWorkflowGraph()); } return publishWFmap; } public void removePublishedWorkflow(String workflowName){ webResource = getPublishedWFRegistryBaseResource().path(ResourcePathConstants.PublishedWFConstants.REMOVE_PUBLISHWORKFLOW); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowname", workflowName); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } }
8,687
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/client/DescriptorResourceClient.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.services.registry.rest.client; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.airavata.commons.gfac.type.ApplicationDeploymentDescription; import org.apache.airavata.commons.gfac.type.HostDescription; import org.apache.airavata.commons.gfac.type.ServiceDescription; import org.apache.airavata.services.registry.rest.resourcemappings.*; import org.apache.airavata.services.registry.rest.utils.DescriptorUtil; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider; import org.codehaus.jackson.jaxrs.JacksonJsonProvider; import org.codehaus.jackson.map.DeserializationConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class DescriptorResourceClient { private WebResource webResource; private final static Logger logger = LoggerFactory.getLogger(DescriptorResourceClient.class); private URI getBaseURI() { logger.info("Creating Base URI"); return UriBuilder.fromUri("http://localhost:9080/airavata-services/").build(); } private WebResource getDescriptorRegistryBaseResource (){ ClientConfig config = new DefaultClientConfig(); config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(config); WebResource baseWebResource = client.resource(getBaseURI()); webResource = baseWebResource.path(ResourcePathConstants.DecResourcePathConstants.DESC_RESOURCE_PATH); return webResource; } public boolean isHostDescriptorExists(String hostDescriptorName){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.HOST_DESC_EXISTS); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("hostDescriptorName", hostDescriptorName); ClientResponse response = webResource.queryParams(queryParams).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } else { return true; } } public void addHostDescriptor (HostDescription hostDescription){ HostDescriptor hostDescriptor = DescriptorUtil.createHostDescriptor(hostDescription); webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.HOST_DESC_SAVE); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, hostDescriptor); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void updateHostDescriptor (HostDescription hostDescription){ HostDescriptor hostDescriptor = DescriptorUtil.createHostDescriptor(hostDescription); webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.HOST_DESC_UPDATE); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, hostDescriptor); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public HostDescription getHostDescriptor (String hostName){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.HOST_DESC); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("hostName", hostName); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } HostDescriptor hostDescriptor = response.getEntity(HostDescriptor.class); HostDescription hostDescription = DescriptorUtil.createHostDescription(hostDescriptor); return hostDescription; } public void removeHostDescriptor(String hostName){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.HOST_DESC_DELETE); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("hostName", hostName); ClientResponse response = webResource.queryParams(queryParams).delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public List<HostDescription> getHostDescriptors() { webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.GET_HOST_DESCS); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } HostDescriptionList hostDescriptionList = response.getEntity(HostDescriptionList.class); HostDescriptor[] hostDescriptors = hostDescriptionList.getHostDescriptions(); List<HostDescription> hostDescriptions = new ArrayList<HostDescription>(); for (HostDescriptor hostDescriptor : hostDescriptors){ HostDescription hostDescription = DescriptorUtil.createHostDescription(hostDescriptor); hostDescriptions.add(hostDescription); } return hostDescriptions; } public List<String> getHostDescriptorNames(){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.GET_HOST_DESCS_NAMES); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } DescriptorNameList descriptorNameList = response.getEntity(DescriptorNameList.class); return descriptorNameList.getDescriptorNames(); } public boolean isServiceDescriptorExists(String serviceDescriptorName){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.SERVICE_DESC_EXISTS); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("serviceDescriptorName", serviceDescriptorName); ClientResponse response = webResource.queryParams(queryParams).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } else { return true; } } public void saveServiceDescriptor (ServiceDescription serviceDescription){ ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.SERVICE_DESC_SAVE); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, serviceDescriptor); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void updateServiceDescriptor(ServiceDescription serviceDescription){ ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.SERVICE_DESC_UPDATE); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, serviceDescriptor); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public ServiceDescription getServiceDescriptor (String serviceName){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.SERVICE_DESC); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("serviceName", serviceName); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ServiceDescriptor serviceDescriptor = response.getEntity(ServiceDescriptor.class); ServiceDescription serviceDescription = DescriptorUtil.createServiceDescription(serviceDescriptor); return serviceDescription; } public void removeServiceDescriptor(String serviceName){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.SERVICE_DESC_DELETE); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("serviceName", serviceName); ClientResponse response = webResource.queryParams(queryParams).delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public List<ServiceDescription> getServiceDescriptors (){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.GET_SERVICE_DESCS); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ServiceDescriptionList serviceDescriptionList = response.getEntity(ServiceDescriptionList.class); ServiceDescriptor[] serviceDescriptors = serviceDescriptionList.getServiceDescriptions(); List<ServiceDescription> serviceDescriptions = new ArrayList<ServiceDescription>(); for (ServiceDescriptor serviceDescriptor : serviceDescriptors){ ServiceDescription serviceDescription = DescriptorUtil.createServiceDescription(serviceDescriptor); serviceDescriptions.add(serviceDescription); } return serviceDescriptions; } public boolean isApplicationDescriptorExist (String serviceName, String hostName, String appDescriptorName){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.APPL_DESC_EXIST); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("serviceName", serviceName); queryParams.add("hostName", hostName); queryParams.add("appDescName", appDescriptorName); ClientResponse response = webResource.queryParams(queryParams).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } else { return true; } } public void addApplicationDescriptor(ServiceDescription serviceDescription, HostDescription hostDescriptor, ApplicationDeploymentDescription descriptor){ ApplicationDescriptor applicationDescriptor = DescriptorUtil.createApplicationDescriptor(descriptor); applicationDescriptor.setHostdescName(hostDescriptor.getType().getHostName()); ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); applicationDescriptor.setServiceDescriptor(serviceDescriptor); webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_BUILD_SAVE); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, applicationDescriptor); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void addApplicationDescriptor(String serviceName, String hostName, ApplicationDeploymentDescription descriptor){ ServiceDescription serviceDescription = getServiceDescriptor(serviceName); ApplicationDescriptor applicationDescriptor = DescriptorUtil.createApplicationDescriptor(descriptor); applicationDescriptor.setHostdescName(hostName); ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); applicationDescriptor.setServiceDescriptor(serviceDescriptor); webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_BUILD_SAVE); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, applicationDescriptor); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void udpateApplicationDescriptor(ServiceDescription serviceDescription, HostDescription hostDescriptor, ApplicationDeploymentDescription descriptor){ ApplicationDescriptor applicationDescriptor = DescriptorUtil.createApplicationDescriptor(descriptor); applicationDescriptor.setHostdescName(hostDescriptor.getType().getHostName()); ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); applicationDescriptor.setServiceDescriptor(serviceDescriptor); webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_UPDATE); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, applicationDescriptor); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void updateApplicationDescriptor(String serviceName, String hostName, ApplicationDeploymentDescription descriptor){ ServiceDescription serviceDescription = getServiceDescriptor(serviceName); ApplicationDescriptor applicationDescriptor = DescriptorUtil.createApplicationDescriptor(descriptor); applicationDescriptor.setHostdescName(hostName); ServiceDescriptor serviceDescriptor = DescriptorUtil.createServiceDescriptor(serviceDescription); applicationDescriptor.setServiceDescriptor(serviceDescriptor); webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_UPDATE); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, applicationDescriptor); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public ApplicationDeploymentDescription getApplicationDescriptor(String serviceName, String hostname, String applicationName){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_DESCRIPTION); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("serviceName", serviceName); queryParams.add("hostName", hostname); queryParams.add("applicationName", applicationName); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ApplicationDescriptor applicationDescriptor = response.getEntity(ApplicationDescriptor.class); ApplicationDeploymentDescription applicationDeploymentDescription = DescriptorUtil.createApplicationDescription(applicationDescriptor); return applicationDeploymentDescription; } public ApplicationDeploymentDescription getApplicationDescriptors(String serviceName, String hostname){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_PER_HOST_SERVICE); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("serviceName", serviceName); queryParams.add("hostName", hostname); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ApplicationDescriptor applicationDescriptor = response.getEntity(ApplicationDescriptor.class); ApplicationDeploymentDescription applicationDeploymentDescription = DescriptorUtil.createApplicationDescription(applicationDescriptor); return applicationDeploymentDescription; } public Map<String, ApplicationDeploymentDescription> getApplicationDescriptors(String serviceName){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_ALL_DESCS_SERVICE); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("serviceName", serviceName); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ApplicationDescriptorList applicationDescriptorList = response.getEntity(ApplicationDescriptorList.class); ApplicationDescriptor[] applicationDescriptors = applicationDescriptorList.getApplicationDescriptors(); Map<String, ApplicationDeploymentDescription> applicationDeploymentDescriptionMap = new HashMap<String, ApplicationDeploymentDescription>(); for (ApplicationDescriptor applicationDescriptor : applicationDescriptors){ ApplicationDeploymentDescription applicationDeploymentDescription = DescriptorUtil.createApplicationDescription(applicationDescriptor); applicationDeploymentDescriptionMap.put(applicationDescriptor.getHostdescName(), applicationDeploymentDescription); } return applicationDeploymentDescriptionMap; } public Map<String[], ApplicationDeploymentDescription> getApplicationDescriptors(){ Map<String[], ApplicationDeploymentDescription> applicationDeploymentDescriptionMap = new HashMap<String[], ApplicationDeploymentDescription>(); webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_ALL_DESCRIPTORS); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ApplicationDescriptorList applicationDescriptorList = response.getEntity(ApplicationDescriptorList.class); ApplicationDescriptor[] applicationDescriptors = applicationDescriptorList.getApplicationDescriptors(); for (ApplicationDescriptor applicationDescriptor : applicationDescriptors){ ApplicationDeploymentDescription applicationDeploymentDescription = DescriptorUtil.createApplicationDescription(applicationDescriptor); String[] descriptors = {applicationDescriptor.getServiceDescriptor().getServiceName(), applicationDescriptor.getHostdescName()}; applicationDeploymentDescriptionMap.put(descriptors, applicationDeploymentDescription); } return applicationDeploymentDescriptionMap; } private List<String> getApplicationDescriptorNames (){ webResource = getDescriptorRegistryBaseResource().path(ResourcePathConstants.DecResourcePathConstants.APP_DESC_NAMES); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } DescriptorNameList descriptorNameList = response.getEntity(DescriptorNameList.class); return descriptorNameList.getDescriptorNames(); } }
8,688
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/client/ExperimentResourceClient.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.services.registry.rest.client; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.airavata.registry.api.AiravataExperiment; import org.apache.airavata.services.registry.rest.resourcemappings.ExperimentList; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ExperimentResourceClient { private WebResource webResource; private final static Logger logger = LoggerFactory.getLogger(ExperimentResourceClient.class); private URI getBaseURI() { logger.info("Creating Base URI"); return UriBuilder.fromUri("http://localhost:9080/airavata-services/").build(); } private WebResource getExperimentRegistryBaseResource (){ ClientConfig config = new DefaultClientConfig(); config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(config); WebResource baseWebResource = client.resource(getBaseURI()); webResource = baseWebResource.path(ResourcePathConstants.ExperimentResourcePathConstants.EXP_RESOURCE_PATH); return webResource; } public void addExperiment(String projectName, AiravataExperiment experiment){ webResource = getExperimentRegistryBaseResource().path(ResourcePathConstants.ExperimentResourcePathConstants.ADD_EXP); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("projectName", projectName); formParams.add("experimentID", experiment.getExperimentId()); formParams.add("submittedDate", experiment.getSubmittedDate().toString()); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void removeExperiment(String experimentId){ webResource = getExperimentRegistryBaseResource().path(ResourcePathConstants.ExperimentResourcePathConstants.DELETE_EXP); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("experimentId", experimentId); ClientResponse response = webResource.queryParams(queryParams).delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public List<AiravataExperiment> getExperiments(){ webResource = getExperimentRegistryBaseResource().path(ResourcePathConstants.ExperimentResourcePathConstants.GET_ALL_EXPS); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ExperimentList experimentList = response.getEntity(ExperimentList.class); AiravataExperiment[] experiments = experimentList.getExperiments(); List<AiravataExperiment> airavataExperiments = new ArrayList<AiravataExperiment>(); for (AiravataExperiment airavataExperiment : experiments){ airavataExperiments.add(airavataExperiment); } return airavataExperiments; } public List<AiravataExperiment> getExperiments(String projectName){ webResource = getExperimentRegistryBaseResource().path(ResourcePathConstants.ExperimentResourcePathConstants.GET_EXPS_BY_PROJECT); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("projectName", projectName); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ExperimentList experimentList = response.getEntity(ExperimentList.class); AiravataExperiment[] experiments = experimentList.getExperiments(); List<AiravataExperiment> airavataExperiments = new ArrayList<AiravataExperiment>(); for (AiravataExperiment airavataExperiment : experiments){ airavataExperiments.add(airavataExperiment); } return airavataExperiments; } public List<AiravataExperiment> getExperiments(Date from, Date to){ webResource = getExperimentRegistryBaseResource().path(ResourcePathConstants.ExperimentResourcePathConstants.GET_EXPS_BY_DATE); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("fromDate", from.toString()); queryParams.add("toDate", to.toString()); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ExperimentList experimentList = response.getEntity(ExperimentList.class); AiravataExperiment[] experiments = experimentList.getExperiments(); List<AiravataExperiment> airavataExperiments = new ArrayList<AiravataExperiment>(); for (AiravataExperiment airavataExperiment : experiments){ airavataExperiments.add(airavataExperiment); } return airavataExperiments; } public List<AiravataExperiment> getExperiments(String projectName, Date from, Date to){ webResource = getExperimentRegistryBaseResource().path(ResourcePathConstants.ExperimentResourcePathConstants.GET_EXPS_PER_PROJECT_BY_DATE); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("projectName", projectName); queryParams.add("fromDate", from.toString()); queryParams.add("toDate", to.toString()); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ExperimentList experimentList = response.getEntity(ExperimentList.class); AiravataExperiment[] experiments = experimentList.getExperiments(); List<AiravataExperiment> airavataExperiments = new ArrayList<AiravataExperiment>(); for (AiravataExperiment airavataExperiment : experiments){ airavataExperiments.add(airavataExperiment); } return airavataExperiments; } public boolean isExperimentExists(String experimentId){ webResource = getExperimentRegistryBaseResource().path(ResourcePathConstants.ExperimentResourcePathConstants.EXP_EXISTS); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("experimentId", experimentId); ClientResponse response = webResource.queryParams(queryParams).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); }else { return true; } } public boolean isExperimentExists(String experimentId, boolean createIfNotPresent){ String createStatus = "false"; webResource = getExperimentRegistryBaseResource().path(ResourcePathConstants.ExperimentResourcePathConstants.EXP_EXISTS_CREATE); if (createIfNotPresent){ createStatus = "true"; } MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("experimentId", experimentId ); formParams.add("createIfNotPresent", createStatus ); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); }else { return true; } } }
8,689
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/client/ProvenanceResourceClient.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.services.registry.rest.client; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.airavata.registry.api.impl.ExperimentDataImpl; import org.apache.airavata.registry.api.workflow.*; import org.apache.airavata.services.registry.rest.resourcemappings.ExperimentDataList; import org.apache.airavata.services.registry.rest.resourcemappings.ExperimentIDList; import org.apache.airavata.services.registry.rest.resourcemappings.WorkflowInstancesList; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ProvenanceResourceClient { private WebResource webResource; private final static Logger logger = LoggerFactory.getLogger(ProvenanceResourceClient.class); private URI getBaseURI() { logger.info("Creating Base URI"); return UriBuilder.fromUri("http://localhost:9080/airavata-services/").build(); } private WebResource getProvenanceRegistryBaseResource (){ ClientConfig config = new DefaultClientConfig(); config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(config); WebResource baseWebResource = client.resource(getBaseURI()); webResource = baseWebResource.path(ResourcePathConstants.ProvenanceResourcePathConstants.REGISTRY_API_PROVENANCEREGISTRY); return webResource; } public void updateExperimentExecutionUser(String experimentId, String user){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_EXPERIMENT_EXECUTIONUSER); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("experimentId", experimentId); formParams.add("user", user); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public String getExperimentExecutionUser(String experimentId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENT_EXECUTIONUSER); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("experimentId", experimentId); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } String executionUser = response.getEntity(String.class); return executionUser; } public boolean isExperimentNameExist(String experimentName){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.EXPERIMENTNAME_EXISTS); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("experimentName", experimentName); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } return true; } public String getExperimentName(String experimentId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENT_NAME); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("experimentId", experimentId); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } String experimentName = response.getEntity(String.class); return experimentName; } public void updateExperimentName(String experimentId, String experimentName){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_EXPERIMENTNAME); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("experimentId", experimentId); formParams.add("experimentName", experimentName); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public String getExperimentMetadata(String experimentId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENTMETADATA); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("experimentId", experimentId); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } String experimentMetadata = response.getEntity(String.class); return experimentMetadata; } public void updateExperimentMetadata(String experimentId, String metadata){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_EXPERIMENTMETADATA); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("experimentId", experimentId); formParams.add("metadata", metadata); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public String getWorkflowExecutionTemplateName(String workflowInstanceId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_WORKFLOWTEMPLATENAME); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowInstanceId", workflowInstanceId); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } String workflowTemplateName = response.getEntity(String.class); return workflowTemplateName; } public void setWorkflowInstanceTemplateName(String workflowInstanceId, String templateName){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWINSTANCETEMPLATENAME); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("workflowInstanceId", workflowInstanceId); formParams.add("templateName", templateName); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public List<WorkflowInstance> getExperimentWorkflowInstances(String experimentId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENTWORKFLOWINSTANCES); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("experimentId", experimentId); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } WorkflowInstancesList workflowInstancesList = response.getEntity(WorkflowInstancesList.class); WorkflowInstance[] workflowInstances = workflowInstancesList.getWorkflowInstances(); List<WorkflowInstance> workflowInstanceList = new ArrayList<WorkflowInstance>(); for (WorkflowInstance workflowInstance : workflowInstances){ workflowInstanceList.add(workflowInstance); } return workflowInstanceList; } public boolean isWorkflowInstanceExists(String instanceId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.WORKFLOWINSTANCE_EXIST_CHECK); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("instanceId", instanceId); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } return true; } public boolean isWorkflowInstanceExists(String instanceId, boolean createIfNotPresent){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.WORKFLOWINSTANCE_NODE_EXIST_CREATE); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("instanceId", instanceId); formParams.add("createIfNotPresent", createIfNotPresent); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } return true; } public void updateWorkflowInstanceStatus(String instanceId, WorkflowInstanceStatus.ExecutionStatus executionStatus){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWINSTANCESTATUS_INSTANCEID); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("instanceId", instanceId); formParams.add("executionStatus", executionStatus.name()); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void updateWorkflowInstanceStatus(WorkflowInstanceStatus workflowInstanceStatus){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWINSTANCESTATUS); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("workflowInstanceId", workflowInstanceStatus.getWorkflowInstance().getWorkflowInstanceId()); formParams.add("executionStatus", workflowInstanceStatus.getExecutionStatus().name()); formParams.add("statusUpdateTime", workflowInstanceStatus.getStatusUpdateTime().toString()); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public WorkflowInstanceStatus getWorkflowInstanceStatus(String instanceId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_WORKFLOWINSTANCESTATUS); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("instanceId", instanceId); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } WorkflowInstanceStatus workflowInstanceStatus = response.getEntity(WorkflowInstanceStatus.class); return workflowInstanceStatus; } public void updateWorkflowNodeInput(WorkflowInstanceNode node, String data){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWNODEINPUT); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("nodeID", node.getNodeId()); formParams.add("workflowInstanceId", node.getWorkflowInstance().getWorkflowInstanceId()); formParams.add("data", data); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void updateWorkflowNodeOutput(WorkflowInstanceNode node, String data){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWNODEOUTPUT); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("nodeID", node.getNodeId()); formParams.add("workflowInstanceId", node.getWorkflowInstance().getWorkflowInstanceId()); formParams.add("data", data); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public ExperimentData getExperiment(String experimentId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENT); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("experimentId", experimentId); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ExperimentDataImpl experimentData = response.getEntity(ExperimentDataImpl.class); return experimentData; } public ExperimentData getExperimentMetaInformation(String experimentId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENT_METAINFORMATION); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("experimentId", experimentId); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ExperimentDataImpl experimentData = response.getEntity(ExperimentDataImpl.class); return experimentData; } public List<ExperimentData> getAllExperimentMetaInformation(String user){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_ALL_EXPERIMENT_METAINFORMATION); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("user", user); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ExperimentDataList experimentDataList = response.getEntity(ExperimentDataList.class); List<ExperimentDataImpl> dataList = experimentDataList.getExperimentDataList(); List<ExperimentData> experimentDatas = new ArrayList<ExperimentData>(); for (ExperimentDataImpl experimentData : dataList){ experimentDatas.add(experimentData); } return experimentDatas; } public List<ExperimentData> searchExperiments(String user, String experimentNameRegex){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.SEARCH_EXPERIMENTS); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("user", user); queryParams.add("experimentNameRegex", experimentNameRegex); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ExperimentDataList experimentDataList = response.getEntity(ExperimentDataList.class); List<ExperimentDataImpl> dataList = experimentDataList.getExperimentDataList(); List<ExperimentData> experimentDatas = new ArrayList<ExperimentData>(); for (ExperimentDataImpl experimentData : dataList){ experimentDatas.add(experimentData); } return experimentDatas; } public List<String> getExperimentIdByUser(String user){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENT_ID_USER); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("username", user); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ExperimentIDList experimentIDList = response.getEntity(ExperimentIDList.class); List<String> experimentIDs = experimentIDList.getExperimentIDList(); return experimentIDs; } public List<ExperimentData> getExperimentByUser(String user){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_EXPERIMENT_USER); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("username", user); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ExperimentDataList experimentDataList = response.getEntity(ExperimentDataList.class); List<ExperimentDataImpl> dataList = experimentDataList.getExperimentDataList(); List<ExperimentData> experimentDatas = new ArrayList<ExperimentData>(); for (ExperimentDataImpl experimentData : dataList){ experimentDatas.add(experimentData); } return experimentDatas; } public void updateWorkflowNodeStatus(WorkflowInstanceNodeStatus workflowStatusNode){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWNODE_STATUS); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("workflowInstanceId", workflowStatusNode.getWorkflowInstanceNode().getWorkflowInstance().getWorkflowInstanceId()); formParams.add("nodeId", workflowStatusNode.getWorkflowInstanceNode().getNodeId()); formParams.add("executionStatus", workflowStatusNode.getExecutionStatus().name()); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void updateWorkflowNodeStatus(String workflowInstanceId, String nodeId, WorkflowInstanceStatus.ExecutionStatus executionStatus){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWNODE_STATUS); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("workflowInstanceId", workflowInstanceId); formParams.add("nodeId", nodeId); formParams.add("executionStatus", executionStatus.name()); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void updateWorkflowNodeStatus(WorkflowInstanceNode workflowNode, WorkflowInstanceStatus.ExecutionStatus executionStatus){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWNODE_STATUS); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("workflowInstanceId", workflowNode.getWorkflowInstance().getWorkflowInstanceId()); formParams.add("nodeId", workflowNode.getNodeId()); formParams.add("executionStatus", executionStatus.name()); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public WorkflowInstanceNodeStatus getWorkflowNodeStatus(WorkflowInstanceNode workflowNode){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_WORKFLOWNODE_STATUS); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowInstanceId", workflowNode.getWorkflowInstance().getWorkflowInstanceId()); queryParams.add("nodeId", workflowNode.getNodeId()); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } WorkflowInstanceNodeStatus workflowInstanceNodeStatus = response.getEntity(WorkflowInstanceNodeStatus.class); return workflowInstanceNodeStatus; } public Date getWorkflowNodeStartTime(WorkflowInstanceNode workflowNode){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_WORKFLOWNODE_STARTTIME); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowInstanceId", workflowNode.getWorkflowInstance().getWorkflowInstanceId()); queryParams.add("nodeId", workflowNode.getNodeId()); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } String wfNodeStartTime = response.getEntity(String.class); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date formattedDate = dateFormat.parse(wfNodeStartTime); return formattedDate; } catch (ParseException e) { logger.error("Error in date format...", e); return null; } } public Date getWorkflowStartTime(WorkflowInstance workflowInstance){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_WORKFLOW_STARTTIME); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowInstanceId", workflowInstance.getWorkflowInstanceId()); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } String wfStartTime = response.getEntity(String.class); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date formattedDate = dateFormat.parse(wfStartTime); return formattedDate; } catch (ParseException e) { logger.error("Error in date format...", e); return null; } } public void updateWorkflowNodeGramData(WorkflowNodeGramData workflowNodeGramData){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWNODE_GRAMDATA); ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, workflowNodeGramData); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public WorkflowInstanceData getWorkflowInstanceData(String workflowInstanceId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.GET_WORKFLOWINSTANCEDATA); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowInstanceId", workflowInstanceId); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } WorkflowInstanceData workflowInstanceData = response.getEntity(WorkflowInstanceData.class); return workflowInstanceData; } public boolean isWorkflowInstanceNodePresent(String workflowInstanceId, String nodeId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.WORKFLOWINSTANCE_NODE_EXIST); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowInstanceId", workflowInstanceId); queryParams.add("nodeId", nodeId); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } return true; } public boolean isWorkflowInstanceNodePresent(String workflowInstanceId, String nodeId, boolean createIfNotPresent){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.WORKFLOWINSTANCE_NODE_EXIST_CREATE); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowInstanceId", workflowInstanceId); queryParams.add("nodeId", nodeId); queryParams.add("createIfNotPresent", createIfNotPresent); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } return true; } public WorkflowInstanceNodeData getWorkflowInstanceNodeData(String workflowInstanceId, String nodeId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.WORKFLOWINSTANCE_NODE_DATA); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowInstanceId", workflowInstanceId); queryParams.add("nodeId", nodeId); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } WorkflowInstanceNodeData workflowInstanceNodeData = response.getEntity(WorkflowInstanceNodeData.class); return workflowInstanceNodeData; } public void addWorkflowInstance(String experimentId, String workflowInstanceId, String templateName){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.ADD_WORKFLOWINSTANCE); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("experimentId", experimentId); formParams.add("workflowInstanceId", workflowInstanceId); formParams.add("templateName", templateName); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void updateWorkflowNodeType(WorkflowInstanceNode node, WorkflowNodeType type){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.UPDATE_WORKFLOWNODETYPE); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("workflowInstanceId", node.getWorkflowInstance().getWorkflowInstanceId()); formParams.add("nodeId", node.getNodeId()); formParams.add("nodeType", type.getNodeType().name()); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void addWorkflowInstanceNode(String workflowInstance, String nodeId){ webResource = getProvenanceRegistryBaseResource().path(ResourcePathConstants.ProvenanceResourcePathConstants.ADD_WORKFLOWINSTANCENODE); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("workflowInstanceId", workflowInstance); formParams.add("nodeId", nodeId); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } }
8,690
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/client/ProjectResourceClient.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.services.registry.rest.client; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.airavata.registry.api.WorkspaceProject; import org.apache.airavata.services.registry.rest.resourcemappings.WorkspaceProjectList; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.util.ArrayList; import java.util.List; public class ProjectResourceClient { private WebResource webResource; private final static Logger logger = LoggerFactory.getLogger(ProjectResourceClient.class); private URI getBaseURI() { logger.info("Creating Base URI"); return UriBuilder.fromUri("http://localhost:9080/airavata-services/").build(); } private WebResource getProjectRegistryBaseResource (){ ClientConfig config = new DefaultClientConfig(); config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(config); WebResource baseWebResource = client.resource(getBaseURI()); webResource = baseWebResource.path(ResourcePathConstants.ProjectResourcePathConstants.REGISTRY_API_PROJECTREGISTRY); return webResource; } public boolean isWorkspaceProjectExists(String projectName){ webResource = getProjectRegistryBaseResource().path(ResourcePathConstants.ProjectResourcePathConstants.PROJECT_EXIST); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("projectName", projectName); ClientResponse response = webResource.queryParams(queryParams).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } else { return true; } } public boolean isWorkspaceProjectExists(String projectName, boolean createIfNotExists){ String createStatus = "false"; webResource = getProjectRegistryBaseResource().path(ResourcePathConstants.ProjectResourcePathConstants.PROJECT_EXIST); if (createIfNotExists){ createStatus = "true"; } MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("projectName", projectName ); formParams.add("createIfNotExists", createStatus ); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); }else { return true; } } public void addWorkspaceProject(String projectName){ webResource = getProjectRegistryBaseResource().path(ResourcePathConstants.ProjectResourcePathConstants.ADD_PROJECT); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("projectName", projectName ); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void updateWorkspaceProject(String projectName){ webResource = getProjectRegistryBaseResource().path(ResourcePathConstants.ProjectResourcePathConstants.UPDATE_PROJECT); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("projectName", projectName ); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void deleteWorkspaceProject(String projectName){ webResource = getProjectRegistryBaseResource().path(ResourcePathConstants.ProjectResourcePathConstants.DELETE_PROJECT); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("projectName", projectName); ClientResponse response = webResource.queryParams(queryParams).delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public WorkspaceProject getWorkspaceProject(String projectName) { webResource = getProjectRegistryBaseResource().path(ResourcePathConstants.ProjectResourcePathConstants.GET_PROJECT); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("projectName", projectName); ClientResponse response = webResource.queryParams(queryParams).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } WorkspaceProject workspaceProject = response.getEntity(WorkspaceProject.class); return workspaceProject; } public List<WorkspaceProject> getWorkspaceProjects(){ webResource = getProjectRegistryBaseResource().path(ResourcePathConstants.ProjectResourcePathConstants.GET_PROJECTS); ClientResponse response = webResource.get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } WorkspaceProjectList workspaceProjectList = response.getEntity(WorkspaceProjectList.class); WorkspaceProject[] workspaceProjects = workspaceProjectList.getWorkspaceProjects(); List<WorkspaceProject> workspaceProjectsList = new ArrayList<WorkspaceProject>(); for (WorkspaceProject workspaceProject : workspaceProjects){ workspaceProjectsList.add(workspaceProject); } return workspaceProjectsList; } }
8,691
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/client/ConfigurationResourceClient.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.services.registry.rest.client; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.airavata.services.registry.rest.resourcemappings.ConfigurationList; import org.apache.airavata.services.registry.rest.resourcemappings.URLList; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; public class ConfigurationResourceClient { private WebResource webResource; private final static Logger logger = LoggerFactory.getLogger(ConfigurationResourceClient.class); private URI getBaseURI() { logger.info("Creating Base URI"); return UriBuilder.fromUri("http://localhost:9080/airavata-services/").build(); } private WebResource getConfigurationBaseResource (){ ClientConfig config = new DefaultClientConfig(); config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(config); WebResource baseWebResource = client.resource(getBaseURI()); webResource = baseWebResource.path(ResourcePathConstants.ConfigResourcePathConstants.CONFIGURATION_REGISTRY_RESOURCE); return webResource; } public Object getConfiguration(String configKey) { webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.GET_CONFIGURATION); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("key", configKey); ClientResponse response = webResource.queryParams(queryParams).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } String output = response.getEntity(String.class); return output; } public List<Object> getConfigurationList (String configKey) { webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.GET_CONFIGURATION_LIST); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("key", configKey); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } ConfigurationList configurationList = response.getEntity(ConfigurationList.class); List<Object> configurationValueList = new ArrayList<Object>(); Object[] configValList = configurationList.getConfigValList(); for(Object configVal : configValList){ configurationValueList.add(configVal); } return configurationValueList; } public void setConfiguration (String configKey, String configVal, String date){ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.SAVE_CONFIGURATION); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("key", configKey); formData.add("value", configVal); formData.add("date", date); ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void addConfiguration(String configKey, String configVal, String date){ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.UPDATE_CONFIGURATION); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("key", configKey); formData.add("value", configVal); formData.add("date", date); ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, formData); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void removeAllConfiguration(String key){ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_ALL_CONFIGURATION); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("key", key); ClientResponse response = webResource.queryParams(queryParams).delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void removeConfiguration(String key, String value){ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_CONFIGURATION); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("key", key); queryParams.add("value", value); ClientResponse response = webResource.queryParams(queryParams).delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public List<URI> getGFacURIs(){ List<URI> uriList = new ArrayList<URI>(); try{ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.GET_GFAC_URI_LIST); ClientResponse response = webResource.get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } URLList urlList = response.getEntity(URLList.class); String[] uris = urlList.getUris(); for (String url: uris){ URI uri = new URI(url); uriList.add(uri); } } catch (URISyntaxException e) { logger.error("URI syntax is not correct..."); return null; } return uriList; } public List<URI> getWorkflowInterpreterURIs(){ List<URI> uriList = new ArrayList<URI>(); try{ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.GET_WFINTERPRETER_URI_LIST); ClientResponse response = webResource.get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } URLList urlList = response.getEntity(URLList.class); String[] uris = urlList.getUris(); for (String url: uris){ URI uri = new URI(url); uriList.add(uri); } } catch (URISyntaxException e) { return null; } return uriList; } public URI getEventingURI(){ try{ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.GET_EVENTING_URI); ClientResponse response = webResource.get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } String uri = response.getEntity(String.class); URI eventingURI = new URI(uri); return eventingURI; } catch (URISyntaxException e) { return null; } } public URI getMsgBoxURI(){ try{ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.GET_MESSAGE_BOX_URI); ClientResponse response = webResource.get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } String uri = response.getEntity(String.class); URI msgBoxURI = new URI(uri); return msgBoxURI; } catch (URISyntaxException e) { return null; } } public void addGFacURI(String uri) { webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.ADD_GFAC_URI); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("uri", uri); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formData); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void addWFInterpreterURI(String uri) { webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.ADD_WFINTERPRETER_URI); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("uri", uri); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formData); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void setEventingURI(String uri) { webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.ADD_EVENTING_URI); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("uri", uri); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formData); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void setMessageBoxURI(String uri) { webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.ADD_MESSAGE_BOX_URI); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("uri", uri); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formData); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void addGFacURIByDate(String uri, String date) { webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.ADD_GFAC_URI_DATE); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("uri", uri); formData.add("date", date); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formData); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void addWorkflowInterpreterURI(String uri, String date) { webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.ADD_WFINTERPRETER_URI_DATE); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("uri", uri); formData.add("date", date); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formData); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void setEventingURIByDate(String uri, String date) { webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.ADD_EVENTING_URI_DATE); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("uri", uri); formData.add("date", date); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formData); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void setMessageBoxURIByDate(String uri, String date) { webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.ADD_MSG_BOX_URI_DATE); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("uri", uri); formData.add("date", date); ClientResponse response = webResource.accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formData); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void removeGFacURI(String uri){ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_GFAC_URI); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("uri", uri); ClientResponse response = webResource.queryParams(queryParams).delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void removeAllGFacURI(){ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_ALL_GFAC_URIS); ClientResponse response = webResource.delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void removeWorkflowInterpreterURI(String uri){ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_WFINTERPRETER_URI); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("uri", uri); ClientResponse response = webResource.queryParams(queryParams).delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void removeAllWorkflowInterpreterURI(){ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_ALL_WFINTERPRETER_URIS); ClientResponse response = webResource.delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void unsetEventingURI(){ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_EVENTING_URI); ClientResponse response = webResource.delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void unsetMessageBoxURI(){ webResource = getConfigurationBaseResource().path(ResourcePathConstants.ConfigResourcePathConstants.DELETE_MSG_BOX_URI); ClientResponse response = webResource.delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } }
8,692
0
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest
Create_ds/airavata-sandbox/airavata-registry-rest/src/main/java/org/apache/airavata/services/registry/rest/client/UserWorkflowResourceClient.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.services.registry.rest.client; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.json.JSONConfiguration; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.airavata.services.registry.rest.resourcemappings.Workflow; import org.apache.airavata.services.registry.rest.resourcemappings.WorkflowList; import org.apache.airavata.services.registry.rest.utils.ResourcePathConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import java.net.URI; import java.util.HashMap; import java.util.List; import java.util.Map; public class UserWorkflowResourceClient { private WebResource webResource; private final static Logger logger = LoggerFactory.getLogger(UserWorkflowResourceClient.class); private URI getBaseURI() { logger.info("Creating Base URI"); return UriBuilder.fromUri("http://localhost:9080/airavata-services/").build(); } private com.sun.jersey.api.client.WebResource getUserWFRegistryBaseResource (){ ClientConfig config = new DefaultClientConfig(); config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(config); WebResource baseWebResource = client.resource(getBaseURI()); webResource = baseWebResource.path(ResourcePathConstants.UserWFConstants.REGISTRY_API_USERWFREGISTRY); return webResource; } public boolean isWorkflowExists(String workflowName){ webResource = getUserWFRegistryBaseResource().path(ResourcePathConstants.UserWFConstants.WORKFLOW_EXIST); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowname", workflowName); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } return true; } public void addWorkflow(String workflowName, String workflowGraphXml){ webResource = getUserWFRegistryBaseResource().path(ResourcePathConstants.UserWFConstants.ADD_WORKFLOW); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("workflowName", workflowName); formParams.add("workflowGraphXml", workflowGraphXml); ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public void updateWorkflow(String workflowName, String workflowGraphXml){ webResource = getUserWFRegistryBaseResource().path(ResourcePathConstants.UserWFConstants.UPDATE_WORKFLOW); MultivaluedMap formParams = new MultivaluedMapImpl(); formParams.add("workflowName", workflowName); formParams.add("workflowGraphXml", workflowGraphXml); ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.TEXT_PLAIN).post(ClientResponse.class, formParams); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } public String getWorkflowGraphXML(String workflowName){ webResource = getUserWFRegistryBaseResource().path(ResourcePathConstants.UserWFConstants.GET_WORKFLOWGRAPH); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowname", workflowName); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } String worlflowGraph = response.getEntity(String.class); return worlflowGraph; } public Map<String, String> getWorkflows(){ webResource = getUserWFRegistryBaseResource().path(ResourcePathConstants.UserWFConstants.GET_WORKFLOWS); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } Map<String, String> userWFMap = new HashMap<String, String>(); WorkflowList workflowList = response.getEntity(WorkflowList.class); List<Workflow> workflows = workflowList.getWorkflowList(); for (Workflow workflow : workflows){ userWFMap.put(workflow.getWorkflowName(), workflow.getWorkflowGraph()); } return userWFMap; } public void removeWorkflow(String workflowName){ webResource = getUserWFRegistryBaseResource().path(ResourcePathConstants.UserWFConstants.REMOVE_WORKFLOW); MultivaluedMap queryParams = new MultivaluedMapImpl(); queryParams.add("workflowname", workflowName); ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.TEXT_PLAIN).delete(ClientResponse.class); int status = response.getStatus(); if (status != 200) { logger.error("Failed : HTTP error code : " + status); throw new RuntimeException("Failed : HTTP error code : " + status); } } }
8,693
0
Create_ds/airavata-sandbox/workflow-monitoring-util/web/src/org/apache/airavata/tools/workflow
Create_ds/airavata-sandbox/workflow-monitoring-util/web/src/org/apache/airavata/tools/workflow/monitoring/QueryManager.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.tools.workflow.monitoring; import org.apache.airavata.tools.workflow.monitoring.db.DBConstants; import org.apache.airavata.tools.workflow.monitoring.db.JdbcStorage; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class QueryManager { private static JdbcStorage database = new JdbcStorage(Server.DB_CONFIG_NAME, true); private Connection connection; private PreparedStatement preparedStatement; private ResultSet resultSet; public QueryManager() { } public void close() throws WorkflowMonitoringException { try { if (resultSet != null) { resultSet.close(); } if (preparedStatement != null) { preparedStatement.close(); } if (connection != null) { database.closeConnection(connection); } } catch (SQLException e) { throw new WorkflowMonitoringException(e); } } public ResultSet getDataRelatesToWorkflowId(String workflowId) throws WorkflowMonitoringException { try { connection = database.connect(); preparedStatement = connection.prepareStatement("SELECT * FROM " + DBConstants.T_FAULTS_NAME + " WHERE " + DBConstants.T_FAULTS_WORKFLOW_ID + " = '" + workflowId + "'"); resultSet = preparedStatement.executeQuery(); return resultSet; } catch (SQLException e) { throw new WorkflowMonitoringException(e); } } public ResultSet getWorkflowsWithinTimeRange(long startDate, long endDate) throws WorkflowMonitoringException { // do a bit of validation here if (startDate < 0) { return null; } try { String sqlString = getSQLForWorkflowInformationRetrieval(startDate, endDate); connection = database.connect(); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); return resultSet; } catch (SQLException e) { throw new WorkflowMonitoringException(e); } } public ResultSet getWorkflowsOfUser(String username) throws WorkflowMonitoringException { // do a bit of validation here if (username != null || "".equals(username)) { return null; } try { String sqlString = getSQLForWorkflowInformationRetrieval(username); System.out.println("sqlString = " + sqlString); connection = database.connect(); preparedStatement = connection.prepareStatement(sqlString); resultSet = preparedStatement.executeQuery(); return resultSet; } catch (SQLException e) { throw new WorkflowMonitoringException(e); } } /** * This will process the input dates and provide with an SQL to retrieve workflow data from the database * <p/> * Note : This method assumes the inputs are validated by the caller before passing them here. * * @param startDate * @param endDate * @return */ private String getSQLForWorkflowInformationRetrieval(long startDate, long endDate) { String sql = "SELECT * FROM " + DBConstants.T_SUMMARY_NAME + " WHERE " + DBConstants.T_SUMMARY_START_TIME + " > " + startDate; if (endDate > 0) { sql += " AND " + DBConstants.T_SUMMARY_START_TIME + " < " + endDate; } return sql; } private String getSQLForWorkflowInformationRetrieval(String username) { return "SELECT * FROM " + DBConstants.T_SUMMARY_NAME + " WHERE " + DBConstants.T_SUMMARY_USERNAME + " LIKE \"%" + username + "%\""; } /** * This will retrieve summary information for all the workflow that had started within the given time range. If no * end time is given, the current time is assumed. * * @param startDate * @param endDate * @return */ public ResultSet getSummaryInformation(long startDate, long endDate) { // do a bit of validation here if (startDate < 0) { return null; } try { String sql = "SELECT count(*) as total, " + DBConstants.T_SUMMARY_STATUS + " FROM " + DBConstants.T_SUMMARY_NAME + " WHERE " + DBConstants.T_SUMMARY_START_TIME + " > " + startDate; if (endDate > 0) { sql += " AND " + DBConstants.T_SUMMARY_START_TIME + " < " + endDate; } sql += " GROUP BY " + DBConstants.T_SUMMARY_STATUS; connection = database.connect(); preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); return resultSet; } catch (SQLException e) { throw new WorkflowMonitoringException(e); } } public ResultSet getSummaryInformationForTemplates(long startDate, long endDate) { // do a bit of validation here if (startDate < 0) { return null; } try { String sql = "SELECT count(*) as total, " + DBConstants.T_SUMMARY_STATUS + ", " + DBConstants.T_SUMMARY_TEMPLATE_ID + " FROM " + DBConstants.T_SUMMARY_NAME + " WHERE " + DBConstants.T_SUMMARY_START_TIME + " > " + startDate; if (endDate > 0) { sql += " AND " + DBConstants.T_SUMMARY_START_TIME + " < " + endDate; } sql += " GROUP BY " + DBConstants.T_SUMMARY_TEMPLATE_ID + ", " + DBConstants.T_SUMMARY_STATUS; connection = database.connect(); preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); return resultSet; } catch (SQLException e) { throw new WorkflowMonitoringException(e); } } /** * There can be workflows successful now, but those might be failed earlier and recovered. We need to find why those * failed earlier to diagnose errors in the system. This will retrieve all the workflows with the current status set * to SUCCESSFUL but has faults registered in faults table. * * @param startDate * @param endDate * @return */ public ResultSet getPreviouslyFailedSuccessfulInstances(long startDate, long endDate) { String sql = "SELECT summary." + DBConstants.T_SUMMARY_WORKFLOW_ID + " FROM " + DBConstants.T_SUMMARY_NAME + " summary, " + DBConstants.T_FAULTS_NAME + " faults " + " WHERE " + DBConstants.T_SUMMARY_START_TIME + " > " + startDate + " AND summary." + DBConstants.T_SUMMARY_WORKFLOW_ID + "=faults." + DBConstants.T_FAULTS_WORKFLOW_ID + " AND summary." + DBConstants.T_SUMMARY_STATUS + "='SUCCESSFUL' "; if (endDate > 0) { sql += " AND " + DBConstants.T_SUMMARY_START_TIME + " < " + endDate; } try { connection = database.connect(); preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); return resultSet; } catch (SQLException e) { throw new WorkflowMonitoringException(e); } } /** * There can be workflows successful now, but those might be failed earlier and recovered. We need to find why those * failed earlier to diagnose errors in the system. This will retrieve all the workflows with the current status set * to SUCCESSFUL but has faults registered in faults table. * * @param startDate * @param endDate * @return */ public ResultSet getPreviouslyFailedSuccessfulInstances(String username) { String sql = "SELECT summary." + DBConstants.T_SUMMARY_WORKFLOW_ID + " FROM " + DBConstants.T_SUMMARY_NAME + " summary, " + DBConstants.T_FAULTS_NAME + " faults " + " WHERE " + DBConstants.T_SUMMARY_USERNAME + " = '" + username + "' " + " AND summary." + DBConstants.T_SUMMARY_WORKFLOW_ID + "=faults." + DBConstants.T_FAULTS_WORKFLOW_ID + " AND summary." + DBConstants.T_SUMMARY_STATUS + "='SUCCESSFUL' "; try { connection = database.connect(); preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); return resultSet; } catch (SQLException e) { throw new WorkflowMonitoringException(e); } } }
8,694
0
Create_ds/airavata-sandbox/workflow-monitoring-util/web/src/org/apache/airavata/tools/workflow/monitoring
Create_ds/airavata-sandbox/workflow-monitoring-util/web/src/org/apache/airavata/tools/workflow/monitoring/util/Util.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.tools.workflow.monitoring.util; import org.apache.airavata.tools.workflow.monitoring.WorkflowMonitoringException; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Util { public static final String DATE_FORMAT = "mm/dd/yyyy hh:mm:ss"; /** * This will convert a give date time string in to the its equivalent time in milliseconds. This could have been * done easily using DateFormat class in java, but for some reason it was not working as expected. * * @param timeString * - the format must be mm/dd/yyyy hh:mm:ss. * @return */ public static long getTime(String timeString) throws WorkflowMonitoringException { String[] dateAndTime = timeString.split(" "); if (dateAndTime.length == 2) { String[] dateComponents = dateAndTime[0].split("/"); String[] timeComponents = dateAndTime[1].split(":"); if (dateComponents.length == 3 && timeComponents.length == 3) { Calendar calendar = Calendar.getInstance(); calendar.set(Integer.parseInt(dateComponents[2]), Integer.parseInt(dateComponents[0]) - 1, Integer.parseInt(dateComponents[1]), Integer.parseInt(timeComponents[0]), Integer.parseInt(timeComponents[1]), Integer.parseInt(timeComponents[2])); return calendar.getTime().getTime(); } else { throw new WorkflowMonitoringException("Date time string should be of the format " + DATE_FORMAT); } } else { throw new WorkflowMonitoringException("Date time string should be of the format " + DATE_FORMAT); } } /** * This method will construct a formatted date and time string from a give date. The date is given as a string which * represents the time in milliseconds. * * @param time * - this is the string presentation of the time in milliseconds * @return */ public static String getFormattedDateFromLongValue(String time) { Date date = new Date(Long.parseLong(time)); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); return (calendar.get(Calendar.MONTH) + 1) + "/" + calendar.get(Calendar.DATE) + "/" + calendar.get(Calendar.YEAR) + " " + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE) + ":" + calendar.get(Calendar.SECOND); } public static String extractUsername(String userDN) { int lastIndex; if (userDN.lastIndexOf("/") == userDN.indexOf("/CN")) { lastIndex = userDN.length(); } else { lastIndex = userDN.lastIndexOf("/"); } return userDN.substring(userDN.indexOf("/CN=") + 4, lastIndex); } public static String extractShortTemplateId(String templateId) { return templateId.substring(templateId.lastIndexOf("/") + 1); } }
8,695
0
Create_ds/airavata-sandbox/workflow-monitoring-util/web/src/org/apache/airavata/tools/workflow/monitoring
Create_ds/airavata-sandbox/workflow-monitoring-util/web/src/org/apache/airavata/tools/workflow/monitoring/bean/WorkflowInfo.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.tools.workflow.monitoring.bean; import java.util.Date; public class WorkflowInfo implements Comparable { private String workflowId; private String templateId; private String username = ""; private String status; private String startTime; private String endTime; private boolean faultsAvailable; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getWorkflowId() { return workflowId; } public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } public String getTemplateId() { return templateId; } public void setTemplateId(String templateId) { this.templateId = templateId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public String getEndTime() { return endTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public boolean isFaultsAvailable() { return faultsAvailable; } public void setFaultsAvailable(boolean faultsAvailable) { this.faultsAvailable = faultsAvailable; } public int compareTo(Object o) { if (o instanceof WorkflowInfo) { WorkflowInfo workflowInfo = (WorkflowInfo) o; return new Date(startTime).before(new Date(workflowInfo.getStartTime())) ? -1 : 1; } // If this < o, return a negative value // If this = o, return 0 // If this > o, return a positive value return 0; } }
8,696
0
Create_ds/airavata-sandbox/workflow-monitoring-util/web/src/org/apache/airavata/tools/workflow/monitoring
Create_ds/airavata-sandbox/workflow-monitoring-util/web/src/org/apache/airavata/tools/workflow/monitoring/bean/TemplateInfoBean.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.tools.workflow.monitoring.bean; import java.util.ArrayList; import java.util.List; public class TemplateInfoBean { private String templateID; // I will store the status and the status count in two different array lists. The count for status[i] will be in // statusCount[i]. // To optimize the number of array list usages, I defined a an initial capacity as 3 assuming most of the time // each template may exist in one of the three status. private int AVERAGE_STATUS_SIZE = 3; private long totalCount = 0; private List<String> status = new ArrayList<String>(3); private List<Long> statusCount = new ArrayList<Long>(AVERAGE_STATUS_SIZE); public TemplateInfoBean(String templateID) { this.templateID = templateID; } public void addStatusInfo(String status, long statusCount) { this.status.add(status); this.statusCount.add(new Long(statusCount)); totalCount += statusCount; } public String getTemplateID() { return templateID; } public List<String> getAllStatusNames() { return status; } public List<Long> getAllStatusCounts() { return statusCount; } public long getTotalCount() { return totalCount; } }
8,697
0
Create_ds/airavata-sandbox/workflow-monitoring-util/src/test/java/org/apache/airavata/tools/workflow/monitoring
Create_ds/airavata-sandbox/workflow-monitoring-util/src/test/java/org/apache/airavata/tools/workflow/monitoring/test/WorkflowIDParsingTest.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.tools.workflow.monitoring.test; import org.apache.airavata.tools.workflow.monitoring.Server; import org.apache.airavata.tools.workflow.monitoring.Util; import junit.framework.TestCase; public class WorkflowIDParsingTest extends TestCase { public static String TEST_ENVELOP = "<S:Envelope " + "xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<S:Body>" + PublishSendingFaultTest.message + "</S:Body>" + "</S:Envelope>"; public void testPasringWOrkflowID() { assertEquals(PublishSendingFaultTest.workflowID, Util.getWorkflowID(TEST_ENVELOP, Server.SENDING_FAULT, "workflowID")); } }
8,698
0
Create_ds/airavata-sandbox/workflow-monitoring-util/src/test/java/org/apache/airavata/tools/workflow/monitoring
Create_ds/airavata-sandbox/workflow-monitoring-util/src/test/java/org/apache/airavata/tools/workflow/monitoring/test/PublishSendingFaultTest.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.tools.workflow.monitoring.test; import org.apache.airavata.tools.workflow.monitoring.Server; import wsmg.WseClientAPI; import junit.framework.TestCase; public class PublishSendingFaultTest extends TestCase { public static String workflowID = "tag:gpel.leadproject.org,2006:6BD/WRFForecastWithADASInitializedData/instance71"; public static String message = "<wor:sendingFault " + "xmlns:wor=\"http://lead.extreme.indiana.edu/namespaces/2006/06/workflow_tracking\">" + "<wor:notificationSource" + " wor:serviceID=\"urn:qname:http://www.extreme.indiana.edu/lead:WRF_Forecasting_Model_Service\"" + " wor:workflowID=\"tag:gpel.leadproject.org,2006:71N/TestCISimpleEchoWorkflow/instance36\"" + " wor:workflowTimestep=\"18\"" + " wor:workflowNodeID=\"WRF_Forecasting_Model_Service\" />" + "</wor:sendingFault>"; public void testPublish() { WseClientAPI client = new WseClientAPI(); client.publish(MonitorTest.brokerurl, "anytopic-since-we-use-xpath", message); } }
8,699