summaryrefslogtreecommitdiffstats
path: root/mdsal-resource/provider/src/main/java
diff options
context:
space:
mode:
authorJessica Wagantall <jwagantall@linuxfoundation.org>2020-12-01 11:26:31 -0800
committerJessica Wagantall <jwagantall@linuxfoundation.org>2020-12-01 11:27:11 -0800
commit11510b43c277b8e1dd7e58d79785544810118c8e (patch)
treeb88a497c999d24b5f357ea9b26bc93e0990fd5e7 /mdsal-resource/provider/src/main/java
parent5d2eab72fc4442f14108b41800cec88126913823 (diff)
Migrate sli-adaptor files
Migrate sli-adaptor repo files into a new "adaptors" directory. Signed-off-by: Jessica Wagantall <jwagantall@linuxfoundation.org>
Diffstat (limited to 'mdsal-resource/provider/src/main/java')
-rw-r--r--mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/ConfigResource.java153
-rwxr-xr-xmdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/MdsalResourcePropertiesProvider.java28
-rwxr-xr-xmdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/MdsalResourcePropertiesProviderImpl.java186
-rw-r--r--mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/OperationalResource.java147
-rw-r--r--mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/RestService.java184
5 files changed, 0 insertions, 698 deletions
diff --git a/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/ConfigResource.java b/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/ConfigResource.java
deleted file mode 100644
index e2e9bc230..000000000
--- a/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/ConfigResource.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * openECOMP : SDN-C
- * ================================================================================
- * 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=========================================================
- */
-
-package org.onap.ccsdk.sli.adaptors.resource.mdsal;
-
-import java.util.Map;
-import java.util.Properties;
-
-import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
-import org.onap.ccsdk.sli.core.sli.SvcLogicException;
-import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
-import org.onap.ccsdk.sli.core.sli.SvcLogicResource.QueryStatus;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-
-public class ConfigResource implements SvcLogicResource {
-
- private static final Logger LOG = LoggerFactory.getLogger(ConfigResource.class);
-
- private RestService restService;
-
- public ConfigResource(MdsalResourcePropertiesProvider propProvider) {
- LOG.info("Loading ConfigResource using property provider");
- Properties props = propProvider.getProperties();
-
- String sdncUser = props.getProperty("org.onap.ccsdk.sli.adaptors.resource.mdsal.sdnc-user", "admin");
- String sdncPasswd = props.getProperty("org.onap.ccsdk.sli.adaptors.resource.mdsal.sdnc-passwd", "admin");
- String sdncHost = props.getProperty("org.onap.ccsdk.sli.adaptors.resource.mdsal.sdnc-host", "localhost");
- String sdncProtocol = props.getProperty("org.onap.ccsdk.sli.adaptors.resource.mdsal.sdnc-protocol", "https");
- String sdncPort = props.getProperty("org.onap.ccsdk.sli.adaptors.resource.mdsal.sdnc-port", "8443");
-
- restService = new RestService(sdncProtocol, sdncHost, sdncPort, sdncUser, sdncPasswd, "XML", "XML");
- }
-
- public ConfigResource(String sdncProtocol, String sdncHost, String sdncPort, String sdncUser, String sdncPasswd)
- {
- restService = new RestService(sdncProtocol, sdncHost, sdncPort, sdncUser, sdncPasswd, "XML", "XML");
- }
-
- public ConfigResource(RestService restService) {
- this.restService = restService;
- }
-
- @Override
- public QueryStatus isAvailable(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException
- {
- return(query(resource, false, null, key, prefix, null, null));
- }
-
- @Override
- public QueryStatus exists(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException
- {
- return(query(resource, false, null, key, prefix, null, null));
- }
-
- @Override
- public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix,
- String orderBy, SvcLogicContext ctx) throws SvcLogicException {
- String module = resource;
- StringBuffer restQuery = new StringBuffer();
-
- String[] keyParts = key.split("/");
- for (String keyPart : keyParts) {
- if (restQuery.length() > 0) {
- restQuery.append("/");
- }
- if (keyPart.startsWith("$")) {
- restQuery.append(ctx.resolve(keyPart.substring(1)));
- } else {
- restQuery.append(keyPart);
- }
- }
-
- String restQueryStr = restQuery.toString();
- if ((restQueryStr.startsWith("'") && restQueryStr.endsWith("'")) ||
- (restQueryStr.startsWith("\"") && restQueryStr.endsWith("\""))) {
- restQueryStr = restQueryStr.substring(1, restQueryStr.length()-1);
- }
-
- String urlString = "restconf/config/" + module + ":" + restQueryStr;
- LOG.info("Querying resource: " + resource + ". At URL: " + urlString);
-
- Document results = restService.get(urlString);
- if (results == null) {
- return(QueryStatus.NOT_FOUND);
- } else {
- if (ctx != null) {
- ctx.mergeDocument(prefix, results);
- }
- return(QueryStatus.SUCCESS);
- }
- }
-
- @Override
- public QueryStatus reserve(String resource, String select, String key, String prefix,
- SvcLogicContext ctx) throws SvcLogicException {
- return(QueryStatus.SUCCESS);
-
- }
-
- @Override
- public QueryStatus release(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
- return(QueryStatus.SUCCESS);
- }
-
- @Override
- public QueryStatus delete(String arg0, String arg1, SvcLogicContext arg2)
- throws SvcLogicException {
- // TODO Auto-generated method stub
- return(QueryStatus.SUCCESS);
- }
-
- @Override
- public QueryStatus save(String arg0, boolean arg1, boolean localOnly, String arg2,
- Map<String, String> arg3, String arg4, SvcLogicContext arg5)
- throws SvcLogicException {
- // TODO Auto-generated method stub
- return(QueryStatus.SUCCESS);
- }
-
- @Override
- public QueryStatus notify(String resource, String action, String key,
- SvcLogicContext ctx) throws SvcLogicException {
- return(QueryStatus.SUCCESS);
- }
-
-
- public QueryStatus update(String resource, String key,
- Map<String, String> parms, String prefix, SvcLogicContext ctx)
- throws SvcLogicException {
- return(QueryStatus.SUCCESS);
- }
-
-}
diff --git a/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/MdsalResourcePropertiesProvider.java b/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/MdsalResourcePropertiesProvider.java
deleted file mode 100755
index e433a4c13..000000000
--- a/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/MdsalResourcePropertiesProvider.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * onap
- * ================================================================================
- * Copyright (C) 2016 - 2017 ONAP
- * ================================================================================
- * 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=========================================================
- */
-
-package org.onap.ccsdk.sli.adaptors.resource.mdsal;
-
-import java.util.Properties;
-
-public interface MdsalResourcePropertiesProvider {
-
- public Properties getProperties();
-}
diff --git a/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/MdsalResourcePropertiesProviderImpl.java b/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/MdsalResourcePropertiesProviderImpl.java
deleted file mode 100755
index e9e006f17..000000000
--- a/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/MdsalResourcePropertiesProviderImpl.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * onap
- * ================================================================================
- * Copyright (C) 2016 - 2017 ONAP
- * ================================================================================
- * 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=========================================================
- */
-
-package org.onap.ccsdk.sli.adaptors.resource.mdsal;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Optional;
-import java.util.Properties;
-import java.util.Vector;
-
-import org.onap.ccsdk.sli.core.sli.ConfigurationException;
-import org.onap.ccsdk.sli.core.utils.JREFileResolver;
-import org.onap.ccsdk.sli.core.utils.KarafRootFileResolver;
-import org.onap.ccsdk.sli.core.utils.PropertiesFileResolver;
-import org.onap.ccsdk.sli.core.utils.common.CoreDefaultFileResolver;
-import org.onap.ccsdk.sli.core.utils.common.SdncConfigEnvVarFileResolver;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Responsible for determining the properties file to use and instantiating the
- * <code>SqlResource</code> Service. The priority for properties file
- * resolution is as follows:
- *
- * <ol>
- * <li>A directory identified by the system environment variable
- * <code>SDNC_CONFIG_DIR</code></li>
- * <li>The default directory <code>DEFAULT_DBLIB_PROP_DIR</code></li>
- * <li>A directory identified by the JRE argument
- * <code>sql-resource.properties</code></li>
- * <li>A <code>sql-resource.properties</code> file located in the karaf root
- * directory</li>
- * </ol>
- */
-public class MdsalResourcePropertiesProviderImpl implements MdsalResourcePropertiesProvider {
-
- private static final Logger LOG = LoggerFactory.getLogger(MdsalResourcePropertiesProviderImpl.class);
-
- /**
- * The name of the properties file for database configuration
- */
- private static final String MDSALRESOURCE_PROP_FILE_NAME = "mdsal-resource.properties";
-
- /**
- * A prioritized list of strategies for resolving sql-resource properties files.
- */
- private Vector<PropertiesFileResolver> mdsalResourcePropertiesFileResolvers = new Vector<>();
-
- /**
- * The configuration properties for the db connection.
- */
- private Properties properties;
-
- /**
- * Set up the prioritized list of strategies for resolving dblib properties
- * files.
- */
- public MdsalResourcePropertiesProviderImpl() {
- mdsalResourcePropertiesFileResolvers
- .add(new SdncConfigEnvVarFileResolver("Using property file (1) from environment variable"));
- mdsalResourcePropertiesFileResolvers.add(new CoreDefaultFileResolver("Using property file (2) from default directory"));
-
- mdsalResourcePropertiesFileResolvers.add(
- new JREFileResolver("Using property file (3) from JRE argument", MdsalResourcePropertiesProviderImpl.class));
- mdsalResourcePropertiesFileResolvers.add(new KarafRootFileResolver("Using property file (4) from karaf root", this));
-
- // determines properties file as according to the priority described in the
- // class header comment
- final File propertiesFile = determinePropertiesFile(this);
- if (propertiesFile != null) {
- try (FileInputStream fileInputStream = new FileInputStream(propertiesFile)) {
- properties = new Properties();
- properties.load(fileInputStream);
- } catch (final IOException e) {
- LOG.error("Failed to load properties for file: {}", propertiesFile.toString(),
- new ConfigurationException("Failed to load properties for file: " + propertiesFile.toString(),
- e));
- }
- } else {
- // Try to read properties as resource
-
- InputStream propStr = getClass().getResourceAsStream("/" + MDSALRESOURCE_PROP_FILE_NAME);
- if (propStr != null) {
- properties = new Properties();
- try {
- properties.load(propStr);
- propStr.close();
- } catch (IOException e) {
- properties = null;
- }
- }
-
- }
-
- if (properties == null) {
- reportFailure("Missing configuration properties resource(3)", new ConfigurationException(
- "Missing configuration properties resource(3): " + MDSALRESOURCE_PROP_FILE_NAME));
- }
- }
-
- /**
- * Extract svclogic config properties.
- *
- * @return the svclogic config properties
- */
- public Properties getProperties() {
- return properties;
- }
-
- /**
- * Reports the method chosen for properties resolution to the
- * <code>Logger</code>.
- *
- * @param message
- * Some user friendly message
- * @param fileOptional
- * The file location of the chosen properties file
- * @return the file location of the chosen properties file
- */
- private static File reportSuccess(final String message, final Optional<File> fileOptional) {
- if (fileOptional.isPresent()) {
- final File file = fileOptional.get();
- LOG.info("{} {}", message, file.getPath());
- return file;
- }
- return null;
- }
-
- /**
- * Reports fatal errors. This is the case in which no properties file could be
- * found.
- *
- * @param message
- * An appropriate fatal error message
- * @param configurationException
- * An exception describing what went wrong during resolution
- */
- private static void reportFailure(final String message, final ConfigurationException configurationException) {
-
- LOG.error("{}", message, configurationException);
- }
-
- /**
- * Determines the sql-resource properties file to use based on the following priority:
- * <ol>
- * <li>A directory identified by the system environment variable
- * <code>SDNC_CONFIG_DIR</code></li>
- * <li>The default directory <code>DEFAULT_DBLIB_PROP_DIR</code></li>
- * <li>A directory identified by the JRE argument
- * <code>mdsal-resource.properties</code></li>
- * <li>A <code>sql-resource.properties</code> file located in the karaf root
- * directory</li>
- * </ol>
- */
- File determinePropertiesFile(final MdsalResourcePropertiesProviderImpl resourceProvider) {
-
- for (final PropertiesFileResolver sliPropertiesFileResolver : mdsalResourcePropertiesFileResolvers) {
- final Optional<File> fileOptional = sliPropertiesFileResolver.resolveFile(MDSALRESOURCE_PROP_FILE_NAME);
- if (fileOptional.isPresent()) {
- return reportSuccess(sliPropertiesFileResolver.getSuccessfulResolutionMessage(), fileOptional);
- }
- }
-
- return null;
- }
-}
diff --git a/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/OperationalResource.java b/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/OperationalResource.java
deleted file mode 100644
index 320878126..000000000
--- a/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/OperationalResource.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * openECOMP : SDN-C
- * ================================================================================
- * 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=========================================================
- */
-
-package org.onap.ccsdk.sli.adaptors.resource.mdsal;
-
-import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
-import org.onap.ccsdk.sli.core.sli.SvcLogicException;
-import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-
-import java.util.Map;
-import java.util.Properties;
-
-public class OperationalResource implements SvcLogicResource {
-
- private static final Logger LOG = LoggerFactory.getLogger(OperationalResource.class);
-
- private RestService restService;
-
- public OperationalResource(MdsalResourcePropertiesProvider propProvider) {
- Properties props = propProvider.getProperties();
-
- String sdncUser = props.getProperty("org.onap.ccsdk.sli.adaptors.resource.mdsal.sdnc-user", "admin");
- String sdncPasswd = props.getProperty("org.onap.ccsdk.sli.adaptors.resource.mdsal.sdnc-passwd", "admin");
- String sdncHost = props.getProperty("org.onap.ccsdk.sli.adaptors.resource.mdsal.sdnc-host", "localhost");
- String sdncProtocol = props.getProperty("org.onap.ccsdk.sli.adaptors.resource.mdsal.sdnc-protocol", "https");
- String sdncPort = props.getProperty("org.onap.ccsdk.sli.adaptors.resource.mdsal.sdnc-port", "8443");
-
- restService = new RestService(sdncProtocol, sdncHost, sdncPort, sdncUser, sdncPasswd, "XML", "XML");
- }
-
- public OperationalResource(String sdncProtocol, String sdncHost, String sdncPort, String sdncUser, String sdncPasswd) {
- restService = new RestService(sdncProtocol, sdncHost, sdncPort, sdncUser, sdncPasswd, "XML", "XML");
- }
-
- public OperationalResource(RestService restService) {
- this.restService = restService;
- }
-
- @Override
- public QueryStatus isAvailable(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException {
- return (query(resource, false, null, key, prefix, null, null));
- }
-
- @Override
- public QueryStatus exists(String resource, String key, String prefix, SvcLogicContext ctx) throws SvcLogicException {
- return (query(resource, false, null, key, prefix, null, null));
- }
-
- @Override
- public QueryStatus query(String resource, boolean localOnly, String select, String key, String prefix,
- String orderBy, SvcLogicContext ctx) throws SvcLogicException {
- String module = resource;
- StringBuffer restQuery = new StringBuffer();
-
- String[] keyParts = key.split("/");
- for (String keyPart : keyParts) {
- if (restQuery.length() > 0) {
- restQuery.append("/");
- }
- if (keyPart.startsWith("$")) {
- restQuery.append(ctx.resolve(keyPart.substring(1)));
- } else {
- restQuery.append(keyPart);
- }
- }
-
- String restQueryStr = restQuery.toString();
- if ((restQueryStr.startsWith("'") && restQueryStr.endsWith("'")) ||
- (restQueryStr.startsWith("\"") && restQueryStr.endsWith("\""))) {
- restQueryStr = restQueryStr.substring(1, restQueryStr.length() - 1);
- }
-
- String urlString = "restconf/operational/" + module + ":" + restQueryStr;
- LOG.info("Querying resource: " + resource + ". At URL: " + urlString);
-
- Document results = restService.get(urlString);
-
- if (results == null) {
- return (QueryStatus.NOT_FOUND);
- } else {
- if (ctx != null) {
- ctx.mergeDocument(prefix, results);
- }
- return (QueryStatus.SUCCESS);
- }
- }
-
- @Override
- public QueryStatus reserve(String resource, String select, String key, String prefix,
- SvcLogicContext ctx) throws SvcLogicException {
- return (QueryStatus.SUCCESS);
- }
-
- @Override
- public QueryStatus release(String resource, String key, SvcLogicContext ctx) throws SvcLogicException {
- return (QueryStatus.SUCCESS);
- }
-
- @Override
- public QueryStatus delete(String arg0, String arg1, SvcLogicContext arg2)
- throws SvcLogicException {
- // TODO Auto-generated method stub
- return (QueryStatus.SUCCESS);
- }
-
- @Override
- public QueryStatus save(String arg0, boolean arg1, boolean localOnly, String arg2,
- Map<String, String> arg3, String arg4, SvcLogicContext arg5)
- throws SvcLogicException {
- // TODO Auto-generated method stub
- return (QueryStatus.SUCCESS);
- }
-
- @Override
- public QueryStatus notify(String resource, String action, String key,
- SvcLogicContext ctx) throws SvcLogicException {
- return (QueryStatus.SUCCESS);
- }
-
- public QueryStatus update(String resource, String key,
- Map<String, String> parms, String prefix, SvcLogicContext ctx)
- throws SvcLogicException {
- return (QueryStatus.SUCCESS);
- }
-
-}
diff --git a/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/RestService.java b/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/RestService.java
deleted file mode 100644
index ebddc24ae..000000000
--- a/mdsal-resource/provider/src/main/java/org/onap/ccsdk/sli/adaptors/resource/mdsal/RestService.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * openECOMP : SDN-C
- * ================================================================================
- * 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=========================================================
- */
-
-package org.onap.ccsdk.sli.adaptors.resource.mdsal;
-
-import org.apache.commons.codec.binary.Base64;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
-import javax.xml.XMLConstants;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import java.io.*;
-import java.net.Authenticator;
-import java.net.HttpURLConnection;
-import java.net.PasswordAuthentication;
-import java.net.URL;
-
-public class RestService {
-
- private static final Logger LOG = LoggerFactory.getLogger(ConfigResource.class);
- private String user;
- private String passwd;
- private String contentType;
- private String accept;
- private String protocol;
- private String host;
- private String port;
-
- public RestService(String protocol, String host, String port, String user, String passwd, String accept, String contentType) {
- this.protocol = protocol;
- this.host = host;
- this.port = port;
- this.user = user;
- this.passwd = passwd;
- this.accept = accept;
- this.contentType = contentType;
- }
-
- private HttpURLConnection getRestConnection(String urlString, String method) throws IOException {
- URL sdncUrl = new URL(urlString);
- Authenticator.setDefault(new SdncAuthenticator(user, passwd));
-
- String authStr = user + ":" + passwd;
- String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes()));
-
- HttpURLConnection conn = (HttpURLConnection) sdncUrl.openConnection();
- conn.addRequestProperty("Authentication", "Basic " + encodedAuthStr);
- conn.setRequestMethod(method);
- conn.setDoInput(true);
- conn.setDoOutput(true);
- conn.setUseCaches(false);
-
- //Setting Accept header (doesn't dependent on Msg Body if present or not)
- if ("XML".equalsIgnoreCase(accept)) {
- conn.setRequestProperty("Accept", "application/xml");
- } else {
- conn.setRequestProperty("Accept", "application/json");
- }
-
- return (conn);
- }
-
- private Document send(String urlString, byte[] msgBytes, String method) {
- Document response = null;
- String fullUrl = protocol + "://" + host + ":" + port + "/" + urlString;
- LOG.info("Sending REST {} to {}", method, fullUrl);
-
- try {
- HttpURLConnection conn = getRestConnection(fullUrl, method);
- if (conn instanceof HttpsURLConnection) {
- HostnameVerifier hostnameVerifier = (hostname, session) -> true;
- ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier);
- }
-
- // Write message
- if (msgBytes != null) {
- LOG.info("Message body:\n{}", msgBytes);
- conn.setRequestProperty("Content-Length", "" + msgBytes.length);
-
- // Setting Content-Type header only if Msg Body is present
- if ("XML".equalsIgnoreCase(contentType)) {
- conn.setRequestProperty("Content-Type", "application/xml");
- } else {
- conn.setRequestProperty("Content-Type", "application/json");
- }
-
- DataOutputStream outStr = new DataOutputStream(conn.getOutputStream());
- outStr.write(msgBytes);
- outStr.close();
- } else {
- conn.setRequestProperty("Content-Length", "0");
- }
-
- // Read response
- LOG.info("Response: {} {}", conn.getResponseCode(), conn.getResponseMessage());
-
- BufferedReader respRdr;
- if (conn.getResponseCode() < 300) {
- respRdr = new BufferedReader(new InputStreamReader(conn.getInputStream()));
- } else {
- respRdr = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
- }
-
- StringBuffer respBuff = new StringBuffer();
- String respLn;
- while ((respLn = respRdr.readLine()) != null) {
- respBuff.append(respLn + "\n");
- }
- respRdr.close();
-
- String respString = respBuff.toString();
- LOG.info("Response body :\n{}", respString);
-
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
- dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
- dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
- DocumentBuilder db = dbf.newDocumentBuilder();
-
- response = db.parse(new ByteArrayInputStream(respString.getBytes()));
-
- } catch (Exception e) {
- LOG.error("Caught exception executing REST command", e);
- }
-
- return (response);
- }
-
- public Document get(String urlString) {
- return (send(urlString, null, "GET"));
- }
-
- public Document delete(String urlString) {
- return (send(urlString, null, "DELETE"));
- }
-
- public Document post(String urlString, byte[] msgBytes) {
- return (send(urlString, msgBytes, "POST"));
- }
-
- public Document put(String urlString, byte[] msgBytes) {
- return (send(urlString, msgBytes, "PUT"));
- }
-
-
- private class SdncAuthenticator extends Authenticator {
- private String user;
- private String passwd;
-
- SdncAuthenticator(String user, String passwd) {
- this.user = user;
- this.passwd = passwd;
- }
-
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(user, passwd.toCharArray());
- }
-
- }
-
-}