diff options
author | VENKATESH KUMAR <vv770d@att.com> | 2017-08-22 17:42:43 -0400 |
---|---|---|
committer | VENKATESH KUMAR <vv770d@att.com> | 2017-08-22 17:44:46 -0400 |
commit | 7506eae7723fc4e8c1bd7952fe93c4924ea29cda (patch) | |
tree | 0a52a0f32cbd896c8149b64fa981630ab64393c7 /src/main/org/onap/ecomp/usermanagement | |
parent | a30008bfaac90f9acc068dda471552fc68cb98cc (diff) |
[CCSDK-36] seedcode for northbound api
Change-Id: If48afb138dbab2fb1eed4d3591f02524489e994e
Signed-off-by: VENKATESH KUMAR <vv770d@att.com>
Diffstat (limited to 'src/main/org/onap/ecomp/usermanagement')
5 files changed, 1190 insertions, 0 deletions
diff --git a/src/main/org/onap/ecomp/usermanagement/EcompRole.java b/src/main/org/onap/ecomp/usermanagement/EcompRole.java new file mode 100644 index 0000000..68fbfed --- /dev/null +++ b/src/main/org/onap/ecomp/usermanagement/EcompRole.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ecomp.usermanagement; + +/** + * This class holds the information for a role. + * + */ +public class EcompRole implements Comparable<EcompRole>{ + + protected Long id; + private String name; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + EcompRole other = (EcompRole) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + + @Override + public String toString() { + String s = "@EcompRole[id: " + id + "; name: " + name + "]"; + return s; + } + + @Override + public int compareTo(EcompRole o) { + return this.id.compareTo(o.id); + } +} diff --git a/src/main/org/onap/ecomp/usermanagement/EcompUser.java b/src/main/org/onap/ecomp/usermanagement/EcompUser.java new file mode 100644 index 0000000..a36d45f --- /dev/null +++ b/src/main/org/onap/ecomp/usermanagement/EcompUser.java @@ -0,0 +1,193 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ecomp.usermanagement; + +import java.util.Set; + +/** + * This class holds the information for a user. + * + */ +public class EcompUser implements Comparable<EcompUser>{ + + private Long orgId; + private String managerId; + private String firstName; + private String middleInitial; + private String lastName; + private String phone; + private String email; + private String hrid; + private String orgUserId; + private String orgCode; + private String orgManagerUserId; + private String jobTitle; + private String loginId; + private boolean active; + + + private Set<EcompRole> roles; + + public Long getOrgId() { + return orgId; + } + + public void setOrgId(Long orgId) { + this.orgId = orgId; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getMiddleInitial() { + return middleInitial; + } + + public void setMiddleInitial(String middleInitial) { + this.middleInitial = middleInitial; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getHrid() { + return hrid; + } + + public void setHrid(String hrid) { + this.hrid = hrid; + } + + public String getOrgUserId() { + return orgUserId; + } + + public void setOrgUserId(String orgUserId) { + this.orgUserId = orgUserId; + } + + public String getOrgCode() { + return orgCode; + } + + public void setOrgCode(String orgCode) { + this.orgCode = orgCode; + } + + public String getOrgManagerUserId() { + return orgManagerUserId; + } + + public void setOrgManagerUserId(String orgManagerUserId) { + this.orgManagerUserId = orgManagerUserId; + } + + public String getJobTitle() { + return jobTitle; + } + + public void setJobTitle(String jobTitle) { + this.jobTitle = jobTitle; + } + + public String getLoginId() { + return loginId; + } + + public void setLoginId(String loginId) { + this.loginId = loginId; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + + public Set<EcompRole> getRoles() { + return roles; + } + + public void setRoles(Set<EcompRole> roles) { + this.roles = roles; + } + + public String getManagerId() { + return managerId; + } + + public void setManagerId(String managerId) { + this.managerId = managerId; + } + + @Override + public String toString() { + String s = "@EcompUser[orgId: " + orgId // + + ", firstName: " + firstName // + + ", mi: " + middleInitial // + + ", lastName: " + lastName // + + ", phone: " + phone // + + ", email: " + email // + + ", hrid: " + hrid // + + ", orgUserId: " + orgUserId // + + ", orgCode: " + orgCode // + + ", orgManagerUserId: " + orgManagerUserId // + + ", jobTitle: " + jobTitle // + + ", loginId: " + loginId // + + ", active:" + active // + + "]"; + return s; + } + + @Override + public int compareTo(EcompUser o) { + return this.loginId.compareTo(o.loginId); + } +}
\ No newline at end of file diff --git a/src/main/org/onap/ecomp/usermanagement/EcompUserManagementDao.java b/src/main/org/onap/ecomp/usermanagement/EcompUserManagementDao.java new file mode 100644 index 0000000..a4d506d --- /dev/null +++ b/src/main/org/onap/ecomp/usermanagement/EcompUserManagementDao.java @@ -0,0 +1,413 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ecomp.usermanagement; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.onap.ecomp.persistence.APIHDBSource; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +/* + * + */ +public class EcompUserManagementDao { + final static EELFLogger logger = EELFManager.getInstance().getLogger(EcompUserManagementDao.class); + private APIHDBSource apihDBSource = null; + + public EcompUserManagementDao() { + apihDBSource = APIHDBSource.getInstance(); + } + /* + * + */ + private void logException(Exception e) { + StringWriter stack = new StringWriter(); + e.printStackTrace(new PrintWriter(stack)); + logger.info(stack.toString()); + } + + private void close(Connection conn, Statement st, ResultSet rs ) { + apihDBSource.close(conn); + apihDBSource.close(st); + apihDBSource.close(rs); + } + + public List<EcompRole> getRoles() { + logger.info("Received request: getRoles"); + List<EcompRole> roles = null; + ResultSet rs = null; + Statement st = null; + Connection conn = null; + String sql = "SELECT role_id, role_name FROM fn_role where active_yn='Y';"; + logger.info(sql); + try { + conn = apihDBSource.getConnection(); + st = conn.createStatement(); + rs = st.executeQuery(sql); + roles = new ArrayList<EcompRole>(); + while (rs.next()) { + String roleName = rs.getString("role_name"); + Long id = rs.getLong("role_id"); + EcompRole role = new EcompRole(); + role.setId(id); + role.setName(roleName); + roles.add(role); + } + logger.info("found " + roles.size() + " record(s)."); + } + catch (Exception e ) { + this.logException(e); + } + finally { + this.close(conn, st, rs ); + } + return roles; + } + /* + * + */ + public List<EcompRole> getRoles(String userId) { + logger.info("Received request: getRoles/userId:" + userId); + List<EcompRole> roles = null; + ResultSet rs = null; + Statement st = null; + Connection conn = null; + String sql = "select r.role_id, r.role_name " + + " from fn_user_role ur, fn_role r, fn_user u " + + " where u.org_user_id=" + "'" + userId + "'" + + " and ur.role_id=r.role_id " + + " and u.user_id = ur.user_id; "; + logger.info(sql); + try { + conn = apihDBSource.getConnection(); + st = conn.createStatement(); + rs = st.executeQuery(sql); + roles = new ArrayList<EcompRole>(); + while (rs.next()) { + String roleName = rs.getString("role_name"); + Long id = rs.getLong("role_id"); + EcompRole role = new EcompRole(); + role.setId(id); + role.setName(roleName); + roles.add(role); + } + logger.info("found " + roles.size() + " record(s)."); + } + catch (Exception e ) { + this.logException(e); + } + finally { + this.close(conn, st, rs ); + } + return roles; + } + /* + * + */ + public List<EcompUser> getUsers() { + logger.info("Received request: getUsers"); + List<EcompUser> ecompUsers = null; + ResultSet rs = null; + Statement st = null; + Connection conn = null; + String sql = "SELECT org_id, manager_id, first_name, middle_name, last_name, phone, " + + " email, hrid, org_user_id, org_code, org_manager_userid, job_title, " + + " login_id, active_yn FROM fn_user;"; + logger.info(sql); + try { + conn = apihDBSource.getConnection(); + st = conn.createStatement(); + rs = st.executeQuery(sql); + ecompUsers = new ArrayList<EcompUser>(); + while (rs.next()) { + Long orgId = rs.getLong("org_id"); + String managerId = rs.getString("manager_id"); + String firstName = rs.getString("first_name");; + String middleInitial = rs.getString("middle_name"); + String lastName = rs.getString("last_name"); + String phone = rs.getString("phone"); + String email = rs.getString("email"); + String hrid = rs.getString("hrid"); + String orgUserId = rs.getString("org_user_id"); + String orgCode = rs.getString("org_code"); + String orgManagerUserId = rs.getString("org_manager_userid"); + String jobTitle = rs.getString("job_title"); + String loginId = rs.getString("login_id"); + boolean active = rs.getBoolean("active_yn"); + + EcompUser ecompUser = new EcompUser(); + ecompUser.setOrgId(orgId); + ecompUser.setManagerId(managerId); + ecompUser.setFirstName(firstName); + ecompUser.setMiddleInitial(middleInitial); + ecompUser.setLastName(lastName); + ecompUser.setPhone(phone); + ecompUser.setEmail(email); + ecompUser.setHrid(hrid); + ecompUser.setOrgUserId(orgUserId); + ecompUser.setOrgCode(orgCode); + ecompUser.setOrgManagerUserId(orgManagerUserId); + ecompUser.setJobTitle(jobTitle); + ecompUser.setLoginId(loginId); + ecompUser.setActive(active); + + ecompUsers.add(ecompUser); + } + logger.info("found " + ecompUsers.size() + " record(s)."); + + for (EcompUser user : ecompUsers ) { + String userId = user.getOrgUserId(); + List<EcompRole> roles = getRoles(userId); + Set<EcompRole> setRoles = new HashSet<EcompRole>(roles); + user.setRoles(setRoles); + } + } + catch (Exception e ) { + this.logException(e); + } + finally { + this.close(conn, st, rs ); + } + return ecompUsers; + } + /* + * + */ + public List<EcompUser> getUser(String uid) { + logger.info("Received request: getUser:" + uid); + List<EcompUser> ecompUsers = null; + ResultSet rs = null; + Statement st = null; + Connection conn = null; + String sql = "SELECT org_id, manager_id, first_name, " + + " middle_name, last_name, phone, email, hrid, " + + " org_user_id, org_code, org_manager_userid, job_title, " + + " login_id, active_yn " + + " FROM fn_user " + + " where org_user_id = " + "'" + uid + "'"; + logger.info(sql); + try { + conn = apihDBSource.getConnection(); + st = conn.createStatement(); + rs = st.executeQuery(sql); + ecompUsers = new ArrayList<EcompUser>(); + while (rs.next()) { + Long orgId = rs.getLong("org_id"); + String managerId = rs.getString("manager_id"); + String firstName = rs.getString("first_name");; + String middleInitial = rs.getString("middle_name"); + String lastName = rs.getString("last_name"); + String phone = rs.getString("phone"); + String email = rs.getString("email"); + String hrid = rs.getString("hrid"); + String orgUserId = rs.getString("org_user_id"); + String orgCode = rs.getString("org_code"); + String orgManagerUserId = rs.getString("org_manager_userid"); + String jobTitle = rs.getString("job_title"); + String loginId = rs.getString("login_id"); + boolean active = rs.getBoolean("active_yn"); + + EcompUser ecompUser = new EcompUser(); + ecompUser.setOrgId(orgId); + ecompUser.setManagerId(managerId); + ecompUser.setFirstName(firstName); + ecompUser.setMiddleInitial(middleInitial); + ecompUser.setLastName(lastName); + ecompUser.setPhone(phone); + ecompUser.setEmail(email); + ecompUser.setHrid(hrid); + ecompUser.setOrgUserId(orgUserId); + ecompUser.setOrgCode(orgCode); + ecompUser.setOrgManagerUserId(orgManagerUserId); + ecompUser.setJobTitle(jobTitle); + ecompUser.setLoginId(loginId); + ecompUser.setActive(active); + + ecompUsers.add(ecompUser); + } + logger.info("found " + ecompUsers.size() + " record(s)."); + + for (EcompUser user : ecompUsers ) { + logger.info("+++++"); + String userId = user.getOrgUserId(); + List<EcompRole> roles = getRoles(userId); + Set<EcompRole> setRoles = new HashSet<EcompRole>(roles); + user.setRoles(setRoles); + } + } + catch (Exception e ) { + this.logException(e); + } + finally { + this.close(conn, st, rs ); + } + return ecompUsers; + } + + /** + * + * @param uid + * @return + */ + public List<EcompRole> getUserRole(String uid ) { + logger.info("Received request: getUserRole:" + uid); + return getRoles(uid); + } + + public int adduser(EcompUser[] userInfo) { + logger.info("Received request: adduser"); + int users = -1; + /* + PreparedStatement pst = null; + Connection conn = null; + ResultSet rs = null; + String sql = "INSERT INTO fn_user ( first_name, " + + " last_name, " + + " phone, " + + " email, " + + " hrid, " + + " org_user_id, " + + " org_code, " + + " login_id, " + + " active_yn, " + + " state_cd, " + + " country_cd ) " + + " VALUES " + + " ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?); "; + logger.info(sql); + try { + conn = apihDBSource.getConnection(); + conn.setAutoCommit(false); + pst = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS); + + for (EcompUser ui:userInfo) { + logger.info(ui.toString()); + String orgUserId = ui.getOrgUserId(); + if (orgUserId==null || orgUserId.length()==0) { + continue; + } + LdapUtil ldap= new LdapUtil(orgUserId); + if (ldap.getAll().equals("")) + continue; + logger.info(ldap.getAll()); + + String orgId=ldap.getOrgid(); + String managerId=ldap.getMngr(); + String firstName=ldap.getFirstName(); + //String middleInitial=; + String lastName=ldap.getLastName(); + String phone=ldap.getTeln(); + String email=ldap.getMail(); + String hrid=ldap.getAttuid(); + //String orgUserId=; + String orgCode=ldap.getBorg(); + String orgManagerUserId=ldap.getManagerId(); + String jobTitle=ldap.getJttl(); + String loginId=ldap.getHndl(); + String state = ldap.getStat(); + String country = ldap.getCountry(); + String active="N"; + logger.info("User info:" + ui.toString()); + + pst.setString(1,firstName); + pst.setString(2,lastName); + pst.setString(3,phone); + pst.setString(4,email); + pst.setString(5,hrid); + pst.setString(6,orgUserId); + pst.setString(7,orgCode); + pst.setString(8,loginId); + pst.setString(9,active); + pst.setString(10,state); + pst.setString(11,country); + + pst.executeUpdate(); + rs = pst.getGeneratedKeys(); + int user_id = -1; + if(rs != null && rs.next()){ + user_id = rs.getInt(1); + } + + logger.info("User ID:" + user_id); + + Set<EcompRole> roles = ui.getRoles(); + if (roles != null && !roles.isEmpty()) { + addUserRole(conn, user_id, roles); + } + conn.commit(); + users++; + } // end of for loop + } catch (Exception e) { + apihDBSource.rollback(conn); + this.logException(e); + } + finally { + this.close(conn, pst, rs ); + } + logger.info("User Added:" + (users + 1)); + */ + return users+1; + } + + private void addUserRole(Connection conn, int userId, Set<EcompRole> roles) throws Exception { + logger.info("Received request: addUserRole"); + PreparedStatement pst = null; + String sql = "INSERT INTO fn_user_role ( user_id, " + + " role_id, " + + " app_id ) " + + " VALUES " + + " ( ?, ?, ? ); "; + logger.info(sql); + List<EcompRole> roleInfo = getRoles(); + try { + pst = conn.prepareStatement(sql); + for (EcompRole er : roles ){ + for (EcompRole ei : roleInfo) { + if (er.getName().equals(ei.getName())) { + long roleId = ei.getId(); + pst.setInt(1,userId); + pst.setLong(2,roleId); + pst.setInt(3,1); + pst.executeUpdate(); + logger.info("Added role:" + ei.getName() + " for user_id " + userId); + break; + } + } + } + } catch ( Exception e) { + this.logException(e); + throw e; + } finally { + apihDBSource.close(pst); + } + } +}
\ No newline at end of file diff --git a/src/main/org/onap/ecomp/usermanagement/UserManagement.java b/src/main/org/onap/ecomp/usermanagement/UserManagement.java new file mode 100644 index 0000000..abcb753 --- /dev/null +++ b/src/main/org/onap/ecomp/usermanagement/UserManagement.java @@ -0,0 +1,364 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ecomp.usermanagement; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Map; +import java.util.Scanner; + +import org.json.JSONException; +import org.json.JSONObject; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + + +public class UserManagement { + + private static UserManagement client = null; + final static EELFLogger logger = EELFManager.getInstance().getLogger(UserManagement.class); + HttpURLConnection connection = null; + + public static UserManagement getInstance(){ + if(client == null) + return new UserManagement(); + else + return client; + } + + public JSONObject doGET(String urlString){ + + URL url; + JSONObject returnObj = null; + try { + urlString = getPostGresIP() + urlString; + url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoOutput(true); + connection.setConnectTimeout(5000); + connection.setReadTimeout(5000); + + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuilder check = new StringBuilder(); + String inputLine; + + while ((inputLine = in.readLine()) != null) + check.append(inputLine); + + // get the Response code from the HTTP + int responseCode = connection.getResponseCode(); + + + returnObj = new JSONObject(check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + + return returnObj; + + } catch (Exception e) { + logger.error("Some Exception found" + e.getLocalizedMessage()); + returnObj = new JSONObject(); + String responseMsg = ""; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + responseCode = connection.getResponseCode(); + } catch (IOException e1) { + responseMsg = "Some Exception while retreiving the response"; + responseCode = 500; + } + try { + returnObj.put("responseMsg", responseMsg); + returnObj.put("responseCode", responseCode); + + } catch (JSONException e1) { + return null; + } + return returnObj; + } + } + + public JSONObject doPATCH(String urlString, Map<String, Object> map, String methodName){ + URL url; + try { + + url = new URL(urlString); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("PATCH"); + connection.setDoOutput(true); + connection.setConnectTimeout(5000); + connection.setReadTimeout(5000); + + if(methodName.equals("patchNodeInstance")){ + connection.setRequestProperty("Content-Type", "application/json"); + OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); + out.write(new JSONObject(map).toString()); + out.close(); + + } + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuilder check = new StringBuilder(); + String inputLine; + + while ((inputLine = in.readLine()) != null) + check.append(inputLine); + + // get the Response code from the HTTP + int responseCode = connection.getResponseCode(); + + JSONObject returnObj = new JSONObject(check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + + return returnObj; + + } catch (MalformedURLException e) { + logger.error("Malformed URL found"); + return null; + } catch (IOException e) { + logger.error("IO exception while reading the StringBuilder"); + return null; + } catch (JSONException e) { + logger.error("JSON parsing error"); + return null; + } + + + } + + public JSONObject doPOST(String urlString, JSONObject outputJSON) { + URL url; + JSONObject returnObj = null; + try { + urlString = getPostGresIP() + urlString; + url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setConnectTimeout(5000); + connection.setReadTimeout(5000); + + + connection.setRequestProperty("Content-Type", "application/json"); + OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); + out.write(outputJSON.toString()); + out.close(); + + + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuilder check = new StringBuilder(); + String inputLine; + + while ((inputLine = in.readLine()) != null) + check.append(inputLine); + + // get the Response code from the HTTP + int responseCode = connection.getResponseCode(); + + + returnObj = new JSONObject(check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + + return returnObj; + + } catch (Exception e) { + logger.error("Exception found"); + returnObj = new JSONObject(); + String responseMsg = ""; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + responseCode = connection.getResponseCode(); + } catch (IOException e1) { + responseMsg = "Some Exception while retreiving the response"; + responseCode = 500; + } + try { + returnObj.put("responseMsg", responseMsg); + returnObj.put("responseCode", responseCode); + } catch (JSONException e1) { + return null; + } + return returnObj; + } + + + } + + public JSONObject doPUT(String urlString,JSONObject outputJson){ + + URL url; + JSONObject returnObj = null; + try { + urlString = getPostGresIP() + urlString; + url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("PUT"); + connection.setDoOutput(true); + connection.setConnectTimeout(5000); + connection.setReadTimeout(5000); + + + if(outputJson != null){ + connection.setRequestProperty("Content-Type", "application/json"); + OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); + out.write(outputJson.toString()); + out.close(); + } + + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuilder check = new StringBuilder(); + String inputLine; + + while ((inputLine = in.readLine()) != null) + check.append(inputLine); + + // get the Response code from the HTTP + int responseCode = connection.getResponseCode(); + + + returnObj = new JSONObject(check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + + return returnObj; + + } catch (Exception e) { + logger.error("Exception found"); + returnObj = new JSONObject(); + String responseMsg = ""; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + responseCode = connection.getResponseCode(); + } catch (IOException e1) { + responseMsg = "Some Exception while retreiving the response"; + responseCode = 500; + } + try { + returnObj.put("responseMsg", responseMsg); + returnObj.put("responseCode", responseCode); + } catch (JSONException e1) { + return null; + } + return returnObj; + } + + } + + public JSONObject doDELETE(String urlString){ + URL url; + JSONObject returnObj = null; + try { + urlString = getPostGresIP() + urlString; + url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("DELETE"); + connection.setDoOutput(true); + connection.setConnectTimeout(5000); + connection.setReadTimeout(5000); + + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + StringBuilder check = new StringBuilder(); + String inputLine; + + while ((inputLine = in.readLine()) != null) + check.append(inputLine); + + // get the Response code from the HTTP + int responseCode = connection.getResponseCode(); + + + returnObj = new JSONObject(check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + + return returnObj; + + } catch (Exception e) { + logger.error("Exception found"); + returnObj = new JSONObject(); + String responseMsg = ""; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + responseCode = connection.getResponseCode(); + } catch (IOException e1) { + responseMsg = "Some Exception while retreiving the response"; + responseCode = 500; + } + try { + returnObj.put("responseMsg", responseMsg); + returnObj.put("responseCode", responseCode); + } catch (JSONException e1) { + return null; + } + return returnObj; + } + + } + + private String getCurrentDataAndTime(){ + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + Date date = new Date(); + return dateFormat.format(date); + } + + private String getPostGresIP() { + String postgres_ip = ""; + String api_version = ""; + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("files/configuration.txt") + .getFile()); + try (Scanner scanner = new Scanner(file)) { + + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + if (line.split("=")[0].equals("postgres_ip")) + postgres_ip = line.split("=")[1]; + if (line.split("=")[0].equals("api_version")) + api_version = line.split("=")[1]; + } + scanner.close(); + } catch (IOException e) { + logger.error("Not able to find the manager ip for REST call"); + return null; + } + return "http://" + postgres_ip + "/api/" + api_version; + } + + + + }
\ No newline at end of file diff --git a/src/main/org/onap/ecomp/usermanagement/UserManagementService.java b/src/main/org/onap/ecomp/usermanagement/UserManagementService.java new file mode 100644 index 0000000..18619c0 --- /dev/null +++ b/src/main/org/onap/ecomp/usermanagement/UserManagementService.java @@ -0,0 +1,136 @@ +/******************************************************************************* + * =============LICENSE_START========================================================= + * + * ================================================================================= + * Copyright (c) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed 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. + * ============LICENSE_END========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + *******************************************************************************/ +package org.onap.ecomp.usermanagement; + +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.onap.ecomp.main.APIHConfig; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +@Path("usermanagement") +public class UserManagementService { + + final static EELFLogger logger = EELFManager.getInstance().getLogger(UserManagementService.class); + + public UserManagementService() { + } + + @GET + @Path("/roles") + @Produces(MediaType.APPLICATION_JSON) + public Response getRoles(@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid ) { + logger.info("Received request: getRoles"); + if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ + return Response.status(401).entity("Unauthorized").build(); + } + + EcompUserManagementDao ecompUserManagementDao = new EcompUserManagementDao(); + List<EcompRole> roles = ecompUserManagementDao.getRoles(); + if (roles == null) { + return Response.status(500).entity("Internal Server Error").build(); + } + + return Response.ok().entity(roles).build(); + } + @GET + @Path("/users") + @Produces(MediaType.APPLICATION_JSON) + public Response getUsers(@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + logger.info("Received request: getUsers"); + if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ + return Response.status(401).entity("Unauthorized").build(); + } + + EcompUserManagementDao ecompUserManagementDao = new EcompUserManagementDao(); + List<EcompUser> users = ecompUserManagementDao.getUsers(); + if (users == null) { + return Response.status(500).entity("Internal Server Error").build(); + } + + return Response.ok().entity(users).build(); + } + @GET + @Path("/user/{uid}") + @Produces(MediaType.APPLICATION_JSON) + public Response getUser(@PathParam("uid") String uid,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + logger.info("Received request: getUser:" + uid); + if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ + return Response.status(401).entity("Unauthorized").build(); + } + + EcompUserManagementDao ecompUserManagementDao = new EcompUserManagementDao(); + List<EcompUser> user = ecompUserManagementDao.getUser(uid); + if (user == null) { + return Response.status(500).entity("Internal Server Error").build(); + } + + return Response.ok().entity(user).build(); + } + @GET + @Path("/user/role/{uid}") + @Produces(MediaType.APPLICATION_JSON) + public Response getUserRole(@PathParam("uid") String uid,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + logger.info("Received request: getUserRole:" + uid); + if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ + return Response.status(401).entity("Unauthorized").build(); + } + + EcompUserManagementDao ecompUserManagementDao = new EcompUserManagementDao(); + List<EcompRole> roles = ecompUserManagementDao.getUserRole(uid); + if (roles == null) { + return Response.status(500).entity("Internal Server Error").build(); + } + + return Response.ok().entity(roles).build(); + } + + @POST + @Path("/users") + @Consumes(MediaType.APPLICATION_JSON) + public Response addUser(EcompUser[] userInfo,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + logger.info("Received request: addUser"); + + if(!APIHConfig.getInstance().validateUser(authString,userid,"POST")){ + return Response.status(401).entity("Unauthorized").build(); + } + + EcompUserManagementDao ecompUserManagementDao = new EcompUserManagementDao(); + int addedUserCnt = ecompUserManagementDao.adduser(userInfo); + if (addedUserCnt < 0) { + return Response.status(500).entity("Internal Server Error").build(); + } + // return HTTP response 201 in case of success + return Response.status(201).entity("User Added:" + addedUserCnt).build(); + } +} |