You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airavata.apache.org by ch...@apache.org on 2014/06/24 20:23:38 UTC
[4/5] initial changes to make credential store as a seperate webapp
http://git-wip-us.apache.org/repos/asf/airavata/blob/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/credential/impl/ssh/SSHCredentialGenerator.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/credential/impl/ssh/SSHCredentialGenerator.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/credential/impl/ssh/SSHCredentialGenerator.java
new file mode 100644
index 0000000..d8bad04
--- /dev/null
+++ b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/credential/impl/ssh/SSHCredentialGenerator.java
@@ -0,0 +1,91 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.credential.impl.ssh;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.apache.airavata.credential.store.store.CredentialStoreException;
+import org.apache.airavata.credential.store.store.impl.SSHCredentialWriter;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.lang.RandomStringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+import com.jcraft.jsch.KeyPair;
+
+/**
+ * A class which generates an SSH credential
+ */
+public class SSHCredentialGenerator {
+
+ private static Logger logger = LoggerFactory.getLogger(SSHCredentialWriter.class);
+
+ /**
+ *
+ * @return a SSH Credential generated and encrypted using a randomly generated password
+ * @throws CredentialStoreException
+ */
+ public SSHCredential generateCredential(String tokenId) throws CredentialStoreException {
+ JSch jsch=new JSch();
+ try {
+ KeyPair kpair=KeyPair.genKeyPair(jsch, KeyPair.RSA);
+ File file;
+
+ file = File.createTempFile("id_rsa", "");
+
+ String fileName = file.getAbsolutePath();
+
+ String password = generateRandomString();
+ // We are encrypting the private key with the hash of (tokenId+password).
+ // Any client which wants to use this private key will also generate a hash and then use it to decrypt the key.
+ kpair.writePrivateKey(fileName,generateHash(tokenId,password).getBytes());
+ kpair.writePublicKey(fileName + ".pub" , "");
+ kpair.dispose();
+ byte[] priKey = FileUtils.readFileToByteArray(new File(fileName));
+ byte[] pubKey = FileUtils.readFileToByteArray(new File(fileName + ".pub"));
+ SSHCredential sshCredential = new SSHCredential();
+ sshCredential.setPrivateKey(priKey);
+ sshCredential.setPublicKey(pubKey);
+ sshCredential.setPassphrase(password);
+ return sshCredential;
+ } catch (IOException e) {
+ logger.error("IO Exception when creating SSH credential ",e);
+ throw new CredentialStoreException("Unable to generate SSH Credential", e);
+ } catch (JSchException e) {
+ logger.error("JSch SSH credential creation exception ",e);
+ throw new CredentialStoreException("Unable to generate SSH Credential. JSch exception ", e);
+ }
+ }
+
+ private String generateHash(String tokenId, String password) {
+ // TODO: Hash the password generated and return it
+ return null;
+ }
+
+ // Generate a random alphanumberic string of 16 characters length
+ private String generateRandomString() {
+ return RandomStringUtils.randomAlphanumeric(16);
+ }
+}
http://git-wip-us.apache.org/repos/asf/airavata/blob/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/CredentialStoreNotifier.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/CredentialStoreNotifier.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/CredentialStoreNotifier.java
new file mode 100644
index 0000000..62b6e27
--- /dev/null
+++ b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/CredentialStoreNotifier.java
@@ -0,0 +1,42 @@
+package org.apache.airavata.credential.store.notifier;/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+
+
+import org.apache.airavata.credential.store.store.CredentialStoreException;
+
+/**
+ * This class is used to notify particular entity with expiring credentials.
+ * The default implementation uses email messages.
+ * User: AmilaJ (amilaj@apache.org)
+ * Date: 12/3/13
+ * Time: 4:17 PM
+ */
+public interface CredentialStoreNotifier {
+
+ /**
+ * The specific notifier implementation needs to implement following method.
+ * This method should actually deliver message to desired entity.
+ * @param message The actual message encapsulated
+ * @throws CredentialStoreException
+ */
+ void notifyMessage(NotificationMessage message) throws CredentialStoreException;
+
+}
http://git-wip-us.apache.org/repos/asf/airavata/blob/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/NotificationMessage.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/NotificationMessage.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/NotificationMessage.java
new file mode 100644
index 0000000..96f0bd9
--- /dev/null
+++ b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/NotificationMessage.java
@@ -0,0 +1,46 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+/**
+ * User: AmilaJ (amilaj@apache.org)
+ * Date: 12/3/13
+ * Time: 4:21 PM
+ */
+
+/**
+ * Encapsulates the notification message.
+ * Usually says particular credential is expiring and need to renew.
+ */
+public class NotificationMessage {
+
+ protected String message;
+
+ public NotificationMessage(String msg) {
+ this.message = msg;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/airavata/blob/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/NotifierBootstrap.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/NotifierBootstrap.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/NotifierBootstrap.java
new file mode 100644
index 0000000..de84ae2
--- /dev/null
+++ b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/NotifierBootstrap.java
@@ -0,0 +1,144 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+/**
+ * User: AmilaJ (amilaj@apache.org)
+ * Date: 12/27/13
+ * Time: 2:22 PM
+ */
+
+import org.apache.airavata.common.exception.ApplicationSettingsException;
+import org.apache.airavata.common.utils.DBUtil;
+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.notifier.impl.EmailNotificationMessage;
+import org.apache.airavata.credential.store.notifier.impl.EmailNotifier;
+import org.apache.airavata.credential.store.notifier.impl.EmailNotifierConfiguration;
+import org.apache.airavata.credential.store.store.CredentialReader;
+import org.apache.airavata.credential.store.store.CredentialStoreException;
+import org.apache.airavata.credential.store.store.impl.CredentialReaderImpl;
+import org.apache.airavata.credential.store.util.Utility;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+/**
+ * This class runs a timer. Periodically it checks for expiring credentials.
+ * Then if there are expiring credentials this will send an email.
+ */
+public class NotifierBootstrap extends TimerTask {
+
+ private static boolean enabled = false;
+
+ private static String MESSAGE = "Credentials for community user {0} expires at {1}";
+ private static String SUBJECT = "Expiring credentials for user {0}";
+
+ private DBUtil dbUtil;
+
+ private long period;
+
+ protected static Logger log = LoggerFactory.getLogger(NotifierBootstrap.class);
+
+
+ private CredentialStoreNotifier credentialStoreNotifier;
+
+ public NotifierBootstrap(long period, DBUtil db, EmailNotifierConfiguration configuration) {
+ this.period = period;
+
+ // bootstrap
+ if (enabled) {
+ Timer timer = new Timer();
+ timer.scheduleAtFixedRate(this, 0, period);
+ }
+
+ this.dbUtil = db;
+
+ this.credentialStoreNotifier = new EmailNotifier(configuration);
+ }
+
+
+
+ public long getPeriod() {
+ return period;
+ }
+
+ public void setPeriod(long period) {
+ this.period = period;
+ }
+
+ public static boolean isEnabled() {
+ return enabled;
+ }
+
+ public static void setEnabled(boolean enabled) {
+ NotifierBootstrap.enabled = enabled;
+ }
+
+ @Override
+ public void run() {
+
+ if (!enabled)
+ return;
+
+ // retrieve OA4MP credentials
+ try {
+ CredentialReader credentialReader = new CredentialReaderImpl(this.dbUtil);
+ List<Credential> credentials = credentialReader.getAllCredentials();
+
+ for(Credential credential : credentials) {
+ if (credential instanceof CertificateCredential) {
+ CertificateCredential certificateCredential = (CertificateCredential)credential;
+
+ Date date = Utility.convertStringToDate(certificateCredential.getNotAfter());
+ date.setDate(date.getDate() + 1); // gap is 1 days
+
+ Date currentDate = new Date();
+ if (currentDate.after(date)) {
+ // Send an email
+ CommunityUser communityUser = certificateCredential.getCommunityUser();
+ String body =
+ String.format(MESSAGE, communityUser.getUserName(), certificateCredential.getNotAfter());
+ String subject = String.format(SUBJECT, communityUser.getUserName());
+ NotificationMessage notificationMessage
+ = new EmailNotificationMessage(subject, communityUser.getUserEmail(), body);
+
+ this.credentialStoreNotifier.notifyMessage(notificationMessage);
+
+ }
+ }
+ }
+
+ } catch (ApplicationSettingsException e) {
+ log.error("Error configuring email senders.", e);
+ } catch (CredentialStoreException e) {
+ log.error("Error sending emails about credential expiring.", e);
+ } catch (ParseException e) {
+ log.error("Error parsing date time when sending emails", e);
+ }
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/airavata/blob/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotificationMessage.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotificationMessage.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotificationMessage.java
new file mode 100644
index 0000000..ffd84c8
--- /dev/null
+++ b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotificationMessage.java
@@ -0,0 +1,58 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.NotificationMessage;
+
+/**
+ * User: AmilaJ (amilaj@apache.org)
+ * Date: 12/3/13
+ * Time: 5:01 PM
+ */
+
+public class EmailNotificationMessage extends NotificationMessage {
+
+ public EmailNotificationMessage(String subject, String senderEmail, String msg) {
+ super(msg);
+ this.subject = subject;
+ this.senderEmail = senderEmail;
+ }
+
+ private String subject;
+ private String senderEmail;
+
+ public String getSubject() {
+ return subject;
+ }
+
+ public void setSubject(String subject) {
+ this.subject = subject;
+ }
+
+ public String getSenderEmail() {
+ return senderEmail;
+ }
+
+ public void setSenderEmail(String senderEmail) {
+ this.senderEmail = senderEmail;
+ }
+}
http://git-wip-us.apache.org/repos/asf/airavata/blob/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifier.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifier.java b/modules/credential-store-service/credential-store/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-service/credential-store/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 (amilaj@apache.org)
+ * 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/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifierConfiguration.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/notifier/impl/EmailNotifierConfiguration.java b/modules/credential-store-service/credential-store/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-service/credential-store/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 (amilaj@apache.org)
+ * 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/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialBootstrapper.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialBootstrapper.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialBootstrapper.java
new file mode 100644
index 0000000..b2e8786
--- /dev/null
+++ b/modules/credential-store-service/credential-store/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/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreCallbackServlet.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreCallbackServlet.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreCallbackServlet.java
new file mode 100644
index 0000000..f232a00
--- /dev/null
+++ b/modules/credential-store-service/credential-store/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 = 800;
+
+ 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(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, 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/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreStartServlet.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreStartServlet.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreStartServlet.java
new file mode 100644
index 0000000..f5358b2
--- /dev/null
+++ b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/servlet/CredentialStoreStartServlet.java
@@ -0,0 +1,164 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.OA4MPResponse;
+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.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);
+
+ 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
+ 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>();
+
+ 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/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialReader.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialReader.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialReader.java
new file mode 100644
index 0000000..eea85f0
--- /dev/null
+++ b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialReader.java
@@ -0,0 +1,101 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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;
+
+}
http://git-wip-us.apache.org/repos/asf/airavata/blob/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialReaderFactory.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialReaderFactory.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialReaderFactory.java
new file mode 100644
index 0000000..f4b5e21
--- /dev/null
+++ b/modules/credential-store-service/credential-store/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/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialStoreException.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialStoreException.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialStoreException.java
new file mode 100644
index 0000000..07bed10
--- /dev/null
+++ b/modules/credential-store-service/credential-store/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/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialWriter.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialWriter.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/CredentialWriter.java
new file mode 100644
index 0000000..05ae9fe
--- /dev/null
+++ b/modules/credential-store-service/credential-store/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/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/impl/CertificateCredentialWriter.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/impl/CertificateCredentialWriter.java b/modules/credential-store-service/credential-store/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-service/credential-store/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/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/impl/CredentialReaderImpl.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/impl/CredentialReaderImpl.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/impl/CredentialReaderImpl.java
new file mode 100644
index 0000000..79d362b
--- /dev/null
+++ b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/impl/CredentialReaderImpl.java
@@ -0,0 +1,152 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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);
+ }
+
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/airavata/blob/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/impl/SSHCredentialWriter.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/impl/SSHCredentialWriter.java b/modules/credential-store-service/credential-store/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-service/credential-store/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/5c7acf30/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/impl/db/CommunityUserDAO.java
----------------------------------------------------------------------
diff --git a/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/impl/db/CommunityUserDAO.java b/modules/credential-store-service/credential-store/src/main/java/org/apache/airavata/credential/store/store/impl/db/CommunityUserDAO.java
new file mode 100644
index 0000000..9d3de23
--- /dev/null
+++ b/modules/credential-store-service/credential-store/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;
+ }
+
+}