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 | |
parent | a30008bfaac90f9acc068dda471552fc68cb98cc (diff) |
[CCSDK-36] seedcode for northbound api
Change-Id: If48afb138dbab2fb1eed4d3591f02524489e994e
Signed-off-by: VENKATESH KUMAR <vv770d@att.com>
Diffstat (limited to 'src')
17 files changed, 3651 insertions, 0 deletions
diff --git a/src/main/org/onap/ecomp/main/APIHConfig.java b/src/main/org/onap/ecomp/main/APIHConfig.java new file mode 100644 index 0000000..a9d4801 --- /dev/null +++ b/src/main/org/onap/ecomp/main/APIHConfig.java @@ -0,0 +1,117 @@ +/******************************************************************************* + * =============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.main; + +import java.io.File; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.util.Scanner; + +import javax.xml.bind.DatatypeConverter; + +import org.json.JSONObject; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class APIHConfig { + final static EELFLogger logger = EELFManager.getInstance().getLogger(APIHConfig.class); + private static JSONObject configObject = new JSONObject(); + private static APIHConfig apihConfigObj = null; + + + public APIHConfig () throws Exception { + configObject = readConfiguration(); + } + + public static APIHConfig getInstance() { + + if (apihConfigObj == null) { + try { + apihConfigObj = new APIHConfig(); + } catch (Exception e) { + StringWriter stack = new StringWriter(); + e.printStackTrace(new PrintWriter(stack)); + logger.info(stack.toString()); + } + } + + return apihConfigObj; + } + + public JSONObject getConfigObject() { + return configObject; + } + + private JSONObject readConfiguration() throws Exception{ + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("configuration.txt").getFile()); + StringBuilder configString = new StringBuilder(); + Scanner scanner = new Scanner(file); + + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + configString.append(line); + } + + JSONObject configObject = new JSONObject(configString.toString()); + scanner.close(); + return configObject; + } + + public boolean validateUser(String authString, String userId, String function){ + + if(!configObject.optBoolean("enableAuthetication")){ + logger.info("Authentication is disabled. Continuing ..."); + return true; + } + + if(authString ==null || authString.isEmpty()){ + logger.info("Authentication data missing. Not Authorized"); + return false; + } + + String decodedAuth = ""; + String[] authParts = authString.split("\\s+"); + + String authInfo = authParts[1]; + byte[] bytes = null; + bytes = DatatypeConverter.parseBase64Binary(authInfo); + + decodedAuth = new String(bytes,StandardCharsets.UTF_8); + String[] authen = decodedAuth.split(":"); + + + // APIHUtil.getIntance().generate() use this function once the encrytion to work + if (authen.length > 1 && configObject.optBoolean("enableAuthetication") && authen[0].equals(configObject.optString("mechid")) + && authen[1].equals(configObject.optString("pass"))) { + logger.info("Application is authenticated sucessfully"); + return true; + } else { + logger.info("Application authentication Failed!!"); + return false; + } + } +} + + diff --git a/src/main/org/onap/ecomp/main/APIHUtil.java b/src/main/org/onap/ecomp/main/APIHUtil.java new file mode 100644 index 0000000..02a04ee --- /dev/null +++ b/src/main/org/onap/ecomp/main/APIHUtil.java @@ -0,0 +1,145 @@ +/******************************************************************************* + * =============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.main; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.List; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipEntry; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class APIHUtil { + + final static EELFLogger logger = EELFManager.getInstance().getLogger( + APIHUtil.class); + private static APIHUtil apihUtil = null; + private String fileNameToSearch; + private List<String> result = null; + private static MessageDigest md; + + public String getFileNameToSearch() { + return fileNameToSearch; + } + + public void setFileNameToSearch(String fileNameToSearch) { + this.fileNameToSearch = fileNameToSearch; + } + + private APIHUtil() { + + } + + public static APIHUtil getIntance() { + if (apihUtil == null) { + apihUtil = new APIHUtil(); + return apihUtil; + } else + return apihUtil; + } + + public void unzip(String zipFilePath, String destDir) + throws IOException { + File dir = new File(destDir); + + if (!dir.exists()) + dir.mkdirs(); + FileInputStream fis; + + byte[] buffer = new byte[1024]; + fis = new FileInputStream(zipFilePath); + ZipInputStream zis = new ZipInputStream(fis); + ZipEntry ze = zis.getNextEntry(); + while (ze != null) { + String fileName = ze.getName(); + File newFile = new File(destDir + File.separator + fileName); + logger.info("Unzipping to " + newFile.getAbsolutePath()); + new File(newFile.getParent()).mkdirs(); + FileOutputStream fos = new FileOutputStream(newFile); + int len; + while ((len = zis.read(buffer)) > 0) { + fos.write(buffer, 0, len); + } + fos.close(); + zis.closeEntry(); + ze = zis.getNextEntry(); + } + + zis.closeEntry(); + zis.close(); + fis.close(); + } + + public String searchBlueprint(File fileDirectory) { + + result = new ArrayList<String>(); + if (fileDirectory.isDirectory()) { + System.out.println("Searching directory ... " + fileDirectory.getAbsoluteFile()); + for (File temp : fileDirectory.listFiles()) { + if (temp.isDirectory()) { + searchBlueprint(temp); + } else { + if (fileNameToSearch.toLowerCase().equals(temp.getName().toLowerCase())) { + logger.info("Found the file " + (temp.getAbsoluteFile().toString())); + result.add(temp.getAbsoluteFile().toString()); + } + } + } + } + return result.get(0); + } + + public void deleteDirectory(String outputLocation) { + File dir = new File(outputLocation); + for (File file: dir.listFiles()) { + if (file.isDirectory()) deleteDirectory(file.getAbsolutePath()); + file.delete(); + } + + } + + public String generate(String pass) { + try { + md = MessageDigest.getInstance("MD5"); + byte[] passBytes = pass.getBytes(); + md.reset(); + byte[] digested = md.digest(passBytes); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < digested.length; i++) { + sb.append(Integer.toHexString(0xff & digested[i])); + } + return sb.toString(); + } catch (NoSuchAlgorithmException ex) { + + } + return null; + + } + +} diff --git a/src/main/org/onap/ecomp/main/ContextListener.java b/src/main/org/onap/ecomp/main/ContextListener.java new file mode 100644 index 0000000..0440b84 --- /dev/null +++ b/src/main/org/onap/ecomp/main/ContextListener.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * =============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.main; + +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + + +@WebListener("application context listener") +public class ContextListener implements ServletContextListener { + + /** + * Initialize log4j when the application is being started + */ + @Override + public void contextInitialized(ServletContextEvent event) { + // initialize log4j here + // ServletContext context = event.getServletContext(); + /*String log4jConfigFile = context.getInitParameter("log4j-config-location"); + String fullPath = context.getRealPath("") + File.separator + log4jConfigFile; + + PropertyConfigurator.configure(fullPath);*/ + // Connector.getDatabase(); + //JSONParser.getJSONParser().loadConfigurationFile(); + + // Instantiate the database connection here + + } + + @Override + public void contextDestroyed(ServletContextEvent event) { + // do nothing + } +}
\ No newline at end of file diff --git a/src/main/org/onap/ecomp/main/GeneratePasswordService.java b/src/main/org/onap/ecomp/main/GeneratePasswordService.java new file mode 100644 index 0000000..0583abf --- /dev/null +++ b/src/main/org/onap/ecomp/main/GeneratePasswordService.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * =============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.main; + +import java.util.Scanner; + +import org.onap.ecomp.main.APIHUtil; + +public class GeneratePasswordService { + + public static void main(String args[]) { + + Scanner reader = new Scanner(System.in); + System.out.println("Enter a username: "); + String username = reader.nextLine(); + System.out.println("Enter a password: "); + String password = reader.nextLine(); + + String encodedUsername = APIHUtil.getIntance().generate(username); + String encodedPassword = APIHUtil.getIntance().generate(password); + + System.out.println("Encoded Username : " + encodedUsername); + System.out.println("Encoded Password : " + encodedPassword); + reader.close(); + + } + +} diff --git a/src/main/org/onap/ecomp/main/cloudify/CloudifyClient.java b/src/main/org/onap/ecomp/main/cloudify/CloudifyClient.java new file mode 100644 index 0000000..78f4008 --- /dev/null +++ b/src/main/org/onap/ecomp/main/cloudify/CloudifyClient.java @@ -0,0 +1,343 @@ +/******************************************************************************* + * =============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.main.cloudify; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.ecomp.main.APIHConfig; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import org.apache.commons.codec.binary.Base64; + +public class CloudifyClient { + + private static CloudifyClient client = null; + final static EELFLogger logger = EELFManager.getInstance().getLogger(CloudifyClient.class); + HttpURLConnection connection = null; + + public static CloudifyClient getInstance() { + if (client == null) + return new CloudifyClient(); + else + return client; + } + + public JSONObject doGET(String urlString) { + + URL url; + JSONObject returnObj = null; + try { + urlString = getManagerID() + urlString; + url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoOutput(true); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + connection.setRequestProperty("Authorization", getAuthString()); + + 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(); + returnObj.put("responseMsg",check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + return returnObj; + + } catch (Exception e) { + logger.error("Exception found : " + e.getLocalizedMessage()); + returnObj = new JSONObject(); + String responseMsg = ""; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + JSONObject errorSteam = getErrorSteam(); + if (errorSteam != null) + responseMsg = errorSteam.optString("message"); + responseCode = connection.getResponseCode(); + returnObj.put("responseMsg", responseMsg); + returnObj.put("responseCode", responseCode); + } catch (Exception e1) { + responseMsg = "Some Exception while retreiving the response"; + responseCode = 500; + } + return returnObj; + }finally{ + connection.disconnect(); + } + } + + public JSONObject doPOST(String urlString, JSONObject outputJSON) { + URL url; + JSONObject returnObj = null; + try { + urlString = getManagerID() + urlString; + url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + connection.setRequestProperty("Authorization", getAuthString()); + + 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(); + returnObj.put("responseMsg",check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + + return returnObj; + + } catch (Exception e) { + logger.error("Exception found : " + e.getLocalizedMessage()); + returnObj = new JSONObject(); + String responseMsg = ""; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + JSONObject errorSteam = getErrorSteam(); + if (errorSteam != null) + responseMsg = errorSteam.optString("message"); + responseCode = connection.getResponseCode(); + returnObj.put("responseMsg", responseMsg); + returnObj.put("responseCode", responseCode); + } catch (Exception e1) { + responseMsg = "Some Exception while retreiving the response"; + responseCode = 500; + } + return returnObj; + } finally{ + connection.disconnect(); + } + + } + + public JSONObject doPUT(String urlString, JSONObject outputJson) { + + URL url; + JSONObject returnObj = null; + try { + urlString = getManagerID() + urlString; + url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("PUT"); + connection.setDoOutput(true); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + connection.setRequestProperty("Authorization", getAuthString()); + + if (outputJson != null) { + connection.setRequestProperty("Content-Type", + "application/json"); + OutputStreamWriter out = new OutputStreamWriter( + connection.getOutputStream()); + out.write(outputJson.toString()); + out.close(); + } + + System.out.println(connection.getResponseMessage()); + 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(); + returnObj.put("responseMsg",check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + + return returnObj; + + } catch (Exception e) { + logger.error("Exception found : " + e.getLocalizedMessage()); + returnObj = new JSONObject(); + String responseMsg = ""; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + JSONObject errorSteam = getErrorSteam(); + if (errorSteam != null) + responseMsg = errorSteam.optString("message"); + responseCode = connection.getResponseCode(); + returnObj.put("responseMsg", responseMsg); + returnObj.put("responseCode", responseCode); + } catch (Exception e1) { + responseMsg = "Some Exception while retreiving the response"; + responseCode = 500; + } + return returnObj; + }finally{ + connection.disconnect(); + } + } + + public JSONObject doDELETE(String urlString) { + URL url; + JSONObject returnObj = null; + try { + urlString = getManagerID() + urlString; + url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("DELETE"); + connection.setDoOutput(true); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + connection.setRequestProperty("Authorization", getAuthString()); + + 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(); + returnObj.put("responseMsg",check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + + return returnObj; + + } catch (Exception e) { + logger.error("Exception found : " + e.getLocalizedMessage()); + returnObj = new JSONObject(); + String responseMsg = ""; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + JSONObject errorSteam = getErrorSteam(); + if (errorSteam != null) + responseMsg = errorSteam.optString("message"); + responseCode = connection.getResponseCode(); + returnObj.put("responseMsg", responseMsg); + returnObj.put("responseCode", responseCode); + } catch (Exception e1) { + responseMsg = "Some Exception while retreiving the response"; + responseCode = 500; + } + return returnObj; + }finally{ + connection.disconnect(); + } + } + + private String getCurrentDataAndTime() { + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + Date date = new Date(); + return dateFormat.format(date); + } + + private String getManagerID() { + String manager_ip = ""; + String api_version = ""; + manager_ip = APIHConfig.getInstance().getConfigObject().optString("manager_ip"); + api_version = APIHConfig.getInstance().getConfigObject().optString("api_version"); + return "http://" + manager_ip + "/api/" + api_version; + } + + private String getManagerUsername() { + String manager_username = ""; + manager_username = APIHConfig.getInstance().getConfigObject().optString("manager_username"); + return manager_username; + } + + private String getManagerPassword() { + String manager_password = ""; + manager_password = APIHConfig.getInstance().getConfigObject().optString("manager_password"); + return manager_password; + } + + private String getAuthString(){ + String username = getManagerUsername(); + String password = getManagerPassword(); + String authString = username + ":" + password; + byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); + String authStringEnc = new String(authEncBytes); + return "Basic " + authStringEnc; + } + private JSONObject getErrorSteam() { + BufferedReader in = new BufferedReader(new InputStreamReader( + connection.getErrorStream())); + StringBuilder check = new StringBuilder(); + try { + + String inputLine; + while ((inputLine = in.readLine()) != null) + check.append(inputLine); + } catch (Exception ex) { + + } + + try { + return new JSONObject(check.toString()); + } catch (JSONException e) { + return null; + } + } + +}
\ No newline at end of file diff --git a/src/main/org/onap/ecomp/main/cloudify/CloudifyHelp.java b/src/main/org/onap/ecomp/main/cloudify/CloudifyHelp.java new file mode 100644 index 0000000..55d8207 --- /dev/null +++ b/src/main/org/onap/ecomp/main/cloudify/CloudifyHelp.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * =============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.main.cloudify; + +import java.io.IOException; +import java.util.Scanner; +import java.io.*; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class CloudifyHelp { + + final static EELFLogger logger = EELFManager.getInstance().getLogger(CloudifyHelp.class); + + public String getHelp() { + return generateHelpJSON(); + } + + private String generateHelpJSON() { + + StringBuilder result = new StringBuilder(""); + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("cloudifyhelp.txt") + .getFile()); + + try (Scanner scanner = new Scanner(file)) { + + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + result.append(line).append("\n"); + } + + scanner.close(); + + } catch (IOException e) { + logger.error("Help File not found in provided location"); + return null; + } + + return result.toString(); + + } + +} diff --git a/src/main/org/onap/ecomp/main/cloudify/CloudifyService.java b/src/main/org/onap/ecomp/main/cloudify/CloudifyService.java new file mode 100644 index 0000000..9b39345 --- /dev/null +++ b/src/main/org/onap/ecomp/main/cloudify/CloudifyService.java @@ -0,0 +1,548 @@ +/******************************************************************************* + * =============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.main.cloudify; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.InputStream; +import java.io.InputStreamReader; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.DELETE; +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.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.ResponseBuilder; +import javax.ws.rs.core.Response.Status; + +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.ecomp.main.APIHConfig; +import org.onap.ecomp.persistence.EcompBlueprintPersistence; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + + +@Path("/") +public class CloudifyService { + + EELFLogger logger = EELFManager.getInstance().getLogger(CloudifyService.class); + + CloudifyHelp cloudifyHelp; + + String errorLine = "Bad Request"; + + public CloudifyService() throws Exception { + cloudifyHelp = new CloudifyHelp(); + } + + /** + * Return the help for all the available API + * + * @param authString + * @param userid + * @return JSONObject + */ + + @GET + @Path("") + @Produces(MediaType.APPLICATION_JSON) + public Response getdefaultHelp(@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + return Response.status(200).entity(" API server is Alive!!") + .build(); + } + /** + * Return the help for all the available API + * + * @param authString + * @param userid + * @return JSONObject + */ + + @GET + @Path("/help") + @Produces(MediaType.APPLICATION_JSON) + public Response getHelp(@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + /*if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ + return Response.status(401).entity("Unauthorized").build(); + }*/ + + String result = cloudifyHelp.getHelp(); + logger.info("Handled get help API Request"); + return Response.status(200).entity(result) + .build(); + + } + + + /** + * Get the list or a specific blueprint which are already uploaded + * @param id + * @param authString + * @param userid + * @param request + * @return Response + */ + + @GET + @Path("/blueprints") + @Produces(MediaType.APPLICATION_JSON) + public Response getBlueprints(@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid,@Context HttpServletRequest request) { + + String url = ""; + //validate the user and the application for GET request + + if (request.getQueryString() == null) { + logger.info("Received request for all blueprints"); + url = "/blueprints"; + } else { + logger.info("Received request for blueprint with query parameters = " + request.getQueryString()); + url = "/blueprints?"+ request.getQueryString(); + } + + if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ + return Response.status(401).entity("Unauthorized").build(); + } + + JSONObject result = CloudifyClient.getInstance().doGET(url); + logger.info("Handled get blueprints API Request"); + return handleResponse(result); + + } + + /** + * DELETE a blueprint + * + * @param id + * @param authString + * @param userid + * @return JSONObject + */ + + @DELETE + @Path("/blueprints/{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response deleteBlueprints(@PathParam("id") String id,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + String url = ""; + logger.info("Received request for deleting blueprint with ID = " + id); + //validate the user and application for DELETE operation + if(!APIHConfig.getInstance().validateUser(authString,userid,"DELETE")){ + return Response.status(401).entity("Unauthorized").build(); + } + + url = "/blueprints/" + id; + + JSONObject result = CloudifyClient.getInstance().doDELETE(url); + int responseCode = result.optInt("responseCode"); + if(responseCode == 200 ){ + logger.info("Deleting the blueprint from Inventory"); + if(new EcompBlueprintPersistence().deleteBlueprint(id)) + logger.info("Deleted the blueprint from Inventory"); + } + logger.info("Handled delete blueprint API Request"); + return handleResponse(result); + + } + + /** + * Upload a new Blueprint + * @param id + * @param blueprintfileName + * @param zipFileURL + * @param authString + * @param userid + * @return JSONObject + */ + + @POST + @Path("/blueprints") + @Produces(MediaType.APPLICATION_JSON) + public Response uploadBlueprints(InputStream inputStream,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + String url = ""; + logger.info("Received request for uploading blueprint"); + + //validate the user and application for PUT operation + if(!APIHConfig.getInstance().validateUser(authString,userid,"PUT")){ + return Response.status(401).entity("Unauthorized").build(); + } + + BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); + StringBuilder check = new StringBuilder(); + String inputLine; + + + try { + while ((inputLine = in.readLine()) != null) + check.append(inputLine); + + JSONObject incomingJSON = new JSONObject(check.toString()); + if(incomingJSON.optString("blueprint_id","").equals("")) + return Response.status(400).entity("blueprint_id is mandatory in payload").build(); + + url = "/blueprints/" + incomingJSON.optString("blueprint_id","") + "?application_file_name=" + + incomingJSON.optString("blueprint_filename","") + "&blueprint_archive_url=" + + incomingJSON.optString("zip_url",""); + + JSONObject result = CloudifyClient.getInstance().doPUT(url,null); + logger.info("Handled uploading blueprint API Request"); + int responseCode = result.optInt("responseCode"); + if(responseCode == 201){ + logger.info("Pushing the blueprint in DB"); + new EcompBlueprintPersistence().saveBlueprint(incomingJSON.optString("blueprint_id",""),incomingJSON.optString("blueprint_filename",""),incomingJSON.optString("zip_url","")); + } + return handleResponse(result); + }catch(Exception e){ + e.printStackTrace(); + return Response.status(400).entity("Error parsing the incoming DATA").build(); + } + + } + + @GET + @Path("/viewblueprints") + public Response fetchBlueprintByID(@QueryParam("id") String id,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + // validate the user and application for PUT operation + if (!APIHConfig.getInstance().validateUser(authString, userid, "PUT")) { + return Response.status(401).entity("Unauthorized").build(); + } + + if(id == "") + return Response.status(400).entity("id parameter is must for fetching the blueprint").build(); + logger.info("Fetching the blueprint with id = " + id); + EcompBlueprintPersistence blueprintPersistence = new EcompBlueprintPersistence(); + try { + File returnFile = blueprintPersistence.fetchBlueprint(id); + if (returnFile == null) { + ResponseBuilder rbuilder = Response.status(Status.OK); + String logMessage = "No such blueprint found in the inventory."; + logger.info(logMessage); + return rbuilder + .type(MediaType.TEXT_PLAIN) + .entity("") + .build(); + } else { + ResponseBuilder rbuilder = Response.status(Status.OK); + logger.info("Blueprint found. Returing the yaml file"); + return rbuilder.type(MediaType.APPLICATION_OCTET_STREAM) + .entity(returnFile).build(); + } + } catch (Exception E) { + logger.info("Exception in handling the fetch command =" + E.getMessage()); + return Response.status(500) + .entity("Error fetching the blueprint resource").build(); + } + } + + + /** + * Get the deployment list or specific deployment + * @param id + * @param authString + * @param userid + * @return JSONObject + */ + + @GET + @Path("/deployments") + @Produces(MediaType.APPLICATION_JSON) + public Response getDeployments(@Context HttpServletRequest request,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + String url = ""; + if (request.getQueryString() == null) { + logger.info("Received request for all deployments"); + url = "/deployments"; + } else { + logger.info("Received request for deployment with query = " + request.getQueryString()); + url = "/deployments?"+request.getQueryString(); + } + + if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ + return Response.status(401).entity("Unauthorized").build(); + } + + JSONObject result = CloudifyClient.getInstance().doGET(url); + logger.info("Handled get deployment API Request"); + return handleResponse(result); + } + + /** + * DELETE a deployment + * @param id + * @param authString + * @param userid + * @return JSONObject + */ + + @DELETE + @Path("/deployments/{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response deleteDeployments(@Context HttpServletRequest request,@PathParam("id") String id,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + logger.info("Received request for deleting deployment with ID = " + id); + + if(!APIHConfig.getInstance().validateUser(authString,userid,"DELETE")){ + return Response.status(401).entity("Unauthorized").build(); + } + + String url = ""; + url = "/deployments/" + id; + if(request.getQueryString() != null) + url = "/deployments/" + id + "?" + request.getQueryString(); + + JSONObject result = CloudifyClient.getInstance().doDELETE(url); + logger.info("Handled delete deployment API Request"); + return handleResponse(result); + } + + /** + * Create a new deployment + * @param inputStream + * @param deploymentID + * @param authString + * @param userid + * @return JSONObject + */ + @POST + @Path("/deployments") + @Produces(MediaType.APPLICATION_JSON) + public Response createDeployment(InputStream inputStream,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + logger.info("Received request for creating deployment"); + + if(!APIHConfig.getInstance().validateUser(authString,userid,"PUT")){ + return Response.status(401).entity("Unauthorized").build(); + } + + String url = ""; + JSONObject inputJSon; + JSONObject outputJSON; + + BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); + StringBuilder check = new StringBuilder(); + String inputLine; + + try { + while ((inputLine = in.readLine()) != null) + check.append(inputLine); + inputJSon = new JSONObject(check.toString()); + + if(inputJSon.optString("deployment_id", "").equals("")) + return Response.status(400).entity("deployment_id is mandatory in payload").build(); + String blueprintID = inputJSon.optString("blueprint_id", ""); + JSONObject parameters = inputJSon.optJSONObject("parameters"); + + outputJSON = new JSONObject(); + outputJSON.put("blueprint_id", blueprintID); + outputJSON.put("inputs", parameters); + url = "/deployments/" + inputJSon.optString("deployment_id", ""); + JSONObject result = CloudifyClient.getInstance().doPUT(url,outputJSON); + logger.info("Handled create deployment API Request"); + return handleResponse(result); + } catch (Exception e) { + return Response.status(400).entity("Error parsing the incoming DATA").build(); + } + } + + /** + * Get the list of execution for a specific deployment + * @param deployment_id + * @param authString + * @param userid + * @return + */ + @GET + @Path("/executions") + @Produces(MediaType.APPLICATION_JSON) + public Response getExecutionForDeployment( + @Context HttpServletRequest request,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + String url = ""; + + if (request.getQueryString() == null) { + logger.info("Received request for list execution"); + url = "/executions"; + } else { + logger.info("Received request for list execution with query paramters = " + request.getQueryString()); + url = "/executions?"+request.getQueryString(); + } + + if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ + return Response.status(401).entity("Unauthorized").build(); + } + + JSONObject result = CloudifyClient.getInstance().doGET(url); + logger.info("Handled get Execution API Request"); + return handleResponse(result); + } + + @GET + @Path("/executions/{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response getExecutionWithID( + @Context HttpServletRequest request,@PathParam("id") String execution_id,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + String url = ""; + if(request.getQueryString() == null){ + logger.info("Received request for list execution for Execution id as :" + execution_id); + url = "/executions/"+ execution_id; + } + else{ + url = "/executions/"+ execution_id + "?" + request.getQueryString(); + logger.info("Received request for list execution for query paramters = " + request.getQueryString() + " and Execution id as :" + execution_id); + } + + if(!APIHConfig.getInstance().validateUser(authString,userid,"GET")){ + return Response.status(401).entity("Unauthorized").build(); + } + + JSONObject result = CloudifyClient.getInstance().doGET(url); + logger.info("Handled get specific execution API Request"); + return handleResponse(result); + } + + /** + * Start an execution + * @param inputStream + * @param authString + * @param userid + * @return + */ + + @POST + @Path("/executions") + @Produces(MediaType.APPLICATION_JSON) + public Response startExecution(InputStream inputStream,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + logger.info("Received request for starting an execution"); + if(!APIHConfig.getInstance().validateUser(authString,userid,"POST")){ + return Response.status(401).entity("Unauthorized").build(); + } + + String url = ""; + JSONObject outputJson = new JSONObject(); + + + url = "/executions"; + + BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); + StringBuilder check = new StringBuilder(); + String inputLine; + + try { + while ((inputLine = in.readLine()) != null) + check.append(inputLine); + JSONObject inputJSon = new JSONObject(check.toString()); + String deploymentID = inputJSon.optString("deployment_id",""); + String workflow = inputJSon.optString("workflow_name",""); + String customParameter = inputJSon.optString("allow_custom_parameter","false"); + String force = inputJSon.optString("force","false"); + JSONArray parameters = inputJSon.optJSONArray("parameters"); + + outputJson.put("deployment_id", deploymentID); + outputJson.put("workflow_id", workflow); + outputJson.put("allow_custom_parameters", customParameter); + outputJson.put("force", force); + outputJson.put("parameters", parameters); + + logger.info("output JSON is " + outputJson.toString()); + JSONObject result = CloudifyClient.getInstance().doPOST(url,outputJson); + logger.info("Handled start execution API Request"); + return handleResponse(result); + } catch (Exception e) { + return Response.status(400).entity("Error parsing the incoming DATA").build(); + } + + } + + /** + * + * @param execution_id + * @param inputStream + * @param authString + * @param userid + * @return + */ + + @DELETE + @Path("/executions/{execution-id}") + @Produces(MediaType.APPLICATION_JSON) + public Response cancelExecution(@PathParam("execution-id") String execution_id,@Context HttpServletRequest request,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + logger.info("Received request for cancel execution for Execution id as :" + execution_id); + + if(!APIHConfig.getInstance().validateUser(authString,userid,"POST")){ + return Response.status(401).entity("Unauthorized").build(); + } + + String url = ""; + JSONObject outputJson = new JSONObject(); + + url = "/executions/"+ execution_id; + + try { + String[] query = request.getQueryString().split("&"); + String deployment_id = query[0].split("=")[1]; + String action = "cancel"; + if(query.length>1) + action = query[1].split("=")[1]; + outputJson.put("deployment_id", deployment_id); + outputJson.put("action", action); + JSONObject result = CloudifyClient.getInstance().doPOST(url,outputJson); + logger.info("Handled cancel execution API Request"); + return handleResponse(result); + } catch (Exception e) { + return Response.status(400).entity("Error parsing the incoming DATA").build(); + } + } + + private Response handleResponse(JSONObject result) { + + if(result == null){ + return Response.status(500).entity("Internal Server Error – We had a problem with our server. Try again later.").build(); + } + int responseCode = result.optInt("responseCode"); + String responseMsg = result.optString("responseMsg", ""); + + if(responseCode >= 300) + { + logger.info("Response code is: " + responseCode + " and Error msg is :" + responseMsg); + } + + return Response.status(responseCode).entity(responseMsg).build(); + } + +} diff --git a/src/main/org/onap/ecomp/main/consul/ConsulClient.java b/src/main/org/onap/ecomp/main/consul/ConsulClient.java new file mode 100644 index 0000000..40721ed --- /dev/null +++ b/src/main/org/onap/ecomp/main/consul/ConsulClient.java @@ -0,0 +1,321 @@ +/******************************************************************************* + * =============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.main.consul; + + import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.ecomp.main.APIHConfig; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + public class ConsulClient { + + private static ConsulClient client = null; + final static EELFLogger logger = EELFManager.getInstance().getLogger(ConsulClient.class); + HttpURLConnection connection = null; + + public static ConsulClient getInstance() { + if (client == null) + return new ConsulClient(); + else + return client; + } + + public JSONObject doGET(String urlString) { + + URL url; + JSONObject returnObj = null; + try { + urlString = getManagerID() + urlString; + url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + connection.setDoOutput(true); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + + 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(); + returnObj.put("responseMsg",check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + return returnObj; + + } catch (Exception e) { + logger.error("Exception found : " + e.getLocalizedMessage()); + returnObj = new JSONObject(); + String responseMsg = ""; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + JSONObject errorSteam = getErrorSteam(); + if (errorSteam != null) + responseMsg = errorSteam.optString("message"); + responseCode = connection.getResponseCode(); + returnObj.put("responseMsg", responseMsg); + returnObj.put("responseCode", responseCode); + } catch (Exception e1) { + responseMsg = "Some Exception while retreiving the response"; + responseCode = 500; + } + return returnObj; + }finally{ + connection.disconnect(); + } + } + + public JSONObject doPOST(String urlString, JSONObject outputJSON) { + URL url; + JSONObject returnObj = null; + try { + urlString = getManagerID() + urlString; + url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + + 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(); + returnObj.put("responseMsg",check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + + return returnObj; + + } catch (Exception e) { + logger.error("Exception found : " + e.getLocalizedMessage()); + returnObj = new JSONObject(); + String responseMsg = ""; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + JSONObject errorSteam = getErrorSteam(); + if (errorSteam != null) + responseMsg = errorSteam.optString("message"); + responseCode = connection.getResponseCode(); + returnObj.put("responseMsg", responseMsg); + returnObj.put("responseCode", responseCode); + } catch (Exception e1) { + responseMsg = "Some Exception while retreiving the response"; + responseCode = 500; + } + return returnObj; + } finally{ + connection.disconnect(); + } + + } + + public JSONObject doPUT(String urlString, JSONObject outputJson) { + + URL url; + JSONObject returnObj = null; + try { + urlString = getManagerID() + urlString; + url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("PUT"); + connection.setDoOutput(true); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + + if (outputJson != null) { + connection.setRequestProperty("Content-Type", + "application/json"); + OutputStreamWriter out = new OutputStreamWriter( + connection.getOutputStream()); + out.write(outputJson.toString()); + out.close(); + } + + System.out.println(connection.getResponseMessage()); + 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(); + returnObj.put("responseMsg",check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + + return returnObj; + + } catch (Exception e) { + logger.error("Exception found : " + e.getLocalizedMessage()); + returnObj = new JSONObject(); + String responseMsg = ""; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + JSONObject errorSteam = getErrorSteam(); + if (errorSteam != null) + responseMsg = errorSteam.optString("message"); + responseCode = connection.getResponseCode(); + returnObj.put("responseMsg", responseMsg); + returnObj.put("responseCode", responseCode); + } catch (Exception e1) { + responseMsg = "Some Exception while retreiving the response"; + responseCode = 500; + } + return returnObj; + }finally{ + connection.disconnect(); + } + } + + public JSONObject doDELETE(String urlString) { + URL url; + JSONObject returnObj = null; + try { + urlString = getManagerID() + urlString; + url = new URL(urlString); + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("DELETE"); + connection.setDoOutput(true); + connection.setConnectTimeout(10000); + connection.setReadTimeout(10000); + + 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(); + returnObj.put("responseMsg",check.toString()); + returnObj.put("responseCode", responseCode); + returnObj.put("timestamp", getCurrentDataAndTime()); + + return returnObj; + + } catch (Exception e) { + logger.error("Exception found : " + e.getLocalizedMessage()); + returnObj = new JSONObject(); + String responseMsg = ""; + int responseCode; + try { + responseMsg = connection.getResponseMessage(); + JSONObject errorSteam = getErrorSteam(); + if (errorSteam != null) + responseMsg = errorSteam.optString("message"); + responseCode = connection.getResponseCode(); + returnObj.put("responseMsg", responseMsg); + returnObj.put("responseCode", responseCode); + } catch (Exception e1) { + responseMsg = "Some Exception while retreiving the response"; + responseCode = 500; + } + return returnObj; + }finally{ + connection.disconnect(); + } + } + + private String getCurrentDataAndTime() { + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + Date date = new Date(); + return dateFormat.format(date); + } + + private String getManagerID() { + String consul_ip = ""; + String api_version = ""; + String consul_port = "8500"; + + consul_ip = APIHConfig.getInstance().getConfigObject().optString("consul_ip"); + api_version = APIHConfig.getInstance().getConfigObject().optString("consul_api_version"); + consul_port = APIHConfig.getInstance().getConfigObject().optString("consul_port"); + + return "http://" + consul_ip + ":" + consul_port+ "/"+ api_version; + } + + private JSONObject getErrorSteam() { + BufferedReader in = new BufferedReader(new InputStreamReader( + connection.getErrorStream())); + StringBuilder check = new StringBuilder(); + try { + + String inputLine; + while ((inputLine = in.readLine()) != null) + check.append(inputLine); + } catch (Exception ex) { + + } + + try { + return new JSONObject(check.toString()); + } catch (JSONException e) { + return null; + } + } + + }
\ No newline at end of file diff --git a/src/main/org/onap/ecomp/main/consul/ConsulHelp.java b/src/main/org/onap/ecomp/main/consul/ConsulHelp.java new file mode 100644 index 0000000..96abda4 --- /dev/null +++ b/src/main/org/onap/ecomp/main/consul/ConsulHelp.java @@ -0,0 +1,64 @@ +/******************************************************************************* + * =============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.main.consul; + +import java.io.IOException; +import java.util.Scanner; +import java.io.*; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class ConsulHelp { + + final static EELFLogger logger = EELFManager.getInstance().getLogger(ConsulHelp.class); + + public String getHelp() { + return generateHelpJSON(); + } + + private String generateHelpJSON() { + + StringBuilder result = new StringBuilder(""); + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource("consulhelp.txt") + .getFile()); + + try (Scanner scanner = new Scanner(file)) { + + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + result.append(line).append("\n"); + } + + scanner.close(); + + } catch (IOException e) { + logger.error("Help File not found in provided location"); + return null; + } + + return result.toString(); + + } + +} diff --git a/src/main/org/onap/ecomp/main/consul/ConsulService.java b/src/main/org/onap/ecomp/main/consul/ConsulService.java new file mode 100644 index 0000000..6954670 --- /dev/null +++ b/src/main/org/onap/ecomp/main/consul/ConsulService.java @@ -0,0 +1,465 @@ +/******************************************************************************* + * =============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.main.consul; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.Statement; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import javax.servlet.http.HttpServletRequest; +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.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.ecomp.main.APIHConfig; +import org.onap.ecomp.persistence.APIHDBSource; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + + +@Path("/healthservices") +public class ConsulService { + + final static EELFLogger logger = EELFManager.getInstance().getLogger(ConsulService.class); + + ConsulHelp consulHelp; + + String errorLine = "Bad Request"; + + public ConsulService() { + consulHelp = new ConsulHelp(); + + } + + /** + * Return the help for all the available API + * + * @param id + * @param authString + * @param userid + * @return JSONObject + */ + @GET + @Path("/help") + @Produces(MediaType.APPLICATION_JSON) + public Response getHelp(@QueryParam("id") String id,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + + logger.info("Received get help API Request"); + String result = consulHelp.getHelp(); + logger.info("Handled get help API Request"); + return Response.status(200).entity(result) + .build(); + } + + + @GET + @Path("/services/{service_name}") + @Produces(MediaType.APPLICATION_JSON) + public Response getServiceHealth(@Context HttpServletRequest request,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid,@PathParam("service_name") String service_name) { + + String url = ""; + logger.info("Health request for service with service name = " + + service_name); + + // validate the user and the application for GET request + if (!APIHConfig.getInstance().validateUser(authString, userid, "GET")) { + return Response.status(401).entity("Unauthorized").build(); + } + + url = "/health/checks/" + service_name; + if (request.getQueryString() != null) + url = "/health/checks/" + service_name + "?" + + request.getQueryString(); + + JSONObject result = ConsulClient.getInstance().doGET(url); + logger.info("Handled Health service name API Request"); + return handleResponse(result); + + } + + @GET + @Path("/nodes/{node_name}") + @Produces(MediaType.APPLICATION_JSON) + public Response getNodeHealth(@Context HttpServletRequest request,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid,@PathParam("node_name") String node_name) { + + String url = ""; + logger.info("Health request for node with node name = " + node_name); + + // validate the user and the application for GET request + if (!APIHConfig.getInstance().validateUser(authString, userid, "GET")) { + return Response.status(401).entity("Unauthorized").build(); + } + + url = "/health/node/" + node_name; + if (request.getQueryString() != null) + url = "/health/node/" + node_name + "?" + request.getQueryString(); + + JSONObject result = ConsulClient.getInstance().doGET(url); + logger.info("Handled Health node name API Request"); + return handleResponse(result); + + } + + @GET + @Path("/nodes") + @Produces(MediaType.APPLICATION_JSON) + public Response getNodes(@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid,@Context HttpServletRequest request) { + + String url = ""; + logger.info("Health request for all the nodes"); + // validate the user and the application for GET request + + if (!APIHConfig.getInstance().validateUser(authString, userid, "GET")) { + return Response.status(401).entity("Unauthorized").build(); + } + + url = "/catalog/nodes"; + if (request.getQueryString() != null) + url = "/catalog/nodes?" + request.getQueryString(); + + JSONObject result = ConsulClient.getInstance().doGET(url); + logger.info("Handled Health for all node API Request"); + return handleResponse(result); + + } + + @GET + @Path("/services") + @Produces(MediaType.APPLICATION_JSON) + public Response getServices(@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid,@Context HttpServletRequest request) { + + String url = ""; + logger.info("Health request for all the services"); + // validate the user and the application for GET request + + if (!APIHConfig.getInstance().validateUser(authString, userid, "GET")) { + return Response.status(401).entity("Unauthorized").build(); + } + + url = "/catalog/services"; + if (request.getQueryString() != null) + url = "/catalog/services?" + request.getQueryString(); + + JSONObject result = ConsulClient.getInstance().doGET(url); + logger.info("Handled Health for all services API Request"); + return handleResponse(result); + + } + + @GET + @Path("/datacenters") + @Produces(MediaType.APPLICATION_JSON) + public Response getDatacenters(@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + String url = ""; + logger.info("Health request for datacenters"); + // validate the user and the application for GET request + + if (!APIHConfig.getInstance().validateUser(authString, userid, "GET")) { + return Response.status(401).entity("Unauthorized").build(); + } + + url = "/catalog/datacenters"; + + JSONObject result = ConsulClient.getInstance().doGET(url); + logger.info("Handled Health for datacenters API Request"); + return handleResponse(result); + + } + + @GET + @Path("/svchist/{id}") + @Produces(MediaType.APPLICATION_JSON) + public Response getHistoricalData(@PathParam("id") String id,@Context HttpServletRequest request,@HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + if(!APIHConfig.getInstance().validateUser(authString,userid,"PUT")){ + return Response.status(401).entity("Unauthorized").build(); + } + + String utc_startDate = ""; + String utc_endDate = ""; + JSONArray resultArray = new JSONArray(); + logger.info("Historical data request received for id " + id); + + if (request.getQueryString() == null) + return Response.status(400).entity("start date and end date is mandatory").build(); + + String[] dates = request.getQueryString().split("&"); + String start_date = ""; + String end_date = ""; + if(dates[0].split("=").length ==2 && dates[0].split("=")[0].equals("start") && !dates[0].split("=")[1].isEmpty()){ + start_date = dates[0].split("=")[1]; + if (dates[1].split("=").length ==2 && dates[1].split("=")[0].equals("end") && !dates[1].split("=")[1].isEmpty()) + end_date = dates[1].split("=")[1]; + else + return Response.status(400).entity("start or end tag/value not found").build(); + } + else + return Response.status(400).entity("start or end tag/value not found").build(); + + try { + + logger.info("Health Request received for start date :" + start_date + " and end date as : " + end_date); + + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ"); + Calendar s = javax.xml.bind.DatatypeConverter.parseDateTime(start_date); + Calendar e = javax.xml.bind.DatatypeConverter.parseDateTime(end_date); + Date sDate = s.getTime(); + Date eDate = e.getTime(); + + + formatter.setTimeZone(TimeZone.getTimeZone("UTC")); + utc_startDate = formatter.format(sDate); + utc_endDate = formatter.format(eDate); + logger.info("Fetching the health date for start date :" + utc_startDate + " and end date as : " + utc_endDate); + Connection conn = APIHDBSource.getInstance().getConnection(); + Statement cs = conn.createStatement(); + /** + String sql = "select date,status,output from healthcheck where id='" + + id + + "' and date between '" + + utc_startDate + + "' and '" + + utc_endDate + "'"; + */ + String sql = "select date,status,output from healthcheck h, service s where s.id = h.id " + + " and s.name ='" + + id + + "' and date between '" + + utc_startDate + + "' and '" + + utc_endDate + "'"; + logger.info("Sending query : " + sql); + ResultSet rs = cs.executeQuery(sql); + if (!rs.isBeforeFirst()) { + return Response + .status(200) + //.entity("No health Data found for the selected dates or service") + .entity(resultArray.toString()) + .build(); + } else { + while (rs.next()) { + JSONObject tmp = new JSONObject(); + String returnDate = rs.getString(1).substring(0,19)+ "+0000"; + // System.out.println("DB return " + returnDate); + formatter.setTimeZone(TimeZone.getTimeZone(s.getTimeZone().getID())); + Date ret = formatter.parse(returnDate); + //System.out.println("After parsing " + ret); + //System.out.println("After formatting " + formatter.format(ret)); + + tmp.put("Date", formatter.format(ret)); + tmp.put("Status", rs.getString(2)); + tmp.put("Output", rs.getString(3)); + resultArray.put(tmp); + } + logger.info("Handled historical health date request sucessfully with total records: " + resultArray.length()); + return Response.status(200).entity(resultArray.toString()) + .build(); + } + } catch (ParseException e) { + e.printStackTrace(); + return Response.status(400) + .entity("start_date or end_date is not parsable. Please check documentation for correct format") + .build(); + } catch (Exception e) { + e.printStackTrace(); + return Response.status(500) + .entity("Error fetching the health historical data") + .build(); + } + } + + @POST + @Path("/register") + @Produces(MediaType.APPLICATION_JSON) + public Response registerService(InputStream inputStream, @HeaderParam("authorization") String authString,@HeaderParam("userid") String userid) { + + logger.info("Register request for a service"); + + JSONArray services = new JSONArray(); + JSONObject outputJson = new JSONObject(); + + //validate the user and the application for POST request + + if(!APIHConfig.getInstance().validateUser(authString,userid,"PUT")){ + return Response.status(401).entity("Unauthorized").build(); + } + + BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); + StringBuilder check = new StringBuilder(); + String inputLine; + try { + while ((inputLine = reader.readLine()) != null) + check.append(inputLine); + + JSONObject incoming = new JSONObject(check.toString()); + services = incoming.optJSONArray("services"); + if(services == null) + return Response.status(400).entity("services[] tag is mandatory").build(); + + int service_length = services.length(); + if(service_length == 1){ + outputJson = createServiceObject(services.getJSONObject(0)); + } + else if(service_length > 1){ + for(int i = 0; i< service_length; i++){ + outputJson = createServiceObject(services.getJSONObject(i)); + } + } + else{ + return Response.status(400).entity("no service is defined inside the services tag").build(); + } + + logger.info("Handled service register Request"); + return handleResponse(outputJson); + + } catch (Exception e) { + logger.error("some exception" + e.getMessage()); + return Response.status(400).entity("Error parsing the incoming DATA").build(); + } + + + + } + + + private JSONObject createServiceObject(JSONObject serviceObject) throws JSONException { + + String url = "/agent/service/register"; + JSONObject checkObject = new JSONObject(); + JSONArray checks = new JSONArray(); + JSONArray tags = new JSONArray(); + JSONObject outputJson = new JSONObject(); + + checks = serviceObject.optJSONArray("checks"); + tags = serviceObject.optJSONArray("tags"); + String service_name = serviceObject.optString("name",""); + String service_port = serviceObject.optString("port",""); + String service_address = serviceObject.optString("address",""); + + if(checks == null || service_port.isEmpty() || service_address.isEmpty() || service_name.isEmpty()) + return new JSONObject("{\"responseCode\":\"400\",\"responseMsg\":\"Required fields : [checks[], port, address, name]\"}"); + + outputJson.put("Name",service_name); + outputJson.put("ID",service_name); + outputJson.put("Port",Integer.parseInt(service_port)); + outputJson.put("Address",service_address); + outputJson.put("Tags", tags); + + if(checks.length() == 1){ + if(checks.getJSONObject(0).optString("endpoint", "").isEmpty() || checks.getJSONObject(0).optString("interval", "").isEmpty()) + return new JSONObject("{\"responseCode\":\"400\",\"responseMsg\":\"Required fields : [endpoint, interval] in checks\"}"); + + checkObject.put("HTTP", checks.getJSONObject(0).optString("endpoint", "")); + checkObject.put("Interval", checks.getJSONObject(0).optString("interval", "")); + if(!checks.getJSONObject(0).optString("description", "").isEmpty()) + checkObject.put("Notes", checks.getJSONObject(0).optString("description", "")); + checkObject.put("ServiceID", service_name); + + outputJson.put("Check", checkObject); + } + else{ + JSONArray checks_new = new JSONArray(); + for (int i = 0; i < checks.length(); i++) { + JSONObject o = checks.getJSONObject(i); + checkObject = new JSONObject(); + if(o.optString("endpoint", "").isEmpty() || o.optString("interval", "").isEmpty()) + return new JSONObject("{\"responseCode\":\"400\",\"responseMsg\":\"Required fields : [endpoint, interval] in checks\"}"); + + checkObject.put("HTTP", o.optString("endpoint", "")); + checkObject.put("Interval", o.optString("interval", "")); + if(!o.optString("description", "").isEmpty()) + checkObject.put("Notes", o.optString("description", "")); + checkObject.put("ServiceID", service_name); + checks_new.put(checkObject); + } + outputJson.put("Checks", checks_new); + } + + JSONObject result = ConsulClient.getInstance().doPUT(url, outputJson); + return result; + + } + + /** + * De register the service from consul + * @param inputStream + * @param authString + * @param userid + * @return + */ + @POST + @Path("/deregister/{serviceID}") + @Produces(MediaType.APPLICATION_JSON) + public Response deregisterService(@PathParam("serviceID") String serviceId, + @HeaderParam("authorization") String authString, + @HeaderParam("userid") String userid) { + + String url = ""; + logger.info("Deregister request for a service"); + // validate the user and the application for POST request + + if (!APIHConfig.getInstance().validateUser(authString, userid, "POST")) { + return Response.status(401).entity("Unauthorized").build(); + } + + url = "/agent/service/deregister/" + serviceId; + JSONObject result = ConsulClient.getInstance().doPUT(url, null); + logger.info("Handled service de register Request"); + return handleResponse(result); + + } + + private Response handleResponse(JSONObject result) { + + if(result == null){ + return Response.status(500).entity("Internal Server Error – We had a problem with our server. Try again later.").build(); + } + int responseCode = result.optInt("responseCode"); + String responseMsg = result.optString("responseMsg", ""); + if(responseCode >= 300) + { + logger.info("Response code is: " + responseCode + " and Error msg is :" + responseMsg); + } + return Response.status(responseCode).entity(responseMsg).build(); + } +} diff --git a/src/main/org/onap/ecomp/persistence/APIHDBSource.java b/src/main/org/onap/ecomp/persistence/APIHDBSource.java new file mode 100644 index 0000000..7fd57e2 --- /dev/null +++ b/src/main/org/onap/ecomp/persistence/APIHDBSource.java @@ -0,0 +1,122 @@ +/******************************************************************************* + * =============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.persistence; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import org.json.JSONObject; +import org.onap.ecomp.main.APIHConfig; +import org.postgresql.ds.PGPoolingDataSource; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class APIHDBSource { + final static EELFLogger logger = EELFManager.getInstance().getLogger(APIHDBSource.class); + private static final String PG_DRIVER = "org.postgresql.Driver"; + private static JSONObject configObject = new JSONObject(); + private static PGPoolingDataSource dbsource = null; + private static APIHDBSource apihDBSource = null; + + public APIHDBSource() { + try { + Class.forName(PG_DRIVER); + configObject = APIHConfig.getInstance().getConfigObject(); + + dbsource = new PGPoolingDataSource(); + dbsource.setDataSourceName("postgresql"); + dbsource.setServerName(configObject.optString("postgres_ip")); + dbsource.setPortNumber(configObject.optInt("postgres_port")); + dbsource.setDatabaseName(configObject.optString("postgres_db_name")); + dbsource.setUser(configObject.optString("postgres_db_user")); + dbsource.setPassword(configObject.optString("postgres_db_passwd")); + dbsource.setMaxConnections(configObject.optInt("postgres_db_max_conn")); + } catch (Exception e) { + logException(e); + } + } + + private void logException(Exception e) { + StringWriter stack = new StringWriter(); + e.printStackTrace(new PrintWriter(stack)); + logger.info(stack.toString()); + } + + public static APIHDBSource getInstance(){ + if(apihDBSource == null) + apihDBSource= new APIHDBSource(); + + return apihDBSource; + } + + public Connection getConnection() throws Exception { + return dbsource.getConnection(); + } + + public void close(Connection con) { + if (con != null) { + try { + con.close(); + } + catch (SQLException e) { + logException(e); + } + } + } + + public void close(Statement st) { + if (st != null) { + try { + st.close(); + } + catch (SQLException e) { + logException(e); + } + } + } + + public void close(ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } + catch (SQLException e) { + logException(e); + } + } + } + + public void rollback(Connection con) { + if (con != null) { + try { + con.rollback(); + } catch (SQLException e) { + logException(e); + } + } + } +}
\ No newline at end of file diff --git a/src/main/org/onap/ecomp/persistence/EcompBlueprintPersistence.java b/src/main/org/onap/ecomp/persistence/EcompBlueprintPersistence.java new file mode 100644 index 0000000..2397519 --- /dev/null +++ b/src/main/org/onap/ecomp/persistence/EcompBlueprintPersistence.java @@ -0,0 +1,171 @@ +/******************************************************************************* + * =============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.persistence; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Statement; + +import org.onap.ecomp.main.APIHUtil; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +public class EcompBlueprintPersistence { + final static EELFLogger logger = EELFManager.getInstance().getLogger( + EcompBlueprintPersistence.class); + private APIHDBSource apihDBSource = null; + + public EcompBlueprintPersistence() { + apihDBSource = APIHDBSource.getInstance(); + } + + public void saveBlueprint(String id, String fileName,String blueprintURL) { + + String outputLocation = "/home/attcloud/apilayer/tmp"; + String zipLocation = "/home/attcloud/apilayer/tmp/" + id + ".zip"; + + try{ + + APIHUtil.getIntance().deleteDirectory(outputLocation); + logger.info("Starting to download the zip file from the URL :" + blueprintURL); + + URL url = new URL(blueprintURL); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + InputStream in = connection.getInputStream(); + FileOutputStream out = new FileOutputStream(zipLocation); + copy(in, out, 1024); + out.close(); + + logger.info("Downloaded the zip file and saved at :" + zipLocation); + logger.info("Extracting the zip file"); + APIHUtil.getIntance().unzip(zipLocation, outputLocation + "/" + id); + + EcompBlueprintPersistence blueprintPersistence = new EcompBlueprintPersistence(); + APIHUtil.getIntance().setFileNameToSearch(fileName); + blueprintPersistence.addBlueprint( id,fileName,APIHUtil.getIntance().searchBlueprint(new File(outputLocation))); + APIHUtil.getIntance().deleteDirectory(outputLocation); + logger.info("Clean up done !!!"); + }catch(Exception e){ + logger.error("Some exception while saving the blueprint in Inventory " + e.getMessage()); + APIHUtil.getIntance().deleteDirectory(outputLocation); + } + + + } + + public static void copy(InputStream input, OutputStream output, + int bufferSize) throws IOException { + byte[] buf = new byte[bufferSize]; + int n = input.read(buf); + while (n >= 0) { + output.write(buf, 0, n); + n = input.read(buf); + } + output.flush(); + } + + public boolean addBlueprint(String blueprintID, final String blueprintName, + String blueprintLocation) throws Exception { + + logger.info("Blueprint location is " + blueprintLocation); + logger.info("Blueprint id is " + blueprintID); + logger.info("Blueprint name is " + blueprintName); + Connection conn = apihDBSource.getConnection(); + + System.out.println(conn.isValid(10)); + if(!conn.isValid(10)) + throw new Exception("Connection is not established"); + + File f = new File(blueprintLocation); + FileInputStream fis = new FileInputStream(f); + PreparedStatement ps = conn + .prepareStatement("INSERT INTO blueprints VALUES (?, ?, ?)"); + ps.setString(1, blueprintID); + ps.setString(2, blueprintName); + ps.setBinaryStream(3, fis, f.length()); + ps.executeUpdate(); + ps.close(); + fis.close(); + logger.info("Saved blueprint in Inventory"); + return true; + } + + public File fetchBlueprint(String id) throws Exception { + + File file = null; + Connection conn = apihDBSource.getConnection(); + String blueprintName = ""; + Statement cs = conn.createStatement(); + String sql = "SELECT name,blueprint from blueprints where id='" + id + "'"; + ResultSet rs = cs.executeQuery(sql); + if (!rs.isBeforeFirst()) { + return null; + } else { + + byte[] imgBytes = null; + while (rs.next()) { + blueprintName = rs.getString(1); + imgBytes = rs.getBytes(2); + } + file = new File( + "/home/attcloud/apilayer/tmp/"+ blueprintName); + if(file.exists()) + file.delete(); + FileOutputStream fos = new FileOutputStream(file); + fos.write(imgBytes); + fos.flush(); + fos.close(); + } + + rs.close(); + + return file; + + } + + public boolean deleteBlueprint(String id) { + + try{ + Connection conn = apihDBSource.getConnection(); + Statement cs = conn.createStatement(); + String sql = "DELETE from blueprints where id='" + id + "'"; + cs.execute(sql); + return true; + }catch(Exception E){ + E.printStackTrace(); + logger.info("Exception while deleting the blueprint from inventory " + id + ":" + E.getMessage()); + return false; + } + + } +} 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(); + } +} |