http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifier.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifier.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifier.java new file mode 100644 index 0000000..e52b211 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifier.java @@ -0,0 +1,71 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.airavata.credential.store.notifier.impl; + +import org.apache.airavata.credential.store.notifier.CredentialStoreNotifier; +import org.apache.airavata.credential.store.notifier.NotificationMessage; +import org.apache.airavata.credential.store.store.CredentialStoreException; +import org.apache.commons.mail.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * User: AmilaJ ([email protected]) + * Date: 12/3/13 + * Time: 4:25 PM + */ + +public class EmailNotifier implements CredentialStoreNotifier { + + protected static Logger log = LoggerFactory.getLogger(EmailNotifier.class); + + private EmailNotifierConfiguration emailNotifierConfiguration; + + public EmailNotifier(EmailNotifierConfiguration notifierConfiguration) { + this.emailNotifierConfiguration = notifierConfiguration; + } + + public void notifyMessage(NotificationMessage message) throws CredentialStoreException { + try { + Email email = new SimpleEmail(); + email.setHostName(this.emailNotifierConfiguration.getEmailServer()); + email.setSmtpPort(this.emailNotifierConfiguration.getEmailServerPort()); + email.setAuthenticator(new DefaultAuthenticator(this.emailNotifierConfiguration.getEmailUserName(), + this.emailNotifierConfiguration.getEmailPassword())); + email.setSSLOnConnect(this.emailNotifierConfiguration.isSslConnect()); + email.setFrom(this.emailNotifierConfiguration.getFromAddress()); + + EmailNotificationMessage emailMessage = (EmailNotificationMessage)message; + + email.setSubject(emailMessage.getSubject()); + email.setMsg(emailMessage.getMessage()); + email.addTo(emailMessage.getSenderEmail()); + email.send(); + + } catch (EmailException e) { + log.error("[CredentialStore]Error sending email notification message."); + throw new CredentialStoreException("Error sending email notification message", e); + } + + + } +}
http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifierConfiguration.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifierConfiguration.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifierConfiguration.java new file mode 100644 index 0000000..b1a204f --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifierConfiguration.java @@ -0,0 +1,84 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.airavata.credential.store.notifier.impl; + +import org.apache.airavata.common.exception.ApplicationSettingsException; +import org.apache.airavata.common.utils.ApplicationSettings; + +/** + * User: AmilaJ ([email protected]) + * Date: 12/3/13 + * Time: 5:06 PM + */ + +public class EmailNotifierConfiguration { + private String emailServer; + private int emailServerPort; + private String emailUserName; + private String emailPassword; + private boolean sslConnect; + private String fromAddress; + + public EmailNotifierConfiguration(String emailServer, int emailServerPort, String emailUserName, + String emailPassword, boolean sslConnect, String fromAddress) { + this.emailServer = emailServer; + this.emailServerPort = emailServerPort; + this.emailUserName = emailUserName; + this.emailPassword = emailPassword; + this.sslConnect = sslConnect; + this.fromAddress = fromAddress; + } + + public String getEmailServer() { + return emailServer; + } + + public int getEmailServerPort() { + return emailServerPort; + } + + public String getEmailUserName() { + return emailUserName; + } + + public String getEmailPassword() { + return emailPassword; + } + + public boolean isSslConnect() { + return sslConnect; + } + + public String getFromAddress() { + return fromAddress; + } + + public static EmailNotifierConfiguration getEmailNotifierConfigurations() throws ApplicationSettingsException { + return new EmailNotifierConfiguration(ApplicationSettings.getCredentialStoreEmailServer(), + Integer.parseInt(ApplicationSettings.getCredentialStoreEmailServerPort()), + ApplicationSettings.getCredentialStoreEmailUser(), + ApplicationSettings.getCredentialStoreEmailPassword(), + Boolean.parseBoolean(ApplicationSettings.getCredentialStoreEmailSSLConnect()), + ApplicationSettings.getCredentialStoreEmailFromEmail()); + } + +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/server/CredentialStoreServer.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/server/CredentialStoreServer.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/server/CredentialStoreServer.java new file mode 100644 index 0000000..f0e14d5 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/server/CredentialStoreServer.java @@ -0,0 +1,158 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.airavata.credential.store.server; + + +import org.apache.airavata.common.utils.Constants; +import org.apache.airavata.common.utils.IServer; +import org.apache.airavata.common.utils.ServerSettings; +import org.apache.airavata.credential.store.cpi.CredentialStoreService; +import org.apache.thrift.server.TServer; +import org.apache.thrift.server.TThreadPoolServer; +import org.apache.thrift.transport.TSSLTransportFactory; +import org.apache.thrift.transport.TServerSocket; +import org.apache.thrift.transport.TTransportException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.net.InetAddress; +import java.net.InetSocketAddress; + +public class CredentialStoreServer implements IServer { + private final static Logger logger = LoggerFactory.getLogger(CredentialStoreServer.class); + private static final String SERVER_NAME = "Credential Store Server"; + private static final String SERVER_VERSION = "1.0"; + + private IServer.ServerStatus status; + private TServer server; + + public CredentialStoreServer() { + setStatus(IServer.ServerStatus.STOPPED); + } + + @Override + public String getName() { + return SERVER_NAME; + } + + @Override + public String getVersion() { + return SERVER_VERSION; + } + + @Override + public void start() throws Exception { + if(ServerSettings.isCredentialStoreStartEnabled()) { + try { + setStatus(ServerStatus.STARTING); + TSSLTransportFactory.TSSLTransportParameters params = + new TSSLTransportFactory.TSSLTransportParameters(); + String keystorePath = ServerSettings.getCredentialStoreThriftServerKeyStorePath(); + String keystorePWD = ServerSettings.getCredentialStoreThriftServerKeyStorePassword(); + final int serverPort = Integer.parseInt(ServerSettings.getSetting(Constants.CREDNETIAL_SERVER_PORT, "8960")); + final String serverHost = ServerSettings.getSetting(Constants.CREDNETIAL_SERVER_HOST, null); + params.setKeyStore(keystorePath, keystorePWD); + + TServerSocket serverTransport = TSSLTransportFactory.getServerSocket(serverPort, 100, InetAddress.getByName(serverHost), params); + + + CredentialStoreService.Processor processor = new CredentialStoreService.Processor(new CredentialStoreServerHandler()); + + server = new TThreadPoolServer(new TThreadPoolServer.Args(serverTransport). + processor(processor)); + new Thread() { + public void run() { + server.serve(); + setStatus(ServerStatus.STOPPED); + logger.info("Credential Store Server Stopped."); + } + }.start(); + new Thread() { + public void run() { + while (!server.isServing()) { + try { + Thread.sleep(500); + } catch (InterruptedException e) { + break; + } + } + if (server.isServing()) { + setStatus(ServerStatus.STARTED); + logger.info("Starting Credential Store Server on Port " + serverPort); + logger.info("Listening to Credential Store Clients ...."); + } + } + }.start(); + } catch (TTransportException e) { + setStatus(ServerStatus.FAILED); + logger.error("Error while starting the credential store service", e); + throw new Exception("Error while starting the credential store service", e); + } + } + } + + public static void main(String[] args) { + try { + new CredentialStoreServer().start(); + } catch (Exception e) { + logger.error(e.getMessage(), e); + } + } + + @Override + public void stop() throws Exception { + if (server!=null && server.isServing()){ + setStatus(ServerStatus.STOPING); + server.stop(); + } + } + + @Override + public void restart() throws Exception { + stop(); + start(); + } + + @Override + public void configure() throws Exception { + + } + + @Override + public ServerStatus getStatus() throws Exception { + return null; + } + + private void setStatus(IServer.ServerStatus stat){ + status=stat; + status.updateTime(); + } + + public TServer getServer() { + return server; + } + + public void setServer(TServer server) { + this.server = server; + } + + +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/server/CredentialStoreServerHandler.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/server/CredentialStoreServerHandler.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/server/CredentialStoreServerHandler.java new file mode 100644 index 0000000..b5b1ac0 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/server/CredentialStoreServerHandler.java @@ -0,0 +1,202 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.airavata.credential.store.server; + +import org.apache.airavata.common.exception.ApplicationSettingsException; +import org.apache.airavata.common.utils.DBUtil; +import org.apache.airavata.common.utils.ServerSettings; +import org.apache.airavata.credential.store.cpi.CredentialStoreService; +import org.apache.airavata.credential.store.cpi.cs_cpi_serviceConstants; +import org.apache.airavata.credential.store.credential.CommunityUser; +import org.apache.airavata.credential.store.credential.Credential; +import org.apache.airavata.credential.store.datamodel.CertificateCredential; +import org.apache.airavata.credential.store.datamodel.PasswordCredential; +import org.apache.airavata.credential.store.datamodel.SSHCredential; +import org.apache.airavata.credential.store.store.CredentialStoreException; +import org.apache.airavata.credential.store.store.impl.CertificateCredentialWriter; +import org.apache.airavata.credential.store.store.impl.CredentialReaderImpl; +import org.apache.airavata.credential.store.store.impl.SSHCredentialWriter; +import org.apache.airavata.credential.store.util.TokenGenerator; +import org.apache.airavata.credential.store.util.Utility; +import org.apache.commons.codec.binary.Base64; +import org.apache.thrift.TException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import sun.security.provider.X509Factory; + +import java.io.ByteArrayInputStream; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.UUID; + +public class CredentialStoreServerHandler implements CredentialStoreService.Iface { + protected static Logger log = LoggerFactory.getLogger(CredentialStoreServerHandler.class); + private DBUtil dbUtil; + private SSHCredentialWriter sshCredentialWriter; + private CertificateCredentialWriter certificateCredentialWriter; + private CredentialReaderImpl credentialReader; + + public CredentialStoreServerHandler() throws ApplicationSettingsException, IllegalAccessException, ClassNotFoundException, InstantiationException { + String jdbcUrl = ServerSettings.getCredentialStoreDBURL(); + String userName = ServerSettings.getCredentialStoreDBUser(); + String password = ServerSettings.getCredentialStoreDBPassword(); + String driverName = ServerSettings.getCredentialStoreDBDriver(); + + log.debug("Starting credential store, connecting to database - " + jdbcUrl + " DB user - " + userName + " driver name - " + driverName); + dbUtil = new DBUtil(jdbcUrl, userName, password, driverName); + sshCredentialWriter = new SSHCredentialWriter(dbUtil); + certificateCredentialWriter = new CertificateCredentialWriter(dbUtil); + credentialReader = new CredentialReaderImpl(dbUtil); + } + + @Override + public String getCSServiceVersion() throws TException { + return cs_cpi_serviceConstants.CS_CPI_VERSION; + } + + @Override + public String addSSHCredential(SSHCredential sshCredential) throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { + try { + org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential credential = new org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential(); + credential.setGateway(sshCredential.getGatewayId()); + credential.setPortalUserName(sshCredential.getUsername()); + // only username and gateway id will be sent by client. + String token = TokenGenerator.generateToken(sshCredential.getGatewayId(), null); + credential.setToken(token); + credential.setPassphrase(String.valueOf(UUID.randomUUID())); + if (sshCredential.getPrivateKey() != null) { + credential.setPrivateKey(sshCredential.getPrivateKey().getBytes()); + } + if (sshCredential.getPublicKey() != null) { + credential.setPublicKey(sshCredential.getPublicKey().getBytes()); + } + if (sshCredential.getPublicKey() == null || sshCredential.getPrivateKey() == null) { + credential = Utility.generateKeyPair(credential); + } + sshCredentialWriter.writeCredentials(credential); + return token; + } catch (CredentialStoreException e) { + log.error("Error occurred while saving SSH Credentials.", e); + throw new org.apache.airavata.credential.store.exception.CredentialStoreException("Error occurred while saving SSH Credentials."); + } catch (Exception e) { + log.error("Error occurred while generating key pair.", e); + throw new org.apache.airavata.credential.store.exception.CredentialStoreException("Error occurred while generating key pair.."); + } + } + + @Override + public String addCertificateCredential(CertificateCredential certificateCredential) throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { + try { + org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential credential = new org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential(); + credential.setPortalUserName(certificateCredential.getCommunityUser().getUsername()); + credential.setCommunityUser(new CommunityUser(certificateCredential.getCommunityUser().getGatewayNmae(), + certificateCredential.getCommunityUser().getUsername(), certificateCredential.getCommunityUser().getUserEmail())); + String token = TokenGenerator.generateToken(certificateCredential.getCommunityUser().getGatewayNmae(), null); + credential.setToken(token); + Base64 encoder = new Base64(64); + byte [] decoded = encoder.decode(certificateCredential.getX509Cert().replaceAll(X509Factory.BEGIN_CERT, "").replaceAll(X509Factory.END_CERT, "")); + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + X509Certificate certificate = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(decoded)); + X509Certificate[] certificates = new X509Certificate[1]; + certificates[0] = certificate; + credential.setCertificates(certificates); + certificateCredentialWriter.writeCredentials(credential); + return token; + } catch (CredentialStoreException e) { + log.error("Error occurred while saving Certificate Credentials.", e); + throw new org.apache.airavata.credential.store.exception.CredentialStoreException("Error occurred while saving Certificate Credentials."); + } catch (Exception e) { + log.error("Error occurred while converting to X509 certificate.", e); + throw new org.apache.airavata.credential.store.exception.CredentialStoreException("Error occurred while converting to X509 certificate.."); + } + } + + @Override + public String addPasswordCredential(PasswordCredential passwordCredential) throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { + return null; + } + + @Override + public SSHCredential getSSHCredential(String tokenId, String gatewayId) throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { + try { + Credential credential = credentialReader.getCredential(gatewayId, tokenId); + if (credential instanceof org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential) { + org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential credential1 = (org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential) credential; + SSHCredential sshCredential = new SSHCredential(); + sshCredential.setUsername(credential1.getPortalUserName()); + sshCredential.setGatewayId(credential1.getGateway()); + sshCredential.setPublicKey(new String(credential1.getPublicKey())); + sshCredential.setPrivateKey(new String(credential1.getPrivateKey())); + sshCredential.setPassphrase(credential1.getPassphrase()); + sshCredential.setToken(credential1.getToken()); + sshCredential.setPersistedTime(credential1.getCertificateRequestedTime().getTime()); + return sshCredential; + } else { + log.info("Could not find SSH credentials for token - " + tokenId + " and " + + "gateway id - " + gatewayId); + return null; + } + } catch (CredentialStoreException e) { + log.error("Error occurred while retrieving SSH credentialfor token - " + tokenId + " and gateway id - " + gatewayId, e); + throw new org.apache.airavata.credential.store.exception.CredentialStoreException("Error occurred while retrieving SSH credential for token - " + tokenId + " and gateway id - " + gatewayId); + } + } + + @Override + public CertificateCredential getCertificateCredential(String tokenId, String gatewayId) throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { + try { + Credential credential = credentialReader.getCredential(gatewayId, tokenId); + if (credential instanceof org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential) { + org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential credential1 = (org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential) credential; + CertificateCredential certificateCredential = new CertificateCredential(); + org.apache.airavata.credential.store.datamodel.CommunityUser communityUser = new org.apache.airavata.credential.store.datamodel.CommunityUser(); + communityUser.setGatewayNmae(credential1.getCommunityUser().getGatewayName()); + communityUser.setUsername(credential1.getCommunityUser().getUserName()); + communityUser.setUserEmail(credential1.getCommunityUser().getUserEmail()); + certificateCredential.setCommunityUser(communityUser); + certificateCredential.setToken(credential1.getToken()); + certificateCredential.setLifeTime(credential1.getLifeTime()); + certificateCredential.setNotAfter(credential1.getNotAfter()); + certificateCredential.setNotBefore(credential1.getNotBefore()); + certificateCredential.setPersistedTime(credential1.getCertificateRequestedTime().getTime()); + if (credential1.getPrivateKey() != null){ + certificateCredential.setPrivateKey(credential1.getPrivateKey().toString()); + } + certificateCredential.setX509Cert(credential1.getCertificates()[0].toString()); + return certificateCredential; + } else { + log.info("Could not find Certificate credentials for token - " + tokenId + " and " + + "gateway id - " + gatewayId); + return null; + } + } catch (CredentialStoreException e) { + log.error("Error occurred while retrieving Certificate credential for token - " + tokenId + " and gateway id - " + gatewayId, e); + throw new org.apache.airavata.credential.store.exception.CredentialStoreException("Error occurred while retrieving Certificate credential for token - " + tokenId + " and gateway id - " + gatewayId); + } + } + + @Override + public PasswordCredential getPasswordCredential(String tokenId, String gatewayId) throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { + return null; + } + + +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/servlet/CredentialBootstrapper.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/servlet/CredentialBootstrapper.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/servlet/CredentialBootstrapper.java new file mode 100644 index 0000000..b2e8786 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/servlet/CredentialBootstrapper.java @@ -0,0 +1,49 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +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 org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.ServletContext; +import java.io.File; + +/** + * Bootstrapper class for credential-store. + */ +public class CredentialBootstrapper extends ClientBootstrapper { + + protected static Logger log = LoggerFactory.getLogger(CredentialBootstrapper.class); + + public ConfigurationLoader getConfigurationLoader(ServletContext servletContext) throws Exception { + + File currentDirectory = new File("."); + + log.info("Current directory is - " + currentDirectory.getAbsolutePath()); + + return super.getConfigurationLoader(servletContext); + + } + +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreCallbackServlet.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreCallbackServlet.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreCallbackServlet.java new file mode 100644 index 0000000..66d4be7 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreCallbackServlet.java @@ -0,0 +1,272 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +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 org.apache.airavata.common.exception.ApplicationSettingsException; +import org.apache.airavata.common.utils.AiravataUtils; +import org.apache.airavata.common.utils.ApplicationSettings; +import org.apache.airavata.common.utils.DBUtil; +import org.apache.airavata.credential.store.credential.CommunityUser; +import org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential; +import org.apache.airavata.credential.store.notifier.NotifierBootstrap; +import org.apache.airavata.credential.store.notifier.impl.EmailNotifierConfiguration; +import org.apache.airavata.credential.store.store.impl.CertificateCredentialWriter; +import org.apache.airavata.credential.store.util.ConfigurationReader; +import org.apache.airavata.credential.store.util.CredentialStoreConstants; +import org.apache.airavata.credential.store.util.PrivateKeyStore; +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.PrivateKey; +import java.security.cert.X509Certificate; +import java.util.HashMap; +import java.util.Map; + +import static edu.uiuc.ncsa.myproxy.oa4mp.client.ClientEnvironment.CALLBACK_URI_KEY; + +/** + * 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 OA4MPService oa4mpService; + + private CertificateCredentialWriter certificateCredentialWriter; + + private static ConfigurationReader configurationReader; + + private NotifierBootstrap notifierBootstrap; + + public void init() throws ServletException { + + DBUtil dbUtil; + + try { + AiravataUtils.setExecutionAsServer(); + dbUtil = DBUtil.getCredentialStoreDBUtil(); + } catch (Exception e) { + throw new ServletException("Error initializing database operations.", e); + } + + try { + configurationReader = new ConfigurationReader(); + super.init(); + certificateCredentialWriter = new CertificateCredentialWriter(dbUtil); + } catch (Exception e) { + throw new ServletException("Error initializing configuration reader.", e); + } + + + // initialize notifier + try { + boolean enabled = Boolean.parseBoolean(ApplicationSettings.getCredentialStoreNotifierEnabled()); + + if (enabled) { + EmailNotifierConfiguration notifierConfiguration + = EmailNotifierConfiguration.getEmailNotifierConfigurations(); + long duration = Long.parseLong(ApplicationSettings.getCredentialStoreNotifierDuration()); + + notifierBootstrap = new NotifierBootstrap(duration, dbUtil, notifierConfiguration); + } + + } catch (ApplicationSettingsException e) { + throw new ServletException("Error initializing notifier.", e); + } + + + info("Credential store callback initialized successfully."); + } + + @Override + public OA4MPService getOA4MPService() { + return oa4mpService; + } + + @Override + public void loadEnvironment() throws IOException { + environment = getConfigurationLoader().load(); + oa4mpService = new OA4MPService((ClientEnvironment) environment); + } + + @Override + protected void doIt(HttpServletRequest request, HttpServletResponse response) throws Throwable { + + String gatewayName = request.getParameter(CredentialStoreConstants.GATEWAY_NAME_QUERY_PARAMETER); + String portalUserName = request.getParameter(CredentialStoreConstants.PORTAL_USER_QUERY_PARAMETER); + String durationParameter = request.getParameter(CredentialStoreConstants.DURATION_QUERY_PARAMETER); + String contactEmail = request.getParameter(CredentialStoreConstants.PORTAL_USER_EMAIL_QUERY_PARAMETER); + String portalTokenId = request.getParameter(CredentialStoreConstants.PORTAL_TOKEN_ID_ASSIGNED); + + // TODO remove hard coded values, once passing query parameters is + // fixed in OA4MP client api + long duration = 864000; + + if (durationParameter != null) { + duration = Long.parseLong(durationParameter); + } + + if (portalTokenId == null) { + error("Token given by portal is invalid."); + GeneralException ge = new GeneralException("Error: The token presented by portal is null."); + request.setAttribute("exception", ge); + JSPUtil.fwd(request, response, configurationReader.getErrorUrl()); + return; + } + + info("Gateway name " + gatewayName); + info("Portal user name " + portalUserName); + info("Community user contact email " + contactEmail); + info("Token id presented " + portalTokenId); + + info("2.a. Getting token and verifier."); + String token = request.getParameter(CONST(ClientEnvironment.TOKEN)); + String verifier = request.getParameter(CONST(ClientEnvironment.VERIFIER)); + 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, configurationReader.getErrorUrl()); + return; + } + info("2.a Token and verifier found."); + X509Certificate[] certificates; + AssetResponse assetResponse = null; + + PrivateKey privateKey; + + try { + + PrivateKeyStore privateKeyStore = PrivateKeyStore.getPrivateKeyStore(); + privateKey = privateKeyStore.getKey(portalTokenId); + + if (privateKey != null) { + info("Found private key for token " + portalTokenId); + } else { + info("Could not find private key for token " + portalTokenId); + } + + info("2.a. Getting the cert(s) from the service"); + assetResponse = getOA4MPService().getCert(token, verifier); + + certificates = assetResponse.getX509Certificates(); + + } 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, configurationReader.getErrorUrl()); + return; + } + + info("2.b. Done! Displaying success page."); + + CertificateCredential certificateCredential = new CertificateCredential(); + + certificateCredential.setNotBefore(Utility.convertDateToString(certificates[0].getNotBefore())); //TODO check this is correct + certificateCredential.setNotAfter(Utility.convertDateToString(certificates[0].getNotAfter())); + certificateCredential.setCertificates(certificates); + certificateCredential.setPrivateKey(privateKey); + certificateCredential + .setCommunityUser(new CommunityUser(gatewayName, assetResponse.getUsername(), contactEmail)); + certificateCredential.setPortalUserName(portalUserName); + certificateCredential.setLifeTime(duration); + certificateCredential.setToken(portalTokenId); + + + certificateCredentialWriter.writeCredentials(certificateCredential); + + StringBuilder stringBuilder = new StringBuilder("Certificate for community user "); + stringBuilder.append(assetResponse.getUsername()).append(" successfully persisted."); + stringBuilder.append(" Certificate DN - ").append(certificates[0].getSubjectDN()); + + info(stringBuilder.toString()); + + if (isUrlInSameServer(configurationReader.getSuccessUrl())) { + + String contextPath = request.getContextPath(); + if (!contextPath.endsWith("/")) { + contextPath = contextPath + "/"; + } + request.setAttribute("action", contextPath); + request.setAttribute("tokenId", portalTokenId); + JSPUtil.fwd(request, response, configurationReader.getSuccessUrl()); + } else { + + String urlToRedirect = decorateUrlWithToken(configurationReader.getSuccessUrl(), portalTokenId); + + info("Redirecting to url - " + urlToRedirect); + + response.sendRedirect(urlToRedirect); + } + + info("2.a. Completely finished with delegation."); + + } + + private boolean isUrlInSameServer(String url) { + + return !(url.toLowerCase().startsWith("http") || url.toLowerCase().startsWith("https")); + + } + + private String decorateUrlWithToken(String url, String tokenId) { + + StringBuilder stringBuilder = new StringBuilder(url); + stringBuilder.append("?tokenId=").append(tokenId); + return stringBuilder.toString(); + } + + private Map<String, String> createQueryParameters(String gatewayName, String portalUserName, String portalEmail, + String tokenId) { + + String callbackUriKey = getEnvironment().getConstants().get(CALLBACK_URI_KEY); + ClientEnvironment clientEnvironment = (ClientEnvironment) getEnvironment(); + + String callbackUri = clientEnvironment.getCallback().toString(); + + StringBuilder stringBuilder = new StringBuilder(callbackUri); + + stringBuilder.append("?").append(CredentialStoreConstants.GATEWAY_NAME_QUERY_PARAMETER).append("=").append(gatewayName).append("&") + .append(CredentialStoreConstants.PORTAL_USER_QUERY_PARAMETER).append("=").append(portalUserName).append("&") + .append(CredentialStoreConstants.PORTAL_USER_EMAIL_QUERY_PARAMETER).append("=").append(portalEmail).append("&") + .append(CredentialStoreConstants.PORTAL_TOKEN_ID_ASSIGNED).append("=").append(tokenId); + + info("Callback URI is set to - " + stringBuilder.toString()); + + Map<String, String> parameters = new HashMap<String, String>(); + parameters.put(callbackUriKey, stringBuilder.toString()); + + return parameters; + + } +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreStartServlet.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreStartServlet.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreStartServlet.java new file mode 100644 index 0000000..3b70242 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreStartServlet.java @@ -0,0 +1,183 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +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.myproxy.oa4mp.client.servlet.ClientServlet; +import edu.uiuc.ncsa.security.servlet.JSPUtil; +import org.apache.airavata.credential.store.store.CredentialStoreException; +import org.apache.airavata.credential.store.util.ConfigurationReader; +import org.apache.airavata.credential.store.util.CredentialStoreConstants; +import org.apache.airavata.credential.store.util.PrivateKeyStore; +import org.apache.airavata.credential.store.util.TokenGenerator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.net.URI; +import java.util.HashMap; +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 static ConfigurationReader configurationReader = null; + + private static Logger log = LoggerFactory.getLogger(CredentialStoreStartServlet.class); + private OA4MPService oa4mpService; + + 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(); + + } + + public void init() throws ServletException { + + super.init(); + + try { + if (configurationReader == null) { + configurationReader = new ConfigurationReader(); + } + } catch (CredentialStoreException e) { + throw new ServletException(e); + } + + } + + @Override + public OA4MPService getOA4MPService() { + return oa4mpService; + } + + @Override + public void loadEnvironment() throws IOException { + environment = getConfigurationLoader().load(); + oa4mpService = new OA4MPService((ClientEnvironment) environment); + } + + @Override + protected void doIt(HttpServletRequest request, HttpServletResponse response) throws Throwable { + + String gatewayName + = request.getParameter(CredentialStoreConstants.GATEWAY_NAME_QUERY_PARAMETER); + String portalUserName + = request.getParameter(CredentialStoreConstants.PORTAL_USER_QUERY_PARAMETER); + String contactEmail + = request.getParameter(CredentialStoreConstants.PORTAL_USER_EMAIL_QUERY_PARAMETER); + String associatedToken = TokenGenerator.generateToken(gatewayName, portalUserName); + + if (gatewayName == null) { + JSPUtil.handleException(new RuntimeException("Please specify a gateway name."), request, response, + configurationReader.getErrorUrl()); + return; + } + + if (portalUserName == null) { + JSPUtil.handleException(new RuntimeException("Please specify a portal user name."), request, response, + configurationReader.getErrorUrl()); + return; + } + + if (contactEmail == null) { + JSPUtil.handleException(new RuntimeException("Please specify a contact email address for community" + + " user account."), request, response, configurationReader.getErrorUrl()); + return; + } + + log.info("1.a. Starting transaction"); + OA4MPResponse gtwResp; + + Map<String, String> queryParameters = new HashMap<String, String>(); + queryParameters.put(CredentialStoreConstants.GATEWAY_NAME_QUERY_PARAMETER, gatewayName); + queryParameters.put(CredentialStoreConstants.PORTAL_USER_QUERY_PARAMETER, portalUserName); + queryParameters.put(CredentialStoreConstants.PORTAL_USER_EMAIL_QUERY_PARAMETER, contactEmail); + queryParameters.put(CredentialStoreConstants.PORTAL_TOKEN_ID_ASSIGNED, associatedToken); + + Map<String, String> additionalParameters = new HashMap<String, String>(); + + if (getOA4MPService() == null) { + loadEnvironment(); + } + + String modifiedCallbackUri = decorateURI(getOA4MPService().getEnvironment().getCallback(), queryParameters); + + info("The modified callback URI - " + modifiedCallbackUri); + + additionalParameters.put(getEnvironment().getConstants().get(CALLBACK_URI_KEY), modifiedCallbackUri); + + try { + gtwResp = getOA4MPService().requestCert(additionalParameters); + + // Private key in store + PrivateKeyStore privateKeyStore = PrivateKeyStore.getPrivateKeyStore(); + privateKeyStore.addKey(associatedToken, gtwResp.getPrivateKey()); + + } catch (Throwable t) { + JSPUtil.handleException(t, request, response, configurationReader.getErrorUrl()); + 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, configurationReader.getPortalRedirectUrl()); + + } +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialReader.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialReader.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialReader.java new file mode 100644 index 0000000..fe54b8e --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialReader.java @@ -0,0 +1,112 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.airavata.credential.store.store; + +import org.apache.airavata.credential.store.credential.AuditInfo; +import org.apache.airavata.credential.store.credential.Credential; + +import java.util.List; + +/** + * This interface provides an API for Credential Store. Provides methods to manipulate credential store data. + */ +public interface CredentialReader { + + /** + * Retrieves the credential from the credential store. + * + * @param gatewayId + * The gateway id + * @param tokenId + * The token id associated with the credential + * @return The Credential object associated with the token. + * @throws CredentialStoreException + * If an error occurred while retrieving a credential. + */ + Credential getCredential(String gatewayId, String tokenId) throws CredentialStoreException; + + /** + * Gets the admin portal user name who retrieved given community user for given portal user name. + * + * @param gatewayName + * The gateway name + * @param tokenId + * The issued token id. + * @return The portal user name who requested given community user credentials. + */ + String getPortalUser(String gatewayName, String tokenId) throws CredentialStoreException; + + /** + * Gets audit information related to given gateway name and community user name. + * + * @param gatewayName + * The gateway name. + * @param tokenId + * The community user name. + * @return CertificateAuditInfo object. + */ + AuditInfo getAuditInfo(String gatewayName, String tokenId) throws CredentialStoreException; + + /** + * Gets all the credential records. + * @return All credential records as a list + * @throws CredentialStoreException If an error occurred while retrieving credentials. + */ + public List<Credential> getAllCredentials() throws CredentialStoreException; + + /** + * Updates the community user contact email address. + * + * @param gatewayName + * The gateway name. + * @param communityUser + * The community user name. + * @param email + * The new email address. + */ + void updateCommunityUserEmail(String gatewayName, String communityUser, String email) + throws CredentialStoreException; + + /** + * Will remove credentials for the given gateway id and community user. + * + * @param gatewayName + * The gateway Id + * @param tokenId + * The issued token id. + * @throws CredentialStoreException + * If an error occurred while retrieving data. + */ + void removeCredentials(String gatewayName, String tokenId) throws CredentialStoreException; + + /** + * Retrieves gatewayID from the credential store. + * + * @param tokenId + * The token id associated with the credential + * @return The Credential object associated with the token. + * @throws CredentialStoreException + * If an error occurred while retrieving a credential. + */ + String getGatewayID(String tokenId) throws CredentialStoreException; + +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialReaderFactory.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialReaderFactory.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialReaderFactory.java new file mode 100644 index 0000000..f4b5e21 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialReaderFactory.java @@ -0,0 +1,54 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.airavata.credential.store.store; + +import org.apache.airavata.common.exception.ApplicationSettingsException; +import org.apache.airavata.common.utils.DBUtil; +import org.apache.airavata.credential.store.store.impl.CredentialReaderImpl; + +/** + * Factory class to create credential store readers. + */ +public class CredentialReaderFactory { + + /** + * Creates a credential reader using supplied database configurations. + * @param dbUti The database configurations. + * @return CredentialReader object. + */ + public static CredentialReader createCredentialStoreReader(DBUtil dbUti) throws ApplicationSettingsException { + return new CredentialReaderImpl(dbUti); + } + + /** + * Creates credential reader using default configurations for credential store database. + * @return The credential reader. + * @throws ClassNotFoundException If an error occurred while instantiating jdbc driver + * @throws ApplicationSettingsException If an error occurred while reading database configurations. + * @throws InstantiationException If an error occurred while instantiating jdbc driver + * @throws IllegalAccessException A security exception accessing jdbc driver. + */ + public static CredentialReader createCredentialStoreReader() throws ClassNotFoundException, + ApplicationSettingsException, InstantiationException, IllegalAccessException { + return new CredentialReaderImpl(DBUtil.getCredentialStoreDBUtil()); + } +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialStoreException.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialStoreException.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialStoreException.java new file mode 100644 index 0000000..07bed10 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialStoreException.java @@ -0,0 +1,40 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.airavata.credential.store.store; + +/** + * An exception class for credential store. + */ +public class CredentialStoreException extends Exception { + + public CredentialStoreException() { + super(); + } + + public CredentialStoreException(String s) { + super(s); + } + + public CredentialStoreException(String s, Throwable throwable) { + super(s, throwable); + } +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialWriter.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialWriter.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialWriter.java new file mode 100644 index 0000000..05ae9fe --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/CredentialWriter.java @@ -0,0 +1,39 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.airavata.credential.store.store; + +import org.apache.airavata.credential.store.credential.Credential; + +/** + * 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; + +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/CertificateCredentialWriter.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/CertificateCredentialWriter.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/CertificateCredentialWriter.java new file mode 100644 index 0000000..8b96187 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/CertificateCredentialWriter.java @@ -0,0 +1,121 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.airavata.credential.store.store.impl; + +import org.apache.airavata.common.exception.ApplicationSettingsException; +import org.apache.airavata.common.utils.ApplicationSettings; +import org.apache.airavata.common.utils.DBUtil; +import org.apache.airavata.common.utils.DefaultKeyStorePasswordCallback; +import org.apache.airavata.credential.store.credential.CommunityUser; +import org.apache.airavata.credential.store.credential.Credential; +import org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential; +import org.apache.airavata.credential.store.store.impl.db.CommunityUserDAO; +import org.apache.airavata.credential.store.store.impl.db.CredentialsDAO; +import org.apache.airavata.credential.store.store.CredentialStoreException; +import org.apache.airavata.credential.store.store.CredentialWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.sql.Connection; +import java.sql.SQLException; + +/** + * Writes certificate credentials to database. + */ +public class CertificateCredentialWriter implements CredentialWriter { + + private CredentialsDAO credentialsDAO; + private CommunityUserDAO communityUserDAO; + + protected static Logger log = LoggerFactory.getLogger(CertificateCredentialWriter.class); + + private DBUtil dbUtil; + + public CertificateCredentialWriter(DBUtil dbUtil) throws ApplicationSettingsException { + + this.dbUtil = dbUtil; + + this.credentialsDAO = new CredentialsDAO(ApplicationSettings.getCredentialStoreKeyStorePath(), + ApplicationSettings.getCredentialStoreKeyAlias(), new DefaultKeyStorePasswordCallback()); + + communityUserDAO = new CommunityUserDAO(); + } + + public void writeCredentials(Credential credential) throws CredentialStoreException { + + CertificateCredential certificateCredential = (CertificateCredential) credential; + + Connection connection = null; + + try { + + connection = dbUtil.getConnection(); + // Write community user + writeCommunityUser(certificateCredential.getCommunityUser(), credential.getToken(), connection); + // First delete existing credentials + credentialsDAO.deleteCredentials(certificateCredential.getCommunityUser().getGatewayName(), + certificateCredential.getToken(), connection); + // Add the new certificate + credentialsDAO.addCredentials(certificateCredential.getCommunityUser().getGatewayName(), credential, + connection); + + if (!connection.getAutoCommit()) { + connection.commit(); + } + + } catch (SQLException e) { + if (connection != null) { + try { + connection.rollback(); + } catch (SQLException e1) { + log.error("Unable to rollback transaction", e1); + } + } + throw new CredentialStoreException("Unable to retrieve database connection.", e); + } finally { + DBUtil.cleanup(connection); + } + + } + + public void writeCommunityUser(CommunityUser communityUser, String token, Connection connection) + throws CredentialStoreException { + + // First delete existing community user + communityUserDAO.deleteCommunityUserByToken(communityUser, token, connection); + + // Persist new community user + communityUserDAO.addCommunityUser(communityUser, token, connection); + + } + + /* + * TODO Remove later - If we dont need to expose this in the interface public void writeCommunityUser(CommunityUser + * communityUser, String token) throws CredentialStoreException { + * + * Connection connection = null; try { connection = dbUtil.getConnection(); writeCommunityUser(communityUser, token, + * connection); + * + * } catch (SQLException e) { throw new CredentialStoreException("Unable to retrieve database connection.", e); } + * finally { DBUtil.cleanup(connection); } } + */ +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/CredentialReaderImpl.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/CredentialReaderImpl.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/CredentialReaderImpl.java new file mode 100644 index 0000000..dc2fd60 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/CredentialReaderImpl.java @@ -0,0 +1,162 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.airavata.credential.store.store.impl; + +import org.apache.airavata.common.exception.ApplicationSettingsException; +import org.apache.airavata.common.utils.ApplicationSettings; +import org.apache.airavata.common.utils.DBUtil; +import org.apache.airavata.common.utils.DefaultKeyStorePasswordCallback; +import org.apache.airavata.credential.store.credential.CommunityUser; +import org.apache.airavata.credential.store.credential.Credential; +import org.apache.airavata.credential.store.credential.impl.certificate.CertificateAuditInfo; +import org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential; +import org.apache.airavata.credential.store.store.CredentialReader; +import org.apache.airavata.credential.store.store.impl.db.CredentialsDAO; +import org.apache.airavata.credential.store.store.CredentialStoreException; + +import java.io.Serializable; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; + +/** + * Credential store API implementation. + */ +public class CredentialReaderImpl implements CredentialReader, Serializable { + + private CredentialsDAO credentialsDAO; + + private DBUtil dbUtil; + + public CredentialReaderImpl(DBUtil dbUtil) throws ApplicationSettingsException { + + this.credentialsDAO = new CredentialsDAO(ApplicationSettings.getCredentialStoreKeyStorePath(), + ApplicationSettings.getCredentialStoreKeyAlias(), new DefaultKeyStorePasswordCallback()); + + this.dbUtil = dbUtil; + } + + private Connection getConnection() throws CredentialStoreException { + try { + return this.dbUtil.getConnection(); + } catch (SQLException e) { + throw new CredentialStoreException("Unable to retrieve database connection.", e); + } + } + + @Override + public Credential getCredential(String gatewayId, String tokenId) throws CredentialStoreException { + + Connection connection = getConnection(); + + try { + return this.credentialsDAO.getCredential(gatewayId, tokenId, connection); + } finally { + DBUtil.cleanup(connection); + } + } + + public List<Credential> getAllCredentials() throws CredentialStoreException { + + Connection connection = getConnection(); + + try { + return this.credentialsDAO.getCredentials(connection); + } finally { + DBUtil.cleanup(connection); + } + + } + + public String getPortalUser(String gatewayName, String tokenId) throws CredentialStoreException { + + Connection connection = getConnection(); + + Credential credential; + + try { + credential = this.credentialsDAO.getCredential(gatewayName, tokenId, connection); + + } finally { + DBUtil.cleanup(connection); + } + + return credential.getPortalUserName(); + } + + public CertificateAuditInfo getAuditInfo(String gatewayName, String tokenId) throws CredentialStoreException { + + Connection connection = getConnection(); + + CertificateAuditInfo certificateAuditInfo; + + try { + + CertificateCredential certificateCredential = (CertificateCredential) this.credentialsDAO.getCredential( + gatewayName, tokenId, connection); + + certificateAuditInfo = new CertificateAuditInfo(); + + CommunityUser retrievedUser = certificateCredential.getCommunityUser(); + certificateAuditInfo.setCommunityUserName(retrievedUser.getUserName()); + certificateAuditInfo.setCredentialLifeTime(certificateCredential.getLifeTime()); + certificateAuditInfo.setCredentialsRequestedTime(certificateCredential.getCertificateRequestedTime()); + certificateAuditInfo.setGatewayName(gatewayName); + certificateAuditInfo.setNotAfter(certificateCredential.getNotAfter()); + certificateAuditInfo.setNotBefore(certificateCredential.getNotBefore()); + certificateAuditInfo.setPortalUserName(certificateCredential.getPortalUserName()); + + } finally { + DBUtil.cleanup(connection); + } + + return certificateAuditInfo; + } + + public void updateCommunityUserEmail(String gatewayName, String communityUser, String email) + throws CredentialStoreException { + // TODO + } + + public void removeCredentials(String gatewayName, String tokenId) throws CredentialStoreException { + + Connection connection = getConnection(); + + try { + credentialsDAO.deleteCredentials(gatewayName, tokenId, connection); + } finally { + DBUtil.cleanup(connection); + } + + } + + @Override + public String getGatewayID(String tokenId) throws CredentialStoreException { + Connection connection = getConnection(); + try { + return this.credentialsDAO.getGatewayID(tokenId, connection); + } finally { + DBUtil.cleanup(connection); + } + } + +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/SSHCredentialWriter.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/SSHCredentialWriter.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/SSHCredentialWriter.java new file mode 100644 index 0000000..ad4f6b3 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/SSHCredentialWriter.java @@ -0,0 +1,87 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.airavata.credential.store.store.impl; + +import java.sql.Connection; +import java.sql.SQLException; + +import org.apache.airavata.common.exception.ApplicationSettingsException; +import org.apache.airavata.common.utils.ApplicationSettings; +import org.apache.airavata.common.utils.DBUtil; +import org.apache.airavata.common.utils.DefaultKeyStorePasswordCallback; +import org.apache.airavata.credential.store.credential.Credential; +import org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential; +import org.apache.airavata.credential.store.store.CredentialStoreException; +import org.apache.airavata.credential.store.store.CredentialWriter; +import org.apache.airavata.credential.store.store.impl.db.CredentialsDAO; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Writes SSH credentials to database. + */ +public class SSHCredentialWriter implements CredentialWriter { + + private CredentialsDAO credentialsDAO; + private DBUtil dbUtil; + + protected static Logger logger = LoggerFactory.getLogger(SSHCredentialWriter.class); + + public SSHCredentialWriter(DBUtil dbUtil) throws ApplicationSettingsException { + this.dbUtil = dbUtil; + this.credentialsDAO = new CredentialsDAO(ApplicationSettings.getCredentialStoreKeyStorePath(), + ApplicationSettings.getCredentialStoreKeyAlias(), new DefaultKeyStorePasswordCallback()); + + } + + public void writeCredentials(Credential credential) throws CredentialStoreException { + + SSHCredential sshCredential = (SSHCredential) credential; + Connection connection = null; + + try { + connection = dbUtil.getConnection(); + // First delete existing credentials + credentialsDAO.deleteCredentials(sshCredential.getGateway(), sshCredential.getToken(), connection); + // Add the new certificate + credentialsDAO.addCredentials(sshCredential.getGateway(), credential, connection); + + if (!connection.getAutoCommit()) { + connection.commit(); + } + + } catch (SQLException e) { + if (connection != null) { + try { + connection.rollback(); + } catch (SQLException e1) { + logger.error("Unable to rollback transaction", e1); + } + } + throw new CredentialStoreException("Unable to retrieve database connection.", e); + } finally { + DBUtil.cleanup(connection); + } + + } + +} http://git-wip-us.apache.org/repos/asf/airavata/blob/58c58cf2/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/CommunityUserDAO.java ---------------------------------------------------------------------- diff --git a/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/CommunityUserDAO.java b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/CommunityUserDAO.java new file mode 100644 index 0000000..f55cd55 --- /dev/null +++ b/modules/credential-store/credential-store-service/src/main/java/org/apache/airavata/credential/store/store/impl/db/CommunityUserDAO.java @@ -0,0 +1,257 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.airavata.credential.store.store.impl.db; + +import org.apache.airavata.common.utils.DBUtil; +import org.apache.airavata.credential.store.credential.CommunityUser; +import org.apache.airavata.credential.store.store.CredentialStoreException; + +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() { + super(); + } + + public void addCommunityUser(CommunityUser user, String token, Connection connection) + throws CredentialStoreException { + + String sql = "INSERT INTO COMMUNITY_USER VALUES (?, ?, ?, ?)"; + + PreparedStatement preparedStatement = null; + + try { + preparedStatement = connection.prepareStatement(sql); + + preparedStatement.setString(1, user.getGatewayName()); + preparedStatement.setString(2, user.getUserName()); + preparedStatement.setString(3, token); + preparedStatement.setString(4, 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()); + stringBuilder.append("token id - ").append(token); + + log.error(stringBuilder.toString(), e); + + throw new CredentialStoreException(stringBuilder.toString(), e); + } finally { + + DBUtil.cleanup(preparedStatement); + } + } + + public void deleteCommunityUser(CommunityUser user, Connection connection) throws CredentialStoreException { + + String sql = "DELETE FROM COMMUNITY_USER WHERE GATEWAY_NAME=? AND COMMUNITY_USER_NAME=?"; + + PreparedStatement preparedStatement = null; + + try { + 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); + } + } + + public void deleteCommunityUserByToken(CommunityUser user, String token, Connection connection) + throws CredentialStoreException { + + String sql = "DELETE FROM COMMUNITY_USER WHERE GATEWAY_NAME=? AND COMMUNITY_USER_NAME=? AND TOKEN_ID=?"; + + PreparedStatement preparedStatement = null; + + try { + preparedStatement = connection.prepareStatement(sql); + + preparedStatement.setString(1, user.getGatewayName()); + preparedStatement.setString(2, user.getUserName()); + preparedStatement.setString(3, token); + + 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); + } + } + + public void updateCommunityUser(CommunityUser user) throws CredentialStoreException { + + // TODO + } + + public CommunityUser getCommunityUser(String gatewayName, String communityUserName, Connection connection) + throws CredentialStoreException { + + String sql = "SELECT * FROM COMMUNITY_USER WHERE GATEWAY_NAME=? AND COMMUNITY_USER_NAME=?"; + + PreparedStatement preparedStatement = null; + + try { + 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); + } + + return null; + } + + public CommunityUser getCommunityUserByToken(String gatewayName, String tokenId, Connection connection) + throws CredentialStoreException { + + String sql = "SELECT * FROM COMMUNITY_USER WHERE GATEWAY_NAME=? AND TOKEN_ID=?"; + + PreparedStatement preparedStatement = null; + + try { + preparedStatement = connection.prepareStatement(sql); + + preparedStatement.setString(1, gatewayName); + preparedStatement.setString(2, tokenId); + + ResultSet resultSet = preparedStatement.executeQuery(); + + if (resultSet.next()) { + String communityUserName = resultSet.getString("COMMUNITY_USER_NAME"); + 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("token- ").append(tokenId); + + log.error(stringBuilder.toString(), e); + + throw new CredentialStoreException(stringBuilder.toString(), e); + } finally { + DBUtil.cleanup(preparedStatement); + } + + return null; + } + + public List<CommunityUser> getCommunityUsers(String gatewayName, Connection connection) + throws CredentialStoreException { + + List<CommunityUser> userList = new ArrayList<CommunityUser>(); + + String sql = "SELECT * FROM COMMUNITY_USER WHERE GATEWAY_NAME=?"; + + PreparedStatement preparedStatement = null; + + try { + 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); + } + + return userList; + } + +}
