From 08ebd7f881b8fb713dfa6def495e6fd6407efbdf Mon Sep 17 00:00:00 2001 From: harshanl Date: Fri, 11 Dec 2015 11:10:53 +0530 Subject: [PATCH 1/6] Added DCR proxy endpoint & refactored code. --- .../dynamic-client-web-proxy/pom.xml | 133 ++++++++++++++++ .../client/web/proxy/OAuthEndpointProxy.java | 37 +++++ .../client/web/proxy/RegistrationProxy.java | 91 +++++++++++ .../client/web/proxy/util/Constants.java | 62 ++++++++ .../client/web/proxy/util/DCRProxyUtils.java | 76 +++++++++ .../web/proxy/util/RemoteDCRClient.java | 150 ++++++++++++++++++ .../webapp/META-INF/webapp-classloading.xml | 35 ++++ .../src/main/webapp/WEB-INF/cxf-servlet.xml | 51 ++++++ .../src/main/webapp/WEB-INF/web.xml | 37 +++++ .../src/main/webapp/servicelist.css | 125 +++++++++++++++ .../src/test/resources/log4j.properties | 32 ++++ .../src/test/resources/testng.xml | 23 +++ .../dynamic-client-web/pom.xml | 5 - .../client/web/RegistrationService.java | 2 +- .../src/main/webapp/WEB-INF/web.xml | 4 +- .../src/test/resources/testng.xml | 7 +- ...amicClientWebAppRegistrationConstants.java | 3 +- .../DynamicClientWebAppRegistrationUtil.java | 2 +- .../registration/util/RemoteDCRClient.java | 13 +- .../dynamic-client-registration/pom.xml | 1 + .../pom.xml | 9 ++ .../src/main/resources/p2.inf | 3 +- 22 files changed, 879 insertions(+), 22 deletions(-) create mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/pom.xml create mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/OAuthEndpointProxy.java create mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/RegistrationProxy.java create mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/Constants.java create mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/DCRProxyUtils.java create mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/RemoteDCRClient.java create mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/META-INF/webapp-classloading.xml create mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/WEB-INF/cxf-servlet.xml create mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/WEB-INF/web.xml create mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/servicelist.css create mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/test/resources/log4j.properties create mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/test/resources/testng.xml diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/pom.xml b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/pom.xml new file mode 100644 index 0000000000..05c20176cd --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/pom.xml @@ -0,0 +1,133 @@ + + + + + + dynamic-client-registration + org.wso2.carbon.devicemgt + 0.9.2-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.mdm + dynamic-client-web-proxy + 0.9.2-SNAPSHOT + WSO2 Carbon - Proxy endpoint of Dynamic Client Registration Web Service + WSO2 Carbon - Dynamic Client Registration Web Proxy + war + + + + + maven-war-plugin + 2.2 + + ${project.artifactId} + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.18 + + + file:src/test/resources/log4j.properties + + + src/test/resources/testng.xml + + + + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.dynamic.client.registration + provided + + + org.wso2.carbon + org.wso2.carbon.utils + provided + + + org.apache.ws.commons.axiom + axiom-api + provided + + + org.apache.ws.commons.axiom + axiom-impl + provided + + + org.apache.ws.commons.axiom.wso2 + axiom + provided + + + org.apache.cxf + cxf-rt-frontend-jaxrs + provided + + + org.apache.cxf + cxf-rt-transports-http + provided + + + org.apache.cxf + cxf-rt-bindings-http + provided + + + org.testng + testng + provided + + + org.codehaus.jackson + jackson-jaxrs + + + commons-logging + commons-logging + provided + + + org.apache.httpcomponents + httpclient + + + com.google.code.gson + gson + provided + + + org.wso2.carbon + org.wso2.carbon.core + provided + + + \ No newline at end of file diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/OAuthEndpointProxy.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/OAuthEndpointProxy.java new file mode 100644 index 0000000000..60ff66bddc --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/OAuthEndpointProxy.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.dynamic.client.web.proxy; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.ws.rs.POST; + +/** + * Created by harshan on 12/10/15. + */ +public class OAuthEndpointProxy { + + private static final Log log = LogFactory.getLog(OAuthEndpointProxy.class); + + @POST + public String getAccessToken() { + return ""; + } +} diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/RegistrationProxy.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/RegistrationProxy.java new file mode 100644 index 0000000000..556c62ef35 --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/RegistrationProxy.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.dynamic.client.web.proxy; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.util.EntityUtils; +import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationException; +import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile; +import org.wso2.carbon.dynamic.client.web.proxy.util.Constants; +import org.wso2.carbon.dynamic.client.web.proxy.util.DCRProxyUtils; +import org.wso2.carbon.dynamic.client.web.proxy.util.RemoteDCRClient; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.IOException; + +/** + * Created by harshan on 12/10/15. + */ + +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public class RegistrationProxy { + + private static final Log log = LogFactory.getLog(RegistrationProxy.class); + + @POST + public Response register(RegistrationProfile profile) { + Response response; + try { + CloseableHttpResponse serverResponse = RemoteDCRClient.createOAuthApplication(profile); + HttpEntity responseData = serverResponse.getEntity(); + int status = serverResponse.getStatusLine().getStatusCode(); + String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF8); + response = Response.status(DCRProxyUtils.getResponseStatus(status)).entity(resp).build(); + } catch (DynamicClientRegistrationException e) { + String msg = "Server error occurred while registering client '" + profile.getClientName() + "'"; + log.error(msg, e); + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (IOException e) { + String msg = "Service invoke error occurred while registering client '" + profile.getClientName() + "'"; + log.error(msg, e); + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return response; + } + + @DELETE + public Response unregister(@QueryParam("applicationName") String applicationName, + @QueryParam("userId") String userId, + @QueryParam("consumerKey") String consumerKey) { + Response response; + try { + CloseableHttpResponse serverResponse = RemoteDCRClient.deleteOAuthApplication(userId, applicationName, + consumerKey); + HttpEntity responseData = serverResponse.getEntity(); + int status = serverResponse.getStatusLine().getStatusCode(); + String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF8); + response = Response.status(DCRProxyUtils.getResponseStatus(status)).entity(resp).build(); + } catch (DynamicClientRegistrationException e) { + String msg = "Server error occurred while deleting the client '" + applicationName + "'"; + log.error(msg, e); + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (IOException e) { + String msg = "Service invoke error occurred while deleting the client '" + applicationName + "'"; + log.error(msg, e); + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + return response; + } +} \ No newline at end of file diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/Constants.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/Constants.java new file mode 100644 index 0000000000..74a491e156 --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/Constants.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.dynamic.client.web.proxy.util; + +/** + * Created by harshan on 12/10/15. + */ +public class Constants { + + public static final class ContentTypes { + private ContentTypes() { + throw new AssertionError(); + } + + public static final String CONTENT_TYPE_ANY = "*/*"; + public static final String CONTENT_TYPE_XML = "application/xml"; + public static final String CONTENT_TYPE_APPLICATION_JSON = "application/json"; + } + + public static final class CharSets { + private CharSets() { + throw new AssertionError(); + } + + public static final String CHARSET_UTF8 = "UTF8"; + } + + public static class ConfigurationProperties { + private ConfigurationProperties() { + throw new AssertionError(); + } + + public static final String AUTHENTICATOR_NAME = "OAuthAuthenticator"; + public static final String AUTHENTICATOR_CONFIG_IS_REMOTE = "isRemote"; + public static final String AUTHENTICATOR_CONFIG_HOST_URL = "hostURL"; + } + + public static class RemoteServiceProperties { + private RemoteServiceProperties() { + throw new AssertionError(); + } + + public static final String DYNAMIC_CLIENT_SERVICE_ENDPOINT = "/dynamic-client-web/register"; + public static final String DYNAMIC_CLIENT_SERVICE_PROTOCOL = "https"; + } +} diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/DCRProxyUtils.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/DCRProxyUtils.java new file mode 100644 index 0000000000..7cfa96f1ab --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/DCRProxyUtils.java @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.dynamic.client.web.proxy.util; + +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.core.security.AuthenticatorsConfiguration; +import org.wso2.carbon.utils.ConfigurationContextService; + +import javax.ws.rs.core.Response; + +/** + * Created by harshan on 12/10/15. + */ +public class DCRProxyUtils { + + public static ConfigurationContextService getConfigurationContextService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + return (ConfigurationContextService) ctx.getOSGiService(ConfigurationContextService.class, null); + } + + public static Response.Status getResponseStatus(int statusCode) { + switch (statusCode) { + case 200 : + return Response.Status.OK; + case 201 : + return Response.Status.CREATED; + case 400 : + return Response.Status.BAD_REQUEST; + case 500 : + return Response.Status.INTERNAL_SERVER_ERROR; + } + return Response.Status.ACCEPTED; + } + + public static String getKeyManagerHost() + throws IllegalArgumentException { + AuthenticatorsConfiguration authenticatorsConfiguration = AuthenticatorsConfiguration.getInstance(); + AuthenticatorsConfiguration.AuthenticatorConfig authenticatorConfig = authenticatorsConfiguration. + getAuthenticatorConfig( + Constants.ConfigurationProperties.AUTHENTICATOR_NAME); + if (authenticatorConfig != null && authenticatorConfig.getParameters() != null) { + return getHostName(authenticatorConfig.getParameters().get(Constants.ConfigurationProperties. + AUTHENTICATOR_CONFIG_HOST_URL)); + + }else{ + throw new IllegalArgumentException("Configuration parameters need to be defined in Authenticators.xml."); + } + } + + private static String getHostName(String host) { + if (host != null && !host.isEmpty()) { + if (host.contains("https://")) { + return host.replace("https://",""); + } + } else { + throw new IllegalArgumentException("Remote Host parameter must defined in Authenticators.xml."); + } + return null; + } +} diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/RemoteDCRClient.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/RemoteDCRClient.java new file mode 100644 index 0000000000..1bf917bb78 --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/RemoteDCRClient.java @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.dynamic.client.web.proxy.util; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.conn.ssl.X509HostnameVerifier; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.SingleClientConnManager; +import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationException; +import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile; +import org.wso2.carbon.utils.CarbonUtils; +import org.wso2.carbon.utils.ConfigurationContextService; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; + +/** + * This class holds the necessary logic to create and delete service-providers by invoking the + * dynamic-client-registration endpoint. + */ +public class RemoteDCRClient { + + private static final String CONTENT_TYPE_APPLICATION_JSON = "application/json"; + private static final String CHARSET_UTF_8 = "UTF-8"; + + public static CloseableHttpResponse createOAuthApplication(RegistrationProfile registrationProfile) + throws DynamicClientRegistrationException { + DefaultHttpClient httpClient = new DefaultHttpClient(); + String clientName = registrationProfile.getClientName(); + String host = DCRProxyUtils.getKeyManagerHost(); + try { + // Setup the HTTPS settings to accept any certificate. + HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; + + SchemeRegistry registry = new SchemeRegistry(); + SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); + socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); + registry.register(new Scheme(Constants.RemoteServiceProperties. + DYNAMIC_CLIENT_SERVICE_PROTOCOL, socketFactory, getServerHTTPSPort())); + SingleClientConnManager mgr = new SingleClientConnManager(httpClient.getParams(), registry); + httpClient = new DefaultHttpClient(mgr, httpClient.getParams()); + + // Set verifier + HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); + + URI uri = new URIBuilder().setScheme(Constants.RemoteServiceProperties. + DYNAMIC_CLIENT_SERVICE_PROTOCOL).setHost(host).setPath( + Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT).build(); + Gson gson = new Gson(); + StringEntity entity = new StringEntity(gson.toJson(registrationProfile), CONTENT_TYPE_APPLICATION_JSON, + CHARSET_UTF_8); + HttpPost httpPost = new HttpPost(uri); + httpPost.setEntity(entity); + return httpClient.execute(httpPost); + } catch (URISyntaxException e) { + throw new DynamicClientRegistrationException("Exception occurred while constructing the URI for invoking " + + "DCR endpoint for registering service-provider for web-app : " + + clientName, e); + } catch (UnsupportedEncodingException e) { + throw new DynamicClientRegistrationException("Exception occurred while constructing the payload for invoking " + + "DCR endpoint for registering service-provider for web-app : " + + clientName, e); + } catch (IOException e) { + throw new DynamicClientRegistrationException("Connection error occurred while invoking DCR endpoint for" + + " registering service-provider for web-app : " + clientName, e); + } + } + + public static CloseableHttpResponse deleteOAuthApplication(String user, String appName, String clientid) + throws DynamicClientRegistrationException { + DefaultHttpClient httpClient = new DefaultHttpClient(); + String host = DCRProxyUtils.getKeyManagerHost(); + try { + // Setup the HTTPS settings to accept any certificate. + HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; + + SchemeRegistry registry = new SchemeRegistry(); + SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); + socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); + registry.register(new Scheme(Constants.RemoteServiceProperties. + DYNAMIC_CLIENT_SERVICE_PROTOCOL, socketFactory, getServerHTTPSPort())); + SingleClientConnManager mgr = new SingleClientConnManager(httpClient.getParams(), registry); + httpClient = new DefaultHttpClient(mgr, httpClient.getParams()); + + // Set verifier + HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); + + URI uri = new URIBuilder().setScheme(Constants.RemoteServiceProperties. + DYNAMIC_CLIENT_SERVICE_PROTOCOL).setHost(host).setPath( + Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT) + .setParameter("applicationName", appName) + .setParameter("userId", user) + .setParameter("consumerKey", clientid).build(); + HttpDelete httpDelete = new HttpDelete(uri); + return httpClient.execute(httpDelete); + } catch (IOException e) { + throw new DynamicClientRegistrationException("Connection error occurred while constructing the payload for " + + "invoking DCR endpoint for unregistering the web-app : " + appName, e); + } catch (URISyntaxException e) { + throw new DynamicClientRegistrationException("Exception occurred while constructing the URI for invoking " + + "DCR endpoint for unregistering the web-app : " + appName, e); + } + } + + private static int getServerHTTPSPort() { + // HTTPS port + String mgtConsoleTransport = CarbonUtils.getManagementTransport(); + ConfigurationContextService configContextService = DCRProxyUtils.getConfigurationContextService(); + int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport); + int httpsProxyPort = + CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(), + mgtConsoleTransport); + if (httpsProxyPort > 0) { + port = httpsProxyPort; + } + return port; + } +} \ No newline at end of file diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/META-INF/webapp-classloading.xml b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 0000000000..38ac535842 --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,35 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 0000000000..3044b684e7 --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/WEB-INF/web.xml b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000000..091413931d --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,37 @@ + + + + Dynamic-client-proxy-Webapp + + Dynamic-client-registration-proxy Endpoint + JAX-WS/JAX-RS Servlet + CXFServlet + + org.apache.cxf.transport.servlet.CXFServlet + + 1 + + + CXFServlet + /* + + + 60 + + \ No newline at end of file diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/servicelist.css b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/servicelist.css new file mode 100644 index 0000000000..e6eacadbb0 --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/servicelist.css @@ -0,0 +1,125 @@ +@CHARSET "ISO-8859-1"; + +/* http://meyerweb.com/eric/tools/css/reset/ + v2.0 | 20110126 + License: none (public domain) +*/ + +html, body, div, span, applet, object, iframe, +h1, h2, h3, h4, h5, h6, p, blockquote, pre, +a, abbr, acronym, address, big, cite, code, +del, dfn, em, img, ins, kbd, q, s, samp, +small, strike, strong, sub, sup, tt, var, +b, u, i, center, +dl, dt, dd, ol, ul, li, +fieldset, form, label, legend, +table, caption, tbody, tfoot, thead, tr, th, td, +article, aside, canvas, details, embed, +figure, figcaption, footer, header, hgroup, +menu, nav, output, ruby, section, summary, +time, mark, audio, video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; +} + +/* HTML5 display-role reset for older browsers */ +article, aside, details, figcaption, figure, +footer, header, hgroup, menu, nav, section { + display: block; +} + +html { + background: #efefef; +} + +body { + line-height: 1; + width: 960px; + margin: auto; + background: white; + padding: 10px; + box-shadow: 0px 0px 5px #CCC; + font-family: "Lucida Grande", "Lucida Sans", "Microsoft Sans Serif", "Lucida Sans Unicode", "Verdana", "Sans-serif", "trebuchet ms" !important; + +} + +ol, ul { + list-style: none; +} + +blockquote, q { + quotes: none; +} + +blockquote:before, blockquote:after, +q:before, q:after { + content: ''; + content: none; +} + +table { + border-collapse: collapse; + border-spacing: 0; + width: 960px; + border: solid 1px #ccc; +} + +table a { + font-size: 12px; + color: #1e90ff; + padding: 7px; + float: left;; +} + +.heading { + font-size: 18px; + margin-top: 20px; + float: left; + color: #0067B1; + margin-bottom: 20px; + padding-top: 20px; +} + +.field { + font-weight: normal; + width: 120px; + font-size: 12px; + float: left; + padding: 7px; + clear: left; +} + +.value { + font-weight: bold; + font-size: 12px; + float: left; + padding: 7px; + clear: right; +} + +.porttypename { + font-weight: bold; + font-size: 14px; +} + +UL { + margin-top: 0; +} + +LI { + font-weight: normal; + font-size: 12px; + margin-top: 10px; +} + +TD { + border: 1px solid #ccc; + vertical-align: text-top; + padding: 5px; +} + + diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/test/resources/log4j.properties b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/test/resources/log4j.properties new file mode 100644 index 0000000000..7da6d6c9e1 --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/test/resources/log4j.properties @@ -0,0 +1,32 @@ +# +# Copyright 2009 WSO2, Inc. (http://wso2.com) +# +# 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. +# + +# +# This is the log4j configuration file used by WSO2 Carbon +# +# IMPORTANT : Please do not remove or change the names of any +# of the Appenders defined here. The layout pattern & log file +# can be changed using the WSO2 Carbon Management Console, and those +# settings will override the settings in this file. +# + +log4j.rootLogger=DEBUG, STD_OUT + +# Redirect log messages to console +log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender +log4j.appender.STD_OUT.Target=System.out +log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout +log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/test/resources/testng.xml b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/test/resources/testng.xml new file mode 100644 index 0000000000..c0c21a40c3 --- /dev/null +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/test/resources/testng.xml @@ -0,0 +1,23 @@ + + + + + + + \ No newline at end of file diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/pom.xml b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/pom.xml index 9df732403c..1df2b45ea1 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/pom.xml +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/pom.xml @@ -87,11 +87,6 @@ cxf-rt-transports-http provided - - org.apache.cxf - cxf-rt-bindings-soap - compile - org.apache.cxf cxf-rt-bindings-http diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/RegistrationService.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/RegistrationService.java index 194d5e966d..3c42d87bf8 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/RegistrationService.java +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/RegistrationService.java @@ -63,7 +63,7 @@ public interface RegistrationService { * @return Status 200 if success. */ @DELETE - public Response unregister(@QueryParam("applicationName") String applicationName, + Response unregister(@QueryParam("applicationName") String applicationName, @QueryParam("userId") String userId, @QueryParam("consumerKey") String consumerKey); diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/webapp/WEB-INF/web.xml b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/webapp/WEB-INF/web.xml index a89397675a..57eb77536b 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/webapp/WEB-INF/web.xml +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/webapp/WEB-INF/web.xml @@ -19,9 +19,9 @@ ~ */ --> - Admin-Webapp + dynamic-client-registration-Webapp - JAX-WS/JAX-RS Device Registration Agent Endpoint + Dynamic-client-registration Agent Endpoint JAX-WS/JAX-RS Servlet CXFServlet diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/test/resources/testng.xml b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/test/resources/testng.xml index de65e3005d..c25631e70a 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/test/resources/testng.xml +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/test/resources/testng.xml @@ -18,11 +18,6 @@ - + - - - - - \ No newline at end of file diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationConstants.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationConstants.java index 12697ceb31..ca5e9a0eb6 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationConstants.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationConstants.java @@ -36,7 +36,8 @@ public class DynamicClientWebAppRegistrationConstants { } public static final String CONTENT_TYPE_ANY = "*/*"; - public static final String MEDIA_TYPE_XML = "application/xml"; + public static final String CONTENT_TYPE_XML = "application/xml"; + public static final String CONTENT_TYPE_APPLICATION_JSON = "application/json"; } public static final class CharSets { diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java index 2372997655..ce6eaa50ee 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/DynamicClientWebAppRegistrationUtil.java @@ -117,7 +117,7 @@ public class DynamicClientWebAppRegistrationUtil { Resource resource = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry().newResource(); resource.setContent(writer.toString()); - resource.setMediaType(DynamicClientWebAppRegistrationConstants.ContentTypes.MEDIA_TYPE_XML); + resource.setMediaType(DynamicClientWebAppRegistrationConstants.ContentTypes.CONTENT_TYPE_XML); String resourcePath = DynamicClientWebAppRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + oAuthAppDetails.getClientName(); status = DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource); diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/RemoteDCRClient.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/RemoteDCRClient.java index 120b2f056f..f8e97ed5c0 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/RemoteDCRClient.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/RemoteDCRClient.java @@ -21,6 +21,8 @@ package org.wso2.carbon.dynamic.client.web.app.registration.util; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpDelete; @@ -54,8 +56,7 @@ import java.net.URISyntaxException; */ public class RemoteDCRClient { - private static final String CONTENT_TYPE_APPLICATION_JSON = "application/json"; - private static final String CHARSET_UTF_8 = "UTF-8"; + private static final Log log = LogFactory.getLog(RemoteDCRClient.class); public static OAuthApplicationInfo createOAuthApplication(RegistrationProfile registrationProfile, String host) throws DynamicClientRegistrationException { @@ -80,14 +81,16 @@ public class RemoteDCRClient { DYNAMIC_CLIENT_SERVICE_PROTOCOL).setHost(host).setPath( DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT).build(); Gson gson = new Gson(); - StringEntity entity = new StringEntity(gson.toJson(registrationProfile), CONTENT_TYPE_APPLICATION_JSON, - CHARSET_UTF_8); + StringEntity entity = new StringEntity(gson.toJson(registrationProfile), + DynamicClientWebAppRegistrationConstants.ContentTypes.CONTENT_TYPE_APPLICATION_JSON, + DynamicClientWebAppRegistrationConstants.CharSets.CHARSET_UTF8); HttpPost httpPost = new HttpPost(uri); httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); HttpEntity responseData = response.getEntity(); - String responseString = EntityUtils.toString(responseData, CHARSET_UTF_8); + String responseString = EntityUtils.toString(responseData, DynamicClientWebAppRegistrationConstants. + CharSets.CHARSET_UTF8); if (status != 201) { throw new DynamicClientRegistrationException("Backend server error occurred while invoking DCR endpoint for " + "registering service-provider for web-app : " + clientName); diff --git a/components/identity-extensions/dynamic-client-registration/pom.xml b/components/identity-extensions/dynamic-client-registration/pom.xml index e568ea5e88..54e68022ac 100644 --- a/components/identity-extensions/dynamic-client-registration/pom.xml +++ b/components/identity-extensions/dynamic-client-registration/pom.xml @@ -36,6 +36,7 @@ dynamic-client-web + dynamic-client-web-proxy org.wso2.carbon.dynamic.client.registration org.wso2.carbon.dynamic.client.web.app.registration diff --git a/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/pom.xml b/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/pom.xml index 3f55389989..44ae1e0e36 100644 --- a/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/pom.xml +++ b/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/pom.xml @@ -105,6 +105,15 @@ ${basedir}/src/main/resources/ dynamic-client-web.war + + org.wso2.mdm + dynamic-client-web-proxy + ${carbon.device.mgt.version} + war + true + ${basedir}/src/main/resources/ + dynamic-client-web-proxy.war + diff --git a/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/src/main/resources/p2.inf b/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/src/main/resources/p2.inf index 0f2ca3fd11..e25a76e1cf 100644 --- a/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/src/main/resources/p2.inf +++ b/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/src/main/resources/p2.inf @@ -1,2 +1,3 @@ instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.dynamic.client.registration.server_${feature.version}/dynamic-client-web.war,target:${installFolder}/../../deployment/server/webapps/dynamic-client-web.war,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.dynamic.client.registration.server_${feature.version}/dynamic-client-web.war,target:${installFolder}/../../deployment/server/webapps/dynamic-client-web.war,overwrite:true);\ +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.dynamic.client.registration.server_${feature.version}/dynamic-client-web-proxy.war,target:${installFolder}/../../deployment/server/webapps/dynamic-client-web-proxy.war,overwrite:true);\ \ No newline at end of file From 00cf61c44c41ab02d3c9d83a654dddf054d0af46 Mon Sep 17 00:00:00 2001 From: harshanl Date: Fri, 11 Dec 2015 20:04:22 +0530 Subject: [PATCH 2/6] Fixed EMM-1069 and refactore DCR services --- .../dynamic-client-web-proxy/pom.xml | 19 --- .../client/web/proxy/OAuthEndpointProxy.java | 53 ++++++- .../client/web/proxy/RegistrationProxy.java | 74 ++++++--- .../client/web/proxy/util/Constants.java | 16 +- .../client/web/proxy/util/DCRProxyUtils.java | 48 +++++- .../web/proxy/util/RemoteDCRClient.java | 150 ------------------ .../src/main/webapp/WEB-INF/cxf-servlet.xml | 2 +- .../client/web/RegistrationService.java | 6 +- .../web/impl/RegistrationServiceImpl.java | 2 - .../registration/util/RemoteDCRClient.java | 98 ++++++------ .../core/mgt/impl/MonitoringManagerImpl.java | 17 +- .../authenticator/OAuthAuthenticator.java | 5 +- .../pom.xml | 9 -- .../src/main/resources/p2.inf | 3 +- 14 files changed, 226 insertions(+), 276 deletions(-) delete mode 100644 components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/RemoteDCRClient.java diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/pom.xml b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/pom.xml index 05c20176cd..2b03b808fb 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/pom.xml +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/pom.xml @@ -44,20 +44,6 @@ ${project.artifactId} - - - org.apache.maven.plugins - maven-surefire-plugin - 2.18 - - - file:src/test/resources/log4j.properties - - - src/test/resources/testng.xml - - - @@ -101,11 +87,6 @@ cxf-rt-bindings-http provided - - org.testng - testng - provided - org.codehaus.jackson jackson-jaxrs diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/OAuthEndpointProxy.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/OAuthEndpointProxy.java index 60ff66bddc..c738d8aec1 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/OAuthEndpointProxy.java +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/OAuthEndpointProxy.java @@ -20,18 +20,61 @@ package org.wso2.carbon.dynamic.client.web.proxy; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpEntity; +import org.apache.http.HttpHost; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.util.EntityUtils; +import org.wso2.carbon.dynamic.client.web.proxy.util.Constants; +import org.wso2.carbon.dynamic.client.web.proxy.util.DCRProxyUtils; +import javax.ws.rs.Consumes; import javax.ws.rs.POST; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; -/** - * Created by harshan on 12/10/15. - */ public class OAuthEndpointProxy { private static final Log log = LogFactory.getLog(OAuthEndpointProxy.class); @POST - public String getAccessToken() { - return ""; + @Consumes("application/x-www-form-urlencoded") + @Produces("application/json") + public Response issueAccessToken(MultivaluedMap paramMap) { + DefaultHttpClient httpClient = DCRProxyUtils.getHttpsClient(); + String host = DCRProxyUtils.getKeyManagerHost(); + Response response; + try { + URI uri = new URIBuilder().setScheme(Constants.RemoteServiceProperties. + DYNAMIC_CLIENT_SERVICE_PROTOCOL).setHost(host).setPath( + Constants.RemoteServiceProperties.OAUTH2_TOKEN_ENDPOINT).build(); + HttpHost httpHost = new HttpHost(uri.toString()); + CloseableHttpResponse serverResponse = httpClient.execute(httpHost, null); + HttpEntity responseData = serverResponse.getEntity(); + int status = serverResponse.getStatusLine().getStatusCode(); + String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF_8); + response = Response.status(DCRProxyUtils.getResponseStatus(status)).entity(resp).build(); + } catch (URISyntaxException e) { + String msg = "Service invoke error occurred while registering client"; + log.error(msg, e); + response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (UnsupportedEncodingException e) { + String msg = "Service invoke error occurred while registering client"; + log.error(msg, e); + response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } catch (IOException e) { + String msg = "Service invoke error occurred while registering client"; + log.error(msg, e); + response = Response.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } finally { + httpClient.close(); + } + return response; } } diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/RegistrationProxy.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/RegistrationProxy.java index 556c62ef35..885530df77 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/RegistrationProxy.java +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/RegistrationProxy.java @@ -18,73 +18,111 @@ package org.wso2.carbon.dynamic.client.web.proxy; +import com.google.gson.Gson; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; -import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationException; import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile; import org.wso2.carbon.dynamic.client.web.proxy.util.Constants; import org.wso2.carbon.dynamic.client.web.proxy.util.DCRProxyUtils; -import org.wso2.carbon.dynamic.client.web.proxy.util.RemoteDCRClient; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; /** - * Created by harshan on 12/10/15. + * This class implements the proxy-endpoint for Dynamic-client-registration web service endpoints. */ - -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) public class RegistrationProxy { private static final Log log = LogFactory.getLog(RegistrationProxy.class); @POST - public Response register(RegistrationProfile profile) { + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + public Response register(RegistrationProfile registrationProfile) { + DefaultHttpClient httpClient = DCRProxyUtils.getHttpsClient(); + String host = DCRProxyUtils.getKeyManagerHost(); Response response; try { - CloseableHttpResponse serverResponse = RemoteDCRClient.createOAuthApplication(profile); + URI uri = new URIBuilder().setScheme(Constants.RemoteServiceProperties. + DYNAMIC_CLIENT_SERVICE_PROTOCOL).setHost(host).setPath( + Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT).build(); + Gson gson = new Gson(); + StringEntity entity = new StringEntity(gson.toJson(registrationProfile), MediaType.APPLICATION_JSON, + Constants.CharSets.CHARSET_UTF_8); + HttpPost httpPost = new HttpPost(uri); + httpPost.setEntity(entity); + CloseableHttpResponse serverResponse = httpClient.execute(httpPost); HttpEntity responseData = serverResponse.getEntity(); int status = serverResponse.getStatusLine().getStatusCode(); - String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF8); + String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF_8); response = Response.status(DCRProxyUtils.getResponseStatus(status)).entity(resp).build(); - } catch (DynamicClientRegistrationException e) { - String msg = "Server error occurred while registering client '" + profile.getClientName() + "'"; + } catch (URISyntaxException e) { + String msg = "Server error occurred while registering client '" + registrationProfile.getClientName() + "'"; log.error(msg, e); - response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + response = Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (UnsupportedEncodingException e) { + String msg = "Request data encoding error occurred while registering client '" + registrationProfile. + getClientName() + "'"; + log.error(msg, e); + response = Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).entity(msg).build(); } catch (IOException e) { - String msg = "Service invoke error occurred while registering client '" + profile.getClientName() + "'"; + String msg = "Service invoke error occurred while registering client."; log.error(msg, e); response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } finally { + httpClient.close(); } return response; } @DELETE + @Produces(MediaType.APPLICATION_JSON) public Response unregister(@QueryParam("applicationName") String applicationName, @QueryParam("userId") String userId, @QueryParam("consumerKey") String consumerKey) { Response response; + DefaultHttpClient httpClient = DCRProxyUtils.getHttpsClient(); + String host = DCRProxyUtils.getKeyManagerHost(); try { - CloseableHttpResponse serverResponse = RemoteDCRClient.deleteOAuthApplication(userId, applicationName, - consumerKey); + URI uri = new URIBuilder().setScheme(Constants.RemoteServiceProperties. + DYNAMIC_CLIENT_SERVICE_PROTOCOL).setHost(host).setPath( + Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT) + .setParameter("applicationName", applicationName) + .setParameter("userId", userId) + .setParameter("consumerKey", consumerKey).build(); + HttpDelete httpDelete = new HttpDelete(uri); + CloseableHttpResponse serverResponse = httpClient.execute(httpDelete); HttpEntity responseData = serverResponse.getEntity(); int status = serverResponse.getStatusLine().getStatusCode(); - String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF8); + String resp = EntityUtils.toString(responseData, Constants.CharSets.CHARSET_UTF_8); response = Response.status(DCRProxyUtils.getResponseStatus(status)).entity(resp).build(); - } catch (DynamicClientRegistrationException e) { + } catch (URISyntaxException e) { String msg = "Server error occurred while deleting the client '" + applicationName + "'"; log.error(msg, e); - response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + response = Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); + } catch (UnsupportedEncodingException e) { + String msg = "Request data encoding error occurred while deleting the client '" + applicationName + "'"; + log.error(msg, e); + response = Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).entity(msg).build(); } catch (IOException e) { String msg = "Service invoke error occurred while deleting the client '" + applicationName + "'"; log.error(msg, e); response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } finally { + httpClient.close(); } return response; } diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/Constants.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/Constants.java index 74a491e156..a63a530edb 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/Constants.java +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/Constants.java @@ -19,26 +19,16 @@ package org.wso2.carbon.dynamic.client.web.proxy.util; /** - * Created by harshan on 12/10/15. + * Holds the constants used by DCR proxy app. */ public class Constants { - public static final class ContentTypes { - private ContentTypes() { - throw new AssertionError(); - } - - public static final String CONTENT_TYPE_ANY = "*/*"; - public static final String CONTENT_TYPE_XML = "application/xml"; - public static final String CONTENT_TYPE_APPLICATION_JSON = "application/json"; - } - public static final class CharSets { private CharSets() { throw new AssertionError(); } - public static final String CHARSET_UTF8 = "UTF8"; + public static final String CHARSET_UTF_8 = "UTF-8"; } public static class ConfigurationProperties { @@ -47,7 +37,6 @@ public class Constants { } public static final String AUTHENTICATOR_NAME = "OAuthAuthenticator"; - public static final String AUTHENTICATOR_CONFIG_IS_REMOTE = "isRemote"; public static final String AUTHENTICATOR_CONFIG_HOST_URL = "hostURL"; } @@ -57,6 +46,7 @@ public class Constants { } public static final String DYNAMIC_CLIENT_SERVICE_ENDPOINT = "/dynamic-client-web/register"; + public static final String OAUTH2_TOKEN_ENDPOINT = "/oauth2/token"; public static final String DYNAMIC_CLIENT_SERVICE_PROTOCOL = "https"; } } diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/DCRProxyUtils.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/DCRProxyUtils.java index 7cfa96f1ab..d9d1e549b2 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/DCRProxyUtils.java +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/DCRProxyUtils.java @@ -18,14 +18,25 @@ package org.wso2.carbon.dynamic.client.web.proxy.util; +import org.apache.http.HttpHost; +import org.apache.http.client.utils.URIBuilder; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.conn.ssl.X509HostnameVerifier; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.SingleClientConnManager; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.core.security.AuthenticatorsConfiguration; +import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.ConfigurationContextService; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; import javax.ws.rs.core.Response; /** - * Created by harshan on 12/10/15. + * Holds the utility methods used by DCR proxy app. */ public class DCRProxyUtils { @@ -34,6 +45,24 @@ public class DCRProxyUtils { return (ConfigurationContextService) ctx.getOSGiService(ConfigurationContextService.class, null); } + public static DefaultHttpClient getHttpsClient() { + DefaultHttpClient httpClient = new DefaultHttpClient(); + // Setup the HTTPS settings to accept any certificate. + HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; + + SchemeRegistry registry = new SchemeRegistry(); + SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); + socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); + registry.register(new Scheme(Constants.RemoteServiceProperties. + DYNAMIC_CLIENT_SERVICE_PROTOCOL, socketFactory, DCRProxyUtils.getServerHTTPSPort())); + SingleClientConnManager mgr = new SingleClientConnManager(httpClient.getParams(), registry); + httpClient = new DefaultHttpClient(mgr, httpClient.getParams()); + + // Set verifier + HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); + return httpClient; + } + public static Response.Status getResponseStatus(int statusCode) { switch (statusCode) { case 200 : @@ -42,6 +71,8 @@ public class DCRProxyUtils { return Response.Status.CREATED; case 400 : return Response.Status.BAD_REQUEST; + case 415 : + return Response.Status.UNSUPPORTED_MEDIA_TYPE; case 500 : return Response.Status.INTERNAL_SERVER_ERROR; } @@ -73,4 +104,19 @@ public class DCRProxyUtils { } return null; } + + + public static int getServerHTTPSPort() { + // HTTPS port + String mgtConsoleTransport = CarbonUtils.getManagementTransport(); + ConfigurationContextService configContextService = DCRProxyUtils.getConfigurationContextService(); + int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport); + int httpsProxyPort = + CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(), + mgtConsoleTransport); + if (httpsProxyPort > 0) { + port = httpsProxyPort; + } + return port; + } } diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/RemoteDCRClient.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/RemoteDCRClient.java deleted file mode 100644 index 1bf917bb78..0000000000 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/java/org/wso2/carbon/dynamic/client/web/proxy/util/RemoteDCRClient.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * you may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.dynamic.client.web.proxy.util; - -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.conn.ssl.X509HostnameVerifier; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.SingleClientConnManager; -import org.wso2.carbon.dynamic.client.registration.DynamicClientRegistrationException; -import org.wso2.carbon.dynamic.client.registration.profile.RegistrationProfile; -import org.wso2.carbon.utils.CarbonUtils; -import org.wso2.carbon.utils.ConfigurationContextService; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; - -/** - * This class holds the necessary logic to create and delete service-providers by invoking the - * dynamic-client-registration endpoint. - */ -public class RemoteDCRClient { - - private static final String CONTENT_TYPE_APPLICATION_JSON = "application/json"; - private static final String CHARSET_UTF_8 = "UTF-8"; - - public static CloseableHttpResponse createOAuthApplication(RegistrationProfile registrationProfile) - throws DynamicClientRegistrationException { - DefaultHttpClient httpClient = new DefaultHttpClient(); - String clientName = registrationProfile.getClientName(); - String host = DCRProxyUtils.getKeyManagerHost(); - try { - // Setup the HTTPS settings to accept any certificate. - HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; - - SchemeRegistry registry = new SchemeRegistry(); - SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); - socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); - registry.register(new Scheme(Constants.RemoteServiceProperties. - DYNAMIC_CLIENT_SERVICE_PROTOCOL, socketFactory, getServerHTTPSPort())); - SingleClientConnManager mgr = new SingleClientConnManager(httpClient.getParams(), registry); - httpClient = new DefaultHttpClient(mgr, httpClient.getParams()); - - // Set verifier - HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); - - URI uri = new URIBuilder().setScheme(Constants.RemoteServiceProperties. - DYNAMIC_CLIENT_SERVICE_PROTOCOL).setHost(host).setPath( - Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT).build(); - Gson gson = new Gson(); - StringEntity entity = new StringEntity(gson.toJson(registrationProfile), CONTENT_TYPE_APPLICATION_JSON, - CHARSET_UTF_8); - HttpPost httpPost = new HttpPost(uri); - httpPost.setEntity(entity); - return httpClient.execute(httpPost); - } catch (URISyntaxException e) { - throw new DynamicClientRegistrationException("Exception occurred while constructing the URI for invoking " + - "DCR endpoint for registering service-provider for web-app : " - + clientName, e); - } catch (UnsupportedEncodingException e) { - throw new DynamicClientRegistrationException("Exception occurred while constructing the payload for invoking " + - "DCR endpoint for registering service-provider for web-app : " - + clientName, e); - } catch (IOException e) { - throw new DynamicClientRegistrationException("Connection error occurred while invoking DCR endpoint for" + - " registering service-provider for web-app : " + clientName, e); - } - } - - public static CloseableHttpResponse deleteOAuthApplication(String user, String appName, String clientid) - throws DynamicClientRegistrationException { - DefaultHttpClient httpClient = new DefaultHttpClient(); - String host = DCRProxyUtils.getKeyManagerHost(); - try { - // Setup the HTTPS settings to accept any certificate. - HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; - - SchemeRegistry registry = new SchemeRegistry(); - SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); - socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); - registry.register(new Scheme(Constants.RemoteServiceProperties. - DYNAMIC_CLIENT_SERVICE_PROTOCOL, socketFactory, getServerHTTPSPort())); - SingleClientConnManager mgr = new SingleClientConnManager(httpClient.getParams(), registry); - httpClient = new DefaultHttpClient(mgr, httpClient.getParams()); - - // Set verifier - HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); - - URI uri = new URIBuilder().setScheme(Constants.RemoteServiceProperties. - DYNAMIC_CLIENT_SERVICE_PROTOCOL).setHost(host).setPath( - Constants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT) - .setParameter("applicationName", appName) - .setParameter("userId", user) - .setParameter("consumerKey", clientid).build(); - HttpDelete httpDelete = new HttpDelete(uri); - return httpClient.execute(httpDelete); - } catch (IOException e) { - throw new DynamicClientRegistrationException("Connection error occurred while constructing the payload for " + - "invoking DCR endpoint for unregistering the web-app : " + appName, e); - } catch (URISyntaxException e) { - throw new DynamicClientRegistrationException("Exception occurred while constructing the URI for invoking " + - "DCR endpoint for unregistering the web-app : " + appName, e); - } - } - - private static int getServerHTTPSPort() { - // HTTPS port - String mgtConsoleTransport = CarbonUtils.getManagementTransport(); - ConfigurationContextService configContextService = DCRProxyUtils.getConfigurationContextService(); - int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport); - int httpsProxyPort = - CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(), - mgtConsoleTransport); - if (httpsProxyPort > 0) { - port = httpsProxyPort; - } - return port; - } -} \ No newline at end of file diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/WEB-INF/cxf-servlet.xml index 3044b684e7..e057aebcd2 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web-proxy/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -37,7 +37,7 @@ - + diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/RegistrationService.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/RegistrationService.java index 3c42d87bf8..ee5fa0ce74 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/RegistrationService.java +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/RegistrationService.java @@ -27,8 +27,6 @@ import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) public interface RegistrationService { enum ErrorCode { @@ -52,6 +50,8 @@ public interface RegistrationService { * @return Status 200 if success including consumerKey and consumerSecret. */ @POST + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) Response register(RegistrationProfile profile); /** @@ -63,6 +63,8 @@ public interface RegistrationService { * @return Status 200 if success. */ @DELETE + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) Response unregister(@QueryParam("applicationName") String applicationName, @QueryParam("userId") String userId, @QueryParam("consumerKey") String consumerKey); diff --git a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/impl/RegistrationServiceImpl.java b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/impl/RegistrationServiceImpl.java index 028b6df1f6..59539b7279 100644 --- a/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/impl/RegistrationServiceImpl.java +++ b/components/identity-extensions/dynamic-client-registration/dynamic-client-web/src/main/java/org/wso2/carbon/dynamic/client/web/impl/RegistrationServiceImpl.java @@ -37,8 +37,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.QueryParam; -@Produces(MediaType.APPLICATION_JSON) -@Consumes(MediaType.APPLICATION_JSON) public class RegistrationServiceImpl implements RegistrationService { private static final Log log = LogFactory.getLog(RegistrationServiceImpl.class); diff --git a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/RemoteDCRClient.java b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/RemoteDCRClient.java index f8e97ed5c0..9d5926db77 100644 --- a/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/RemoteDCRClient.java +++ b/components/identity-extensions/dynamic-client-registration/org.wso2.carbon.dynamic.client.web.app.registration/src/main/java/org/wso2/carbon/dynamic/client/web/app/registration/util/RemoteDCRClient.java @@ -60,26 +60,17 @@ public class RemoteDCRClient { public static OAuthApplicationInfo createOAuthApplication(RegistrationProfile registrationProfile, String host) throws DynamicClientRegistrationException { - DefaultHttpClient httpClient = new DefaultHttpClient(); + if (log.isDebugEnabled()) { + log.debug("Invoking DCR service to create OAuth application for web app : " + registrationProfile. + getClientName()); + } + DefaultHttpClient httpClient = getHTTPSClient(); String clientName = registrationProfile.getClientName(); try { - // Setup the HTTPS settings to accept any certificate. - HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; - - SchemeRegistry registry = new SchemeRegistry(); - SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); - socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); - registry.register(new Scheme(DynamicClientWebAppRegistrationConstants.RemoteServiceProperties. - DYNAMIC_CLIENT_SERVICE_PROTOCOL, socketFactory, getServerHTTPSPort())); - SingleClientConnManager mgr = new SingleClientConnManager(httpClient.getParams(), registry); - httpClient = new DefaultHttpClient(mgr, httpClient.getParams()); - - // Set verifier - HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); - URI uri = new URIBuilder().setScheme(DynamicClientWebAppRegistrationConstants.RemoteServiceProperties. DYNAMIC_CLIENT_SERVICE_PROTOCOL).setHost(host).setPath( - DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT).build(); + DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT) + .build(); Gson gson = new Gson(); StringEntity entity = new StringEntity(gson.toJson(registrationProfile), DynamicClientWebAppRegistrationConstants.ContentTypes.CONTENT_TYPE_APPLICATION_JSON, @@ -88,11 +79,12 @@ public class RemoteDCRClient { httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); - HttpEntity responseData = response.getEntity(); + HttpEntity responseData = response.getEntity(); String responseString = EntityUtils.toString(responseData, DynamicClientWebAppRegistrationConstants. CharSets.CHARSET_UTF8); if (status != 201) { - throw new DynamicClientRegistrationException("Backend server error occurred while invoking DCR endpoint for " + + throw new DynamicClientRegistrationException( + "Backend server error occurred while invoking DCR endpoint for " + "registering service-provider for web-app : " + clientName); } return getOAuthApplicationInfo(gson.fromJson(responseString, JsonElement.class)); @@ -101,39 +93,32 @@ public class RemoteDCRClient { "DCR endpoint for registering service-provider for web-app : " + clientName, e); } catch (UnsupportedEncodingException e) { - throw new DynamicClientRegistrationException("Exception occurred while constructing the payload for invoking " + - "DCR endpoint for registering service-provider for web-app : " - + clientName, e); + throw new DynamicClientRegistrationException( + "Exception occurred while constructing the payload for invoking " + + "DCR endpoint for registering service-provider for web-app : " + + clientName, e); } catch (IOException e) { throw new DynamicClientRegistrationException("Connection error occurred while invoking DCR endpoint for" + - " registering service-provider for web-app : " + clientName, e); + " registering service-provider for web-app : " + clientName, + e); + } finally { + httpClient.close(); } } public static boolean deleteOAuthApplication(String user, String appName, String clientid, String host) throws DynamicClientRegistrationException { - DefaultHttpClient httpClient = new DefaultHttpClient(); + if (log.isDebugEnabled()) { + log.debug("Invoking DCR service to remove OAuth application created for web app : " + appName); + } + DefaultHttpClient httpClient = getHTTPSClient(); try { - // Setup the HTTPS settings to accept any certificate. - HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; - - SchemeRegistry registry = new SchemeRegistry(); - SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); - socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); - registry.register(new Scheme(DynamicClientWebAppRegistrationConstants.RemoteServiceProperties. - DYNAMIC_CLIENT_SERVICE_PROTOCOL, socketFactory, getServerHTTPSPort())); - SingleClientConnManager mgr = new SingleClientConnManager(httpClient.getParams(), registry); - httpClient = new DefaultHttpClient(mgr, httpClient.getParams()); - - // Set verifier - HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); - - URI uri = new URIBuilder().setScheme(DynamicClientWebAppRegistrationConstants.RemoteServiceProperties. - DYNAMIC_CLIENT_SERVICE_PROTOCOL).setHost(host).setPath( - DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT) - .setParameter("applicationName", appName) - .setParameter("userId", user) - .setParameter("consumerKey", clientid).build(); + URI uri = new URIBuilder().setScheme(DynamicClientWebAppRegistrationConstants.RemoteServiceProperties. + DYNAMIC_CLIENT_SERVICE_PROTOCOL).setHost(host).setPath( + DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_ENDPOINT) + .setParameter("applicationName", appName) + .setParameter("userId", user) + .setParameter("consumerKey", clientid).build(); HttpDelete httpDelete = new HttpDelete(uri); HttpResponse response = httpClient.execute(httpDelete); int status = response.getStatusLine().getStatusCode(); @@ -141,11 +126,14 @@ public class RemoteDCRClient { return true; } } catch (IOException e) { - throw new DynamicClientRegistrationException("Connection error occurred while constructing the payload for " + - "invoking DCR endpoint for unregistering the web-app : " + appName, e); + throw new DynamicClientRegistrationException( + "Connection error occurred while constructing the payload for " + + "invoking DCR endpoint for unregistering the web-app : " + appName, e); } catch (URISyntaxException e) { throw new DynamicClientRegistrationException("Exception occurred while constructing the URI for invoking " + "DCR endpoint for unregistering the web-app : " + appName, e); + } finally { + httpClient.close(); } return false; } @@ -162,7 +150,7 @@ public class RemoteDCRClient { if (httpsProxyPort > 0) { port = httpsProxyPort; } - return port; + return port; } private static OAuthApplicationInfo getOAuthApplicationInfo(JsonElement jsonData) { @@ -182,4 +170,22 @@ public class RemoteDCRClient { } return oAuthApplicationInfo; } + + private static DefaultHttpClient getHTTPSClient() { + DefaultHttpClient httpClient = new DefaultHttpClient(); + // Setup the HTTPS settings to accept any certificate. + HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; + + SchemeRegistry registry = new SchemeRegistry(); + SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); + socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); + registry.register(new Scheme(DynamicClientWebAppRegistrationConstants.RemoteServiceProperties. + DYNAMIC_CLIENT_SERVICE_PROTOCOL, socketFactory, getServerHTTPSPort())); + SingleClientConnManager mgr = new SingleClientConnManager(httpClient.getParams(), registry); + httpClient = new DefaultHttpClient(mgr, httpClient.getParams()); + + // Set verifier + HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); + return httpClient; + } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index 1eb91150b8..54b284dcb2 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -106,6 +106,9 @@ public class MonitoringManagerImpl implements MonitoringManager { complianceData.setPolicyId(policy.getId()); } catch (SQLException e) { throw new PolicyComplianceException("Error occurred while opening a data source connection", e); + } catch (MonitoringDAOException e) { + throw new PolicyComplianceException("Unable to add the none compliance features to database for device " + + deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -124,6 +127,10 @@ public class MonitoringManagerImpl implements MonitoringManager { complianceFeatures); PolicyManagementDAOFactory.commitTransaction(); + } catch (MonitoringDAOException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyComplianceException("Unable to add the none compliance features to database for device " + + deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -143,6 +150,10 @@ public class MonitoringManagerImpl implements MonitoringManager { .getId()); monitoringDAO.deleteNoneComplianceData(complianceData.getId()); PolicyManagementDAOFactory.commitTransaction(); + } catch (MonitoringDAOException e) { + PolicyManagementDAOFactory.rollbackTransaction(); + throw new PolicyComplianceException("Unable to remove the none compliance features from database for device " + + deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); } finally { PolicyManagementDAOFactory.closeConnection(); } @@ -153,17 +164,11 @@ public class MonitoringManagerImpl implements MonitoringManager { } } } catch (DeviceManagementException e) { - PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyComplianceException("Unable tor retrieve device data from DB for " + deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); } catch (PolicyManagerDAOException | PolicyManagementException e) { - PolicyManagementDAOFactory.rollbackTransaction(); throw new PolicyComplianceException("Unable tor retrieve policy data from DB for device " + deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); - } catch (MonitoringDAOException e) { - PolicyManagementDAOFactory.rollbackTransaction(); - throw new PolicyComplianceException("Unable to add the none compliance features to database for device " + - deviceIdentifier.getId() + " - " + deviceIdentifier.getType(), e); } return complianceFeatures; } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index 497fa3b3e2..c82a57646b 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -99,13 +99,14 @@ public class OAuthAuthenticator implements WebappAuthenticator { if (oAuthValidationResponse.isValid()) { String username = oAuthValidationResponse.getUserName(); + String tenantDomain = oAuthValidationResponse.getTenantDomain(); //Remove the userstore domain from username /*if (username.contains("/")) { username = username.substring(username.indexOf('/') + 1); }*/ authenticationInfo.setUsername(username); - authenticationInfo.setTenantDomain(oAuthValidationResponse.getTenantDomain()); - authenticationInfo.setTenantId(Utils.getTenantIdOFUser(username)); + authenticationInfo.setTenantDomain(tenantDomain); + authenticationInfo.setTenantId(Utils.getTenantIdOFUser(username + "@" + tenantDomain)); if (oAuthValidationResponse.isValid()) { authenticationInfo.setStatus(Status.CONTINUE); } diff --git a/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/pom.xml b/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/pom.xml index 44ae1e0e36..3f55389989 100644 --- a/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/pom.xml +++ b/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/pom.xml @@ -105,15 +105,6 @@ ${basedir}/src/main/resources/ dynamic-client-web.war - - org.wso2.mdm - dynamic-client-web-proxy - ${carbon.device.mgt.version} - war - true - ${basedir}/src/main/resources/ - dynamic-client-web-proxy.war - diff --git a/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/src/main/resources/p2.inf b/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/src/main/resources/p2.inf index e25a76e1cf..0f2ca3fd11 100644 --- a/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/src/main/resources/p2.inf +++ b/features/dynamic-client-registration/org.wso2.carbon.dynamic.client.registration.server.feature/src/main/resources/p2.inf @@ -1,3 +1,2 @@ instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.dynamic.client.registration.server_${feature.version}/dynamic-client-web.war,target:${installFolder}/../../deployment/server/webapps/dynamic-client-web.war,overwrite:true);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.dynamic.client.registration.server_${feature.version}/dynamic-client-web-proxy.war,target:${installFolder}/../../deployment/server/webapps/dynamic-client-web-proxy.war,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.dynamic.client.registration.server_${feature.version}/dynamic-client-web.war,target:${installFolder}/../../deployment/server/webapps/dynamic-client-web.war,overwrite:true);\ \ No newline at end of file From d5f87f4dc136b15c1b04f496b728ff0733bdd06b Mon Sep 17 00:00:00 2001 From: Kasun Delgolla Date: Wed, 16 Dec 2015 14:38:32 +0530 Subject: [PATCH 3/6] Committing policy compliance monitoring issue --- .../carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java | 1 + 1 file changed, 1 insertion(+) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java index 54b284dcb2..f4c83d990f 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/MonitoringManagerImpl.java @@ -123,6 +123,7 @@ public class MonitoringManagerImpl implements MonitoringManager { if (log.isDebugEnabled()) { log.debug("Compliance status primary key " + complianceData.getId()); } + monitoringDAO.deleteNoneComplianceData(complianceData.getId()); monitoringDAO.addNonComplianceFeatures(complianceData.getId(), device.getId(), complianceFeatures); From d4b6ba5e364c6d23ff1091116a25e350869e4edc Mon Sep 17 00:00:00 2001 From: harshanl Date: Thu, 17 Dec 2015 10:32:06 +0530 Subject: [PATCH 4/6] Added pagination support for operation management apis. --- .../operation/mgt/OperationManager.java | 15 +- .../core/dao/DeviceManagementDAOFactory.java | 5 + .../core/dao/impl/AbstractDeviceDAOImpl.java | 26 ++++ .../{ => device}/GenericDeviceDAOImpl.java | 29 +--- .../{ => device}/OracleDeviceDAOImpl.java | 31 +--- .../{ => device}/PostgreSQLDeviceDAOImpl.java | 39 +---- .../{ => device}/SQLServerDeviceDAOImpl.java | 28 +--- .../operation/mgt/OperationManagerImpl.java | 62 ++++++++ .../core/operation/mgt/dao/OperationDAO.java | 9 +- .../dao/OperationManagementDAOFactory.java | 32 +++- .../mgt/dao/impl/CommandOperationDAOImpl.java | 2 +- .../mgt/dao/impl/ConfigOperationDAOImpl.java | 2 +- ...Impl.java => GenericOperationDAOImpl.java} | 141 ++++++++++++++++-- .../mgt/dao/impl/PolicyOperationDAOImpl.java | 2 +- .../mgt/dao/impl/ProfileOperationDAOImpl.java | 2 +- .../operation/OracleOperationDAOImpl.java | 127 ++++++++++++++++ .../operation/PostgreSQLOperationDAOImpl.java | 126 ++++++++++++++++ .../operation/SQLServerOperationDAOImpl.java | 127 ++++++++++++++++ .../DeviceManagementProviderServiceImpl.java | 6 + 19 files changed, 679 insertions(+), 132 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/{ => device}/GenericDeviceDAOImpl.java (87%) rename components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/{ => device}/OracleDeviceDAOImpl.java (85%) rename components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/{ => device}/PostgreSQLDeviceDAOImpl.java (84%) rename components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/{ => device}/SQLServerDeviceDAOImpl.java (86%) rename components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/{OperationDAOImpl.java => GenericOperationDAOImpl.java} (73%) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java index 3a0916b49f..710facd64f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/OperationManager.java @@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.common.operation.mgt; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.common.PaginationResult; import java.util.List; @@ -41,12 +42,24 @@ public interface OperationManager { /** * Method to retrieve the list of all operations to a device. * - * @param deviceId DeviceIdentifier of the device + * @param deviceId * @throws OperationManagementException If some unusual behaviour is observed while fetching the * operation list. */ List getOperations(DeviceIdentifier deviceId) throws OperationManagementException; + /** + * Method to retrieve all the operations applied to a device with pagination support. + * + * @param deviceId DeviceIdentifier of the device + * @param index Starting row number + * @param limit No of rows to fetch + * @return PaginationResult - Result including the required parameters necessary to do pagination. + * @throws OperationManagementException If some unusual behaviour is observed while fetching the + * operation list. + */ + PaginationResult getOperations(DeviceIdentifier deviceId, int index, int limit) throws OperationManagementException; + /** * Method to retrieve the list of available operations to a device. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java index e72efc1d79..29737f4894 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java @@ -26,6 +26,10 @@ import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.device.mgt.core.dao.impl.*; +import org.wso2.carbon.device.mgt.core.dao.impl.device.GenericDeviceDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.impl.device.OracleDeviceDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.impl.device.PostgreSQLDeviceDAOImpl; +import org.wso2.carbon.device.mgt.core.dao.impl.device.SQLServerDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import javax.sql.DataSource; @@ -96,6 +100,7 @@ public class DeviceManagementDAOFactory { case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL: return new SQLServerDeviceDAOImpl(); case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new PostgreSQLDeviceDAOImpl(); case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2: case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL: default: diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 14e1109cf5..92deb13643 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -26,6 +26,7 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; import java.sql.*; import java.util.ArrayList; @@ -652,4 +653,29 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { return devices; } + @Override + public List getDeviceTypes() + throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List deviceTypes; + try { + conn = this.getConnection(); + String sql = "SELECT t.ID, t.NAME FROM DM_DEVICE_TYPE t"; + stmt = conn.prepareStatement(sql); + rs = stmt.executeQuery(); + deviceTypes = new ArrayList<>(); + while (rs.next()) { + DeviceType deviceType = DeviceManagementDAOUtil.loadDeviceType(rs); + deviceTypes.add(deviceType); + } + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while listing device types.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + return deviceTypes; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java similarity index 87% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GenericDeviceDAOImpl.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 4df319c577..e6bf3b7843 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -16,13 +16,14 @@ * under the License. */ -package org.wso2.carbon.device.mgt.core.dao.impl; +package org.wso2.carbon.device.mgt.core.dao.impl.device; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dto.DeviceType; @@ -121,32 +122,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { return result; } - @Override - public List getDeviceTypes() - throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List deviceTypes; - try { - conn = this.getConnection(); - String sql = "SELECT t.ID, t.NAME " + - "FROM DM_DEVICE_TYPE t"; - stmt = conn.prepareStatement(sql); - rs = stmt.executeQuery(); - deviceTypes = new ArrayList<>(); - while (rs.next()) { - DeviceType deviceType = DeviceManagementDAOUtil.loadDeviceType(rs); - deviceTypes.add(deviceType); - } - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing device types.", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return deviceTypes; - } - private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java similarity index 85% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/OracleDeviceDAOImpl.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index 92d790fe60..d1a6c57001 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -16,12 +16,13 @@ * under the License. */ -package org.wso2.carbon.device.mgt.core.dao.impl; +package org.wso2.carbon.device.mgt.core.dao.impl.device; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dto.DeviceType; @@ -52,7 +53,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, " + "d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?,? ROW_NUMBER <= ?"; + "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setInt(2, tenantId); @@ -92,7 +93,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + - "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ?,?"; + "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setString(1, type); stmt.setInt(2, tenantId); @@ -117,30 +118,6 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { return result; } - @Override public List getDeviceTypes() throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List deviceTypes; - try { - conn = this.getConnection(); - String sql = "SELECT t.ID, t.NAME " + - "FROM DM_DEVICE_TYPE t"; - stmt = conn.prepareStatement(sql); - rs = stmt.executeQuery(); - deviceTypes = new ArrayList<>(); - while (rs.next()) { - DeviceType deviceType = DeviceManagementDAOUtil.loadDeviceType(rs); - deviceTypes.add(deviceType); - } - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing device types.", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return deviceTypes; - } - private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java similarity index 84% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/PostgreSQLDeviceDAOImpl.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index 26b0d34d9d..612a431fb1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -16,12 +16,13 @@ * under the License. */ -package org.wso2.carbon.device.mgt.core.dao.impl; +package org.wso2.carbon.device.mgt.core.dao.impl.device; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dto.DeviceType; @@ -52,12 +53,12 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID AS DEVICE_ID, " + "d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?) d1 " + - "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? LIMIT ?"; + "WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setInt(2, tenantId); - stmt.setInt(3, index); - stmt.setInt(4, limit); + stmt.setInt(3, limit); + stmt.setInt(4, index); rs = stmt.executeQuery(); devices = new ArrayList<>(); while (rs.next()) { @@ -92,13 +93,13 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + - "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? LIMIT ?"; + "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, type); stmt.setInt(2, tenantId); stmt.setInt(3, tenantId); - stmt.setInt(4, index); - stmt.setInt(5, limit); + stmt.setInt(4, limit); + stmt.setInt(5, index); rs = stmt.executeQuery(); devices = new ArrayList<>(); while (rs.next()) { @@ -117,30 +118,6 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { return result; } - @Override public List getDeviceTypes() throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List deviceTypes; - try { - conn = this.getConnection(); - String sql = "SELECT t.ID, t.NAME " + - "FROM DM_DEVICE_TYPE t"; - stmt = conn.prepareStatement(sql); - rs = stmt.executeQuery(); - deviceTypes = new ArrayList<>(); - while (rs.next()) { - DeviceType deviceType = DeviceManagementDAOUtil.loadDeviceType(rs); - deviceTypes.add(deviceType); - } - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing device types.", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return deviceTypes; - } - private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java similarity index 86% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/SQLServerDeviceDAOImpl.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index 21c3ef8848..8e47ac2024 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -16,12 +16,13 @@ * under the License. */ -package org.wso2.carbon.device.mgt.core.dao.impl; +package org.wso2.carbon.device.mgt.core.dao.impl.device; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dto.DeviceType; @@ -117,31 +118,6 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { return result; } - @Override - public List getDeviceTypes() throws DeviceManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List deviceTypes; - try { - conn = this.getConnection(); - String sql = "SELECT t.ID, t.NAME " + - "FROM DM_DEVICE_TYPE t"; - stmt = conn.prepareStatement(sql); - rs = stmt.executeQuery(); - deviceTypes = new ArrayList<>(); - while (rs.next()) { - DeviceType deviceType = DeviceManagementDAOUtil.loadDeviceType(rs); - deviceTypes.add(deviceType); - } - } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while listing device types.", e); - } finally { - DeviceManagementDAOUtil.cleanupResources(stmt, rs); - } - return deviceTypes; - } - private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index 71ea7adf72..7b65fc308c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; @@ -188,6 +189,67 @@ public class OperationManagerImpl implements OperationManager { return operations; } + @Override + public PaginationResult getOperations(DeviceIdentifier deviceId, int index, int limit) + throws OperationManagementException { + PaginationResult paginationResult = null; + int enrolmentId; + List operations = new ArrayList<>(); + try { + boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). + isUserAuthorized(deviceId); + if (isUserAuthorized) { + try { + try { + DeviceManagementDAOFactory.openConnection(); + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE, tenantId); + } finally { + DeviceManagementDAOFactory.closeConnection(); + } + + OperationManagementDAOFactory.openConnection(); + if (enrolmentId < 0) { + throw new OperationManagementException("Device not found for given device " + + "Identifier:" + deviceId.getId() + " and given type" + + deviceId.getType()); + } + List operationList = + operationDAO.getOperationsForDevice(enrolmentId, index, limit); + for (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation : operationList) { + Operation operation = OperationDAOUtil.convertOperation(dtoOperation); + operations.add(operation); + } + paginationResult = new PaginationResult(); + int count = operationDAO.getOperationCountForDevice(enrolmentId); + paginationResult.setData(operations); + paginationResult.setRecordsTotal(count); + paginationResult.setRecordsFiltered(operations.size()); + } catch (OperationManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving the list of " + + "operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); + } catch (DeviceManagementDAOException e) { + throw new OperationManagementException("Error occurred while retrieving metadata of '" + + deviceId.getType() + "' device carrying the identifier '" + + deviceId.getId() + "'"); + } catch (SQLException e) { + throw new OperationManagementException( + "Error occurred while opening a connection to the data source", e); + } finally { + OperationManagementDAOFactory.closeConnection(); + } + } else { + log.info("User : " + getUser() + " is not authorized to fetch operations on device : " + deviceId.getId()); + } + } catch (DeviceAccessAuthorizationException e) { + throw new OperationManagementException("Error occurred while authorizing access to the devices for user : " + + this.getUser(), e); + } + + return paginationResult; + } + @Override public List getPendingOperations(DeviceIdentifier deviceId) throws OperationManagementException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java index 9c0f998153..78097cf8dd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationDAO.java @@ -37,8 +37,15 @@ public interface OperationDAO { List getOperationsByDeviceAndStatus(int enrolmentId, Operation.Status status) throws OperationManagementDAOException; + List getOperationsByDeviceAndStatus(int enrolmentId, int index, int limit, Operation.Status status) + throws OperationManagementDAOException; + List getOperationsForDevice(int enrolmentId) throws OperationManagementDAOException; + int getOperationCountForDevice(int enrolmentId) throws OperationManagementDAOException; + + List getOperationsForDevice(int enrolmentId, int index, int limit) throws OperationManagementDAOException; + Operation getNextOperation(int enrolmentId) throws OperationManagementDAOException; void updateOperationStatus(int enrolmentId, int operationId,Operation.Status status) @@ -47,4 +54,4 @@ public interface OperationDAO { void addOperationResponse(int enrolmentId, int operationId, Object operationResponse) throws OperationManagementDAOException; -} +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java index e43843a474..4b723d92cf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java @@ -20,12 +20,16 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; import org.wso2.carbon.device.mgt.common.TransactionManagementException; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.*; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation.OracleOperationDAOImpl; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation.PostgreSQLOperationDAOImpl; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation.SQLServerOperationDAOImpl; import javax.sql.DataSource; import java.sql.Connection; @@ -37,6 +41,7 @@ public class OperationManagementDAOFactory { private static final Log log = LogFactory.getLog(OperationManagementDAOFactory.class); private static DataSource dataSource; + private static String databaseEngine; private static ThreadLocal currentConnection = new ThreadLocal(); public static OperationDAO getCommandOperationDAO() { @@ -60,15 +65,40 @@ public class OperationManagementDAOFactory { } public static OperationDAO getOperationDAO() { - return new OperationDAOImpl(); + if(databaseEngine != null) { + switch (databaseEngine) { + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE: + return new OracleOperationDAOImpl(); + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL: + return new SQLServerOperationDAOImpl(); + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new PostgreSQLOperationDAOImpl(); + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL: + default: + return new GenericOperationDAOImpl(); + } + } else { + return new GenericOperationDAOImpl(); + } } public static void init(DataSource dtSource) { dataSource = dtSource; + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } } public static void init(DataSourceConfig config) { dataSource = resolveDataSource(config); + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } } public static void beginTransaction() throws TransactionManagementException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java index 8fdd35591a..464597dc05 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/CommandOperationDAOImpl.java @@ -31,7 +31,7 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -public class CommandOperationDAOImpl extends OperationDAOImpl { +public class CommandOperationDAOImpl extends GenericOperationDAOImpl { @Override public int addOperation(Operation operation) throws OperationManagementDAOException { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java index f56bbff51b..e6994977ad 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ConfigOperationDAOImpl.java @@ -35,7 +35,7 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -public class ConfigOperationDAOImpl extends OperationDAOImpl { +public class ConfigOperationDAOImpl extends GenericOperationDAOImpl { private static final Log log = LogFactory.getLog(ConfigOperationDAOImpl.class); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java similarity index 73% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationDAOImpl.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index 90c0565c2e..5ae150d792 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/OperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -1,20 +1,19 @@ /* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl; @@ -34,9 +33,12 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -public class OperationDAOImpl implements OperationDAO { +/** + * This class holds the generic implementation of OperationDAO which can be used to support ANSI db syntax. + */ +public class GenericOperationDAOImpl implements OperationDAO { - private static final Log log = LogFactory.getLog(OperationDAOImpl.class); + private static final Log log = LogFactory.getLog(GenericOperationDAOImpl.class); public int addOperation(Operation operation) throws OperationManagementDAOException { PreparedStatement stmt = null; @@ -273,6 +275,51 @@ public class OperationDAOImpl implements OperationDAO { return operations; } + @Override + public List getOperationsByDeviceAndStatus(int enrolmentId, int index, int limit, + Operation.Status status) + throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Operation operation; + List operations = new ArrayList(); + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE " + + "FROM DM_OPERATION o " + + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + + "o.CREATED_TIMESTAMP ASC LIMIT ?,?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, enrolmentId); + stmt.setString(2, status.toString()); + stmt.setInt(3, index); + stmt.setInt(4, limit); + rs = stmt.executeQuery(); + + while (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(status); + operations.add(operation); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + + "available for the device'" + enrolmentId + "' with status '" + status.toString(), e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return operations; + } + @Override public List getOperationsForDevice(int enrolmentId) throws OperationManagementDAOException { PreparedStatement stmt = null; @@ -312,6 +359,72 @@ public class OperationDAOImpl implements OperationDAO { return operations; } + @Override + public List getOperationsForDevice(int enrolmentId, int index, int limit) + throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Operation operation; + List operations = new ArrayList(); + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + + "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP ASC LIMIT ?,?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, enrolmentId); + stmt.setInt(2, index); + stmt.setInt(3, limit); + rs = stmt.executeQuery(); + + while (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); + operations.add(operation); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + + "available for the device'" + enrolmentId + "' with status '", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return operations; + } + + @Override + public int getOperationCountForDevice(int enrolmentId) throws OperationManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + int operationCount = 0; + try { + conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT COUNT(ID) AS OPERATION_COUNT FROM DM_ENROLMENT_OP_MAPPING WHERE ENROLMENT_ID = ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, enrolmentId); + rs = stmt.executeQuery(); + if (rs.next()) { + operationCount = rs.getInt("OPERATION_COUNT"); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("Error occurred while getting the operations count for enrolment : " + + enrolmentId, e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return operationCount; + } + @Override public Operation getNextOperation(int enrolmentId) throws OperationManagementDAOException { PreparedStatement stmt = null; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java index 6b2a848809..957f206f3a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/PolicyOperationDAOImpl.java @@ -31,7 +31,7 @@ import java.sql.*; import java.util.ArrayList; import java.util.List; -public class PolicyOperationDAOImpl extends OperationDAOImpl { +public class PolicyOperationDAOImpl extends GenericOperationDAOImpl { private static final Log log = LogFactory.getLog(PolicyOperationDAOImpl.class); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ProfileOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ProfileOperationDAOImpl.java index a82e7c5e5f..4cc496c853 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ProfileOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/ProfileOperationDAOImpl.java @@ -31,7 +31,7 @@ import java.sql.*; import java.util.ArrayList; import java.util.List; -public class ProfileOperationDAOImpl extends OperationDAOImpl { +public class ProfileOperationDAOImpl extends GenericOperationDAOImpl { private static final Log log = LogFactory.getLog(ProfileOperationDAOImpl.class); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java new file mode 100644 index 0000000000..aefb1a10bf --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation; + +import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.GenericOperationDAOImpl; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the implementation of OperationDAO which can be used to support Oracle db syntax. + */ +public class OracleOperationDAOImpl extends GenericOperationDAOImpl { + + @Override + public List getOperationsForDevice(int enrolmentId, int index, int limit) + throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Operation operation; + List operations = new ArrayList(); + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + + "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP ASC " + + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, enrolmentId); + stmt.setInt(2, index); + stmt.setInt(3, limit); + rs = stmt.executeQuery(); + + while (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); + operations.add(operation); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + + "available for the device'" + enrolmentId + "' with status '", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return operations; + } + + @Override + public List getOperationsByDeviceAndStatus(int enrolmentId, int index, int limit, + Operation.Status status) + throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Operation operation; + List operations = new ArrayList(); + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE " + + "FROM DM_OPERATION o " + + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + + "o.CREATED_TIMESTAMP ASC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, enrolmentId); + stmt.setString(2, status.toString()); + stmt.setInt(3, index); + stmt.setInt(4, limit); + rs = stmt.executeQuery(); + + while (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(status); + operations.add(operation); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + + "available for the device'" + enrolmentId + "' with status '" + status.toString(), e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return operations; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java new file mode 100644 index 0000000000..8f4ee5512f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation; + +import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.GenericOperationDAOImpl; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the implementation of OperationDAO which can be used to support PostgreSQL db syntax. + */ +public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { + + @Override + public List getOperationsForDevice(int enrolmentId, int index, int limit) + throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Operation operation; + List operations = new ArrayList(); + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + + "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP ASC LIMIT ? OFFSET ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, enrolmentId); + stmt.setInt(2, limit); + stmt.setInt(3, index); + rs = stmt.executeQuery(); + + while (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); + operations.add(operation); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + + "available for the device'" + enrolmentId + "' with status '", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return operations; + } + + @Override + public List getOperationsByDeviceAndStatus(int enrolmentId, int index, int limit, + Operation.Status status) + throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Operation operation; + List operations = new ArrayList(); + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE " + + "FROM DM_OPERATION o " + + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + + "o.CREATED_TIMESTAMP ASC LIMIT ? OFFSET ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, enrolmentId); + stmt.setString(2, status.toString()); + stmt.setInt(3, limit); + stmt.setInt(4, index); + rs = stmt.executeQuery(); + + while (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(status); + operations.add(operation); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + + "available for the device'" + enrolmentId + "' with status '" + status.toString(), e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return operations; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java new file mode 100644 index 0000000000..09d5626bab --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation; + +import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.GenericOperationDAOImpl; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the implementation of OperationDAO which can be used to support SQLServer db syntax. + */ +public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { + + @Override + public List getOperationsForDevice(int enrolmentId, int index, int limit) + throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Operation operation; + List operations = new ArrayList(); + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + + "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP ASC " + + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, enrolmentId); + stmt.setInt(2, index); + stmt.setInt(3, limit); + rs = stmt.executeQuery(); + + while (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(Operation.Status.valueOf(rs.getString("STATUS"))); + operations.add(operation); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + + "available for the device'" + enrolmentId + "' with status '", e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return operations; + } + + @Override + public List getOperationsByDeviceAndStatus(int enrolmentId, int index, int limit, + Operation.Status status) + throws OperationManagementDAOException { + PreparedStatement stmt = null; + ResultSet rs = null; + Operation operation; + List operations = new ArrayList(); + try { + Connection conn = OperationManagementDAOFactory.getConnection(); + String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE " + + "FROM DM_OPERATION o " + + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + + "o.CREATED_TIMESTAMP ASC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, enrolmentId); + stmt.setString(2, status.toString()); + stmt.setInt(3, index); + stmt.setInt(4, limit); + rs = stmt.executeQuery(); + + while (rs.next()) { + operation = new Operation(); + operation.setId(rs.getInt("ID")); + operation.setType(Operation.Type.valueOf(rs.getString("TYPE"))); + operation.setCreatedTimeStamp(rs.getTimestamp("CREATED_TIMESTAMP").toString()); + if (rs.getTimestamp("RECEIVED_TIMESTAMP") == null) { + operation.setReceivedTimeStamp(""); + } else { + operation.setReceivedTimeStamp(rs.getTimestamp("RECEIVED_TIMESTAMP").toString()); + } + operation.setCode(rs.getString("OPERATION_CODE")); + operation.setStatus(status); + operations.add(operation); + } + } catch (SQLException e) { + throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + + "available for the device'" + enrolmentId + "' with status '" + status.toString(), e); + } finally { + OperationManagementDAOUtil.cleanupResources(stmt, rs); + } + return operations; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 649d024646..c1bc8cfa94 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -861,6 +861,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv return DeviceManagementDataHolder.getInstance().getOperationManager().getOperations(deviceId); } + @Override + public PaginationResult getOperations(DeviceIdentifier deviceId, int index, int limit) + throws OperationManagementException { + return DeviceManagementDataHolder.getInstance().getOperationManager().getOperations(deviceId, index, limit); + } + @Override public List getPendingOperations(DeviceIdentifier deviceId) throws OperationManagementException { From 91ece82eca0578211ece42e56eac070e6da68e85 Mon Sep 17 00:00:00 2001 From: harshanl Date: Thu, 17 Dec 2015 12:52:42 +0530 Subject: [PATCH 5/6] Updated operation DAO to sort data in DESC order of timestamp. --- .../mgt/core/operation/mgt/OperationManagerImpl.java | 2 +- .../operation/mgt/dao/impl/GenericOperationDAOImpl.java | 8 ++++---- .../mgt/dao/impl/operation/OracleOperationDAOImpl.java | 5 ++--- .../dao/impl/operation/PostgreSQLOperationDAOImpl.java | 5 ++--- .../mgt/dao/impl/operation/SQLServerOperationDAOImpl.java | 4 ++-- 5 files changed, 11 insertions(+), 13 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index 7b65fc308c..e0018eaafe 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -224,7 +224,7 @@ public class OperationManagerImpl implements OperationManager { int count = operationDAO.getOperationCountForDevice(enrolmentId); paginationResult.setData(operations); paginationResult.setRecordsTotal(count); - paginationResult.setRecordsFiltered(operations.size()); + paginationResult.setRecordsFiltered(count); } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while retrieving the list of " + "operations assigned for '" + deviceId.getType() + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index 5ae150d792..8864026826 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -246,7 +246,7 @@ public class GenericOperationDAOImpl implements OperationDAO { String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE " + "FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + - "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP ASC"; + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); stmt.setString(2, status.toString()); @@ -289,7 +289,7 @@ public class GenericOperationDAOImpl implements OperationDAO { "FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + - "o.CREATED_TIMESTAMP ASC LIMIT ?,?"; + "o.CREATED_TIMESTAMP DESC LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); stmt.setString(2, status.toString()); @@ -331,7 +331,7 @@ public class GenericOperationDAOImpl implements OperationDAO { String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + - "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP ASC"; + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); rs = stmt.executeQuery(); @@ -371,7 +371,7 @@ public class GenericOperationDAOImpl implements OperationDAO { String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + - "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP ASC LIMIT ?,?"; + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); stmt.setInt(2, index); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java index aefb1a10bf..eb16c2feda 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/OracleOperationDAOImpl.java @@ -18,7 +18,6 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation; -import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; @@ -49,7 +48,7 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + - "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP ASC " + + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC " + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); @@ -94,7 +93,7 @@ public class OracleOperationDAOImpl extends GenericOperationDAOImpl { "FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + - "o.CREATED_TIMESTAMP ASC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + "o.CREATED_TIMESTAMP DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); stmt.setString(2, status.toString()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java index 8f4ee5512f..192ee388b8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java @@ -18,7 +18,6 @@ package org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation; -import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; @@ -49,7 +48,7 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + - "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP ASC LIMIT ? OFFSET ?"; + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); stmt.setInt(2, limit); @@ -93,7 +92,7 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { "FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + - "o.CREATED_TIMESTAMP ASC LIMIT ? OFFSET ?"; + "o.CREATED_TIMESTAMP DESC LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); stmt.setString(2, status.toString()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java index 09d5626bab..5849e8b0a1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/SQLServerOperationDAOImpl.java @@ -49,7 +49,7 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + - "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP ASC " + + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC " + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); @@ -94,7 +94,7 @@ public class SQLServerOperationDAOImpl extends GenericOperationDAOImpl { "FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + - "o.CREATED_TIMESTAMP ASC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + "o.CREATED_TIMESTAMP DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, enrolmentId); stmt.setString(2, status.toString()); From eb680da5726e2791f92be3a00c9c0cecf8b35f0b Mon Sep 17 00:00:00 2001 From: Dileesha Rajapakse Date: Thu, 17 Dec 2015 14:57:28 +0530 Subject: [PATCH 6/6] Fixed EMM-1103 --- .../mgt/core/dao/impl/ApplicationDAOImpl.java | 54 +++++++++++++++++-- 1 file changed, 49 insertions(+), 5 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java index b2f79dbbd6..290ddacf1f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java @@ -26,9 +26,7 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.ObjectInputStream; +import java.io.*; import java.sql.*; import java.util.ArrayList; import java.util.List; @@ -43,6 +41,8 @@ public class ApplicationDAOImpl implements ApplicationDAO { Connection conn; PreparedStatement stmt = null; ResultSet rs = null; + ByteArrayOutputStream bao = null; + ObjectOutputStream oos = null; int applicationId = -1; try { conn = this.getConnection(); @@ -58,7 +58,12 @@ public class ApplicationDAOImpl implements ApplicationDAO { stmt.setString(6, application.getLocationUrl()); stmt.setString(7, application.getImageUrl()); stmt.setInt(8, tenantId); - stmt.setObject(9, application.getAppProperties()); + + bao = new ByteArrayOutputStream(); + oos = new ObjectOutputStream(bao); + oos.writeObject(application.getAppProperties()); + stmt.setBytes(9, bao.toByteArray()); + stmt.setString(10, application.getApplicationIdentifier()); stmt.execute(); @@ -70,7 +75,23 @@ public class ApplicationDAOImpl implements ApplicationDAO { } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while adding application '" + application.getName() + "'", e); + } catch (IOException e) { + throw new DeviceManagementDAOException("Error occurred while serializing application properties object", e); } finally { + if (bao != null) { + try { + bao.close(); + } catch (IOException e) { + log.warn("Error occurred while closing ByteArrayOutputStream", e); + } + } + if (oos != null) { + try { + oos.close(); + } catch (IOException e) { + log.warn("Error occurred while closing ObjectOutputStream", e); + } + } DeviceManagementDAOUtil.cleanupResources(stmt, rs); } } @@ -81,6 +102,8 @@ public class ApplicationDAOImpl implements ApplicationDAO { Connection conn; PreparedStatement stmt = null; ResultSet rs; + ByteArrayOutputStream bao = null; + ObjectOutputStream oos = null; List applicationIds = new ArrayList<>(); try { conn = this.getConnection(); @@ -99,7 +122,12 @@ public class ApplicationDAOImpl implements ApplicationDAO { stmt.setString(6, application.getLocationUrl()); stmt.setString(7, application.getImageUrl()); stmt.setInt(8, tenantId); - stmt.setObject(9, application.getAppProperties()); + + bao = new ByteArrayOutputStream(); + oos = new ObjectOutputStream(bao); + oos.writeObject(application.getAppProperties()); + stmt.setBytes(9, bao.toByteArray()); + stmt.setString(10, application.getApplicationIdentifier()); stmt.executeUpdate(); @@ -111,7 +139,23 @@ public class ApplicationDAOImpl implements ApplicationDAO { return applicationIds; } catch (SQLException e) { throw new DeviceManagementDAOException("Error occurred while adding bulk application list", e); + } catch (IOException e) { + throw new DeviceManagementDAOException("Error occurred while serializing application properties object", e); } finally { + if (bao != null) { + try { + bao.close(); + } catch (IOException e) { + log.warn("Error occurred while closing ByteArrayOutputStream", e); + } + } + if (oos != null) { + try { + oos.close(); + } catch (IOException e) { + log.warn("Error occurred while closing ObjectOutputStream", e); + } + } DeviceManagementDAOUtil.cleanupResources(stmt, null); } }