From 2dc1c7341af8741f798e0ec69f3d28a0ce2da1eb Mon Sep 17 00:00:00 2001 From: prabathabey Date: Wed, 8 Jul 2015 21:28:51 +0530 Subject: [PATCH 1/6] Improving the current dynamic client authentication to be more spec compliant --- .../oauth/extension/ApplicationConstants.java | 59 +++++++------- .../extension/FaultMessageBodyWriter.java | 77 +++++++++++++++++++ .../oauth/extension/FaultResponse.java | 39 ++++++++++ .../oauth/extension/OAuthApplicationInfo.java | 20 +---- .../oauth/extension/RegistrationService.java | 16 ++++ .../impl/ConfigurationServiceImpl.java | 33 ++++++++ ...Impl.java => RegistrationServiceImpl.java} | 72 +++++++++-------- .../{ => profile}/RegistrationProfile.java | 2 +- .../{ => profile}/UnregistrationProfile.java | 2 +- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 4 +- 10 files changed, 238 insertions(+), 86 deletions(-) create mode 100644 components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/FaultMessageBodyWriter.java create mode 100644 components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/FaultResponse.java create mode 100644 components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/ConfigurationServiceImpl.java rename components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/{ClientRegistrationServiceImpl.java => RegistrationServiceImpl.java} (86%) rename components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/{ => profile}/RegistrationProfile.java (98%) rename components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/{ => profile}/UnregistrationProfile.java (95%) diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/ApplicationConstants.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/ApplicationConstants.java index f01ad38814..ad160b6ff3 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/ApplicationConstants.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/ApplicationConstants.java @@ -18,33 +18,38 @@ */ package org.wso2.carbon.identity.oauth.extension; -public class ApplicationConstants { +public final class ApplicationConstants { - public static final String OAUTH_CLIENT_ID = "client_id"; //this means consumer key - public static final String OAUTH_CLIENT_SECRET = "client_secret"; - public static final String OAUTH_REDIRECT_URIS = "redirect_uris"; - public static final String OAUTH_CALLBACK_URIS = "callback_url"; - public static final String OAUTH_CLIENT_NAME = "client_name"; - public static final String OAUTH_CLIENT_TYPE = "client_type"; - public static final String APP_KEY_TYPE = "key_type"; - public static final String APP_CALLBACK_URL = "callback_url"; - public static final String APP_HOME_PAGE = "homepage"; - public static final String OAUTH_CLIENT_CONTACT = "contact"; - public static final String APP_LOGOURI = "logouri"; - public static final String OAUTH_CLIENT_SCOPE = "scope"; - public static final String OAUTH_CLIENT_GRANT = "grant_types"; - public static final String OAUTH_CLIENT_RESPONSETYPE = "response_types"; - public static final String OAUTH_CLIENT_AUTHMETHOD = "token_endpoint_auth_method"; - public static final String OAUTH_CLIENT_REGISTRATION_CLIENT_URI = "registration_client_uri"; - public static final String OAUTH_CLIENT_REGISTRATION_ACCESSTOKEN = "registration_access_token"; - public static final String OAUTH_CLIENT_CONTACTS = "contacts"; - public static final String OAUTH_CLIENT_MANUAL = "MANUAL"; - public static final String OAUTH_CLIENT_PRODUCTION = "PRODUCTION"; - public static final String OAUTH_CLIENT_SANDBOX = "SANDBOX"; - public static final String OAUTH_CLIENT_NOACCESSTOKEN = "NO ACCESS TOKEN"; - public static final String OAUTH_CLIENT_JSONPARAMSTRING = "jsonParams"; - public static final String OAUTH_CLIENT_USERNAME = "username"; - public static final String OAUTH_CLIENT_APPLICATION = "application"; - public static final String VALIDITY_PERIOD = "validityPeriod"; + public static class ClientMetadata { + private ClientMetadata() { + throw new AssertionError(); + } + public static final String OAUTH_CLIENT_ID = "client_id"; //this means consumer key + public static final String OAUTH_CLIENT_SECRET = "client_secret"; + public static final String OAUTH_REDIRECT_URIS = "redirect_uris"; + public static final String OAUTH_CALLBACK_URIS = "callback_url"; + public static final String OAUTH_CLIENT_NAME = "client_name"; + public static final String OAUTH_CLIENT_TYPE = "client_type"; + public static final String APP_KEY_TYPE = "key_type"; + public static final String APP_CALLBACK_URL = "callback_url"; + public static final String APP_HOME_PAGE = "homepage"; + public static final String OAUTH_CLIENT_CONTACT = "contact"; + public static final String APP_LOGOURI = "logouri"; + public static final String OAUTH_CLIENT_SCOPE = "scope"; + public static final String OAUTH_CLIENT_GRANT = "grant_types"; + public static final String OAUTH_CLIENT_RESPONSETYPE = "response_types"; + public static final String OAUTH_CLIENT_AUTHMETHOD = "token_endpoint_auth_method"; + public static final String OAUTH_CLIENT_REGISTRATION_CLIENT_URI = "registration_client_uri"; + public static final String OAUTH_CLIENT_REGISTRATION_ACCESSTOKEN = "registration_access_token"; + public static final String OAUTH_CLIENT_CONTACTS = "contacts"; + public static final String OAUTH_CLIENT_MANUAL = "MANUAL"; + public static final String OAUTH_CLIENT_PRODUCTION = "PRODUCTION"; + public static final String OAUTH_CLIENT_SANDBOX = "SANDBOX"; + public static final String OAUTH_CLIENT_NOACCESSTOKEN = "NO ACCESS TOKEN"; + public static final String OAUTH_CLIENT_JSONPARAMSTRING = "jsonParams"; + public static final String OAUTH_CLIENT_USERNAME = "username"; + public static final String OAUTH_CLIENT_APPLICATION = "application"; + public static final String VALIDITY_PERIOD = "validityPeriod"; + } } diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/FaultMessageBodyWriter.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/FaultMessageBodyWriter.java new file mode 100644 index 0000000000..6311b4c80d --- /dev/null +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/FaultMessageBodyWriter.java @@ -0,0 +1,77 @@ +/* + * 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.identity.oauth.extension; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; + +import javax.ws.rs.Produces; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.ext.MessageBodyWriter; +import javax.ws.rs.ext.Provider; +import java.io.IOException; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; + +@Provider +@Produces(MediaType.APPLICATION_JSON) +public class FaultMessageBodyWriter implements MessageBodyWriter { + + private static final String UTF_8 = "UTF-8"; + + @Override + public boolean isWriteable(Class aClass, Type type, Annotation[] annotations, MediaType mediaType) { + return (FaultResponse.class == type); + } + + @Override + public long getSize(FaultResponse faultResponse, Class aClass, Type type, Annotation[] annotations, + MediaType mediaType) { + return -1; + } + + @Override + public void writeTo(FaultResponse faultResponse, Class aClass, Type type, Annotation[] annotations, + MediaType mediaType, MultivaluedMap stringObjectMultivaluedMap, + OutputStream outputStream) throws IOException, WebApplicationException { + OutputStreamWriter writer = null; + try { + writer = new OutputStreamWriter(outputStream, UTF_8); + JsonObject response = new JsonObject(); + response.addProperty("error", faultResponse.getCode().getValue()); + response.addProperty("error_description", faultResponse.getDescription()); + getGson().toJson(response, type, writer); + } finally { + if (writer != null) { + writer.close(); + } + } + } + + private Gson getGson() { + GsonBuilder gsonBuilder = new GsonBuilder(); + return gsonBuilder.create(); + } + +} diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/FaultResponse.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/FaultResponse.java new file mode 100644 index 0000000000..5e71a41237 --- /dev/null +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/FaultResponse.java @@ -0,0 +1,39 @@ +/* + * 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.identity.oauth.extension; + +public class FaultResponse { + + private RegistrationService.ErrorCode code; + private String description; + + public FaultResponse(RegistrationService.ErrorCode code, String description) { + this.code = code; + this.description = description; + } + + public RegistrationService.ErrorCode getCode() { + return code; + } + + public String getDescription() { + return description; + } + +} diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/OAuthApplicationInfo.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/OAuthApplicationInfo.java index 74206f3def..3457b60d38 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/OAuthApplicationInfo.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/OAuthApplicationInfo.java @@ -27,24 +27,16 @@ import java.util.Map; public class OAuthApplicationInfo { - private String clientId; private String clientName; private String callBackURL; private String clientSecret; private Map parameters = new HashMap(); - /** - * get client Id (consumer id) - * @return clientId - */ public String getClientId() { return clientId; } - /** - * set client Id - * @param clientId - */ + public void setClientId(String clientId) { this.clientId = clientId; } @@ -57,18 +49,10 @@ public class OAuthApplicationInfo { this.clientSecret = clientSecret; } - /** - * Set client Name of OAuthApplication. - * @param clientName - */ public void setClientName(String clientName){ this.clientName = clientName; } - /** - * Set callback URL of OAuthapplication. - * @param callBackURL - */ public void setCallBackURL(String callBackURL){ this.callBackURL = callBackURL; } @@ -82,9 +66,7 @@ public class OAuthApplicationInfo { } public String getJsonString(){ - return JSONObject.toJSONString(parameters); - } public String getClientName(){ diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/RegistrationService.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/RegistrationService.java index a8660aec90..d9c3217d80 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/RegistrationService.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/RegistrationService.java @@ -18,6 +18,9 @@ */ package org.wso2.carbon.identity.oauth.extension; +import org.wso2.carbon.identity.oauth.extension.profile.RegistrationProfile; +import org.wso2.carbon.identity.oauth.extension.profile.UnregistrationProfile; + import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.POST; @@ -29,6 +32,19 @@ import javax.ws.rs.core.Response; @Consumes(MediaType.APPLICATION_JSON) public interface RegistrationService { + enum ErrorCode { + INVALID_URI("invalid_redirect_uri"), INVALID_CLIENT_METADATA("invalid_client_metadata"); + + private String value; + private ErrorCode(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + } + @POST Response register(RegistrationProfile profile); diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/ConfigurationServiceImpl.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/ConfigurationServiceImpl.java new file mode 100644 index 0000000000..87f36b6fbf --- /dev/null +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/ConfigurationServiceImpl.java @@ -0,0 +1,33 @@ +/* + * 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.identity.oauth.extension.impl; + +import org.wso2.carbon.identity.oauth.extension.ConfigurationService; + +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Response; + +public class ConfigurationServiceImpl implements ConfigurationService { + + @Override + public Response getProfile(@PathParam("client_id") String clientId) { + return null; + } + +} diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/ClientRegistrationServiceImpl.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/RegistrationServiceImpl.java similarity index 86% rename from components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/ClientRegistrationServiceImpl.java rename to components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/RegistrationServiceImpl.java index dd27729564..030c357bbe 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/ClientRegistrationServiceImpl.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/RegistrationServiceImpl.java @@ -35,11 +35,9 @@ import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.oauth.OAuthAdminService; import org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO; -import org.wso2.carbon.identity.oauth.extension.ApplicationConstants; -import org.wso2.carbon.identity.oauth.extension.OAuthApplicationInfo; -import org.wso2.carbon.identity.oauth.extension.RegistrationProfile; -import org.wso2.carbon.identity.oauth.extension.RegistrationService; -import org.wso2.carbon.identity.oauth.extension.UnregistrationProfile; +import org.wso2.carbon.identity.oauth.extension.*; +import org.wso2.carbon.identity.oauth.extension.profile.RegistrationProfile; +import org.wso2.carbon.identity.oauth.extension.profile.UnregistrationProfile; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; @@ -53,9 +51,9 @@ import java.util.Arrays; @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) -public class ClientRegistrationServiceImpl implements RegistrationService { +public class RegistrationServiceImpl implements RegistrationService { - private static final Log log = LogFactory.getLog(ClientRegistrationServiceImpl.class); + private static final Log log = LogFactory.getLog(RegistrationServiceImpl.class); @POST @Override @@ -71,7 +69,7 @@ public class ClientRegistrationServiceImpl implements RegistrationService { } catch (APIManagementException e) { String msg = "Error occurred while registering client '" + profile.getClientName() + "'"; log.error(msg, e); - return Response.serverError().entity(msg).build(); + return Response.serverError().entity(new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build(); } finally { PrivilegedCarbonContext.endTenantFlow(); } @@ -87,13 +85,12 @@ public class ClientRegistrationServiceImpl implements RegistrationService { this.unregisterApplication(userId, applicationName, consumerKey); return Response.status(Response.Status.ACCEPTED).build(); } catch (APIManagementException e) { - String msg = "Error occurred while unregistering client '" + applicationName + "'"; + String msg = "Error occurred while un-registering client '" + applicationName + "'"; log.error(msg, e); - return Response.serverError().entity(msg).build(); + return Response.serverError().entity(new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build(); } } - private OAuthApplicationInfo registerApplication(RegistrationProfile profile) throws APIManagementException { OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); @@ -131,16 +128,15 @@ public class ClientRegistrationServiceImpl implements RegistrationService { try { JSONObject jsonObject = new JSONObject(info.getJsonString()); - if (jsonObject.has(ApplicationConstants.OAUTH_REDIRECT_URIS)) { - oAuthApplicationInfo.addParameter(ApplicationConstants.OAUTH_REDIRECT_URIS, jsonObject.get(ApplicationConstants.OAUTH_REDIRECT_URIS)); + if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)) { + oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, + jsonObject.get(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)); } - if (jsonObject.has(ApplicationConstants.OAUTH_CLIENT_GRANT)) { - oAuthApplicationInfo.addParameter(ApplicationConstants. - OAUTH_CLIENT_GRANT, jsonObject.get(ApplicationConstants.OAUTH_CLIENT_GRANT)); + if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)) { + oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata. + OAUTH_CLIENT_GRANT, jsonObject.get(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)); } - - } catch (JSONException e) { throw new APIManagementException("Can not retrieve information of the created OAuth application", e); } @@ -167,7 +163,6 @@ public class ClientRegistrationServiceImpl implements RegistrationService { PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName); try { - // Append the username before Application name to make application name unique across two users. applicationName = userName + "_" + applicationName; @@ -180,7 +175,6 @@ public class ClientRegistrationServiceImpl implements RegistrationService { appMgtService.createApplication(serviceProvider); ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName); - if (createdServiceProvider == null) { throw new APIManagementException("Couldn't create Service Provider Application " + applicationName); } @@ -189,17 +183,23 @@ public class ClientRegistrationServiceImpl implements RegistrationService { OAuthAdminService oAuthAdminService = new OAuthAdminService(); OAuthConsumerAppDTO oAuthConsumerAppDTO = new OAuthConsumerAppDTO(); - oAuthConsumerAppDTO.setApplicationName(applicationName); oAuthConsumerAppDTO.setCallbackUrl(callbackUrl); oAuthConsumerAppDTO.setGrantTypes(grantType); - log.debug("Creating OAuth App " + applicationName); + if (log.isDebugEnabled()) { + log.debug("Creating OAuth App " + applicationName); + } + oAuthAdminService.registerOAuthApplicationData(oAuthConsumerAppDTO); - log.debug("Created OAuth App " + applicationName); + if (log.isDebugEnabled()) { + log.debug("Created OAuth App " + applicationName); + } + OAuthConsumerAppDTO createdApp = oAuthAdminService.getOAuthApplicationDataByAppName(oAuthConsumerAppDTO .getApplicationName()); - log.debug("Retrieved Details for OAuth App " + createdApp.getApplicationName()); - + if (log.isDebugEnabled()) { + log.debug("Retrieved Details for OAuth App " + createdApp.getApplicationName()); + } // Set the OAuthApp in InboundAuthenticationConfig InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig(); InboundAuthenticationRequestConfig[] inboundAuthenticationRequestConfigs = new @@ -225,20 +225,17 @@ public class ClientRegistrationServiceImpl implements RegistrationService { // Update the Service Provider app to add OAuthApp as an Inbound Authentication Config appMgtService.updateApplication(createdServiceProvider); - OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); oAuthApplicationInfo.setClientId(createdApp.getOauthConsumerKey()); oAuthApplicationInfo.setCallBackURL(createdApp.getCallbackUrl()); oAuthApplicationInfo.setClientSecret(createdApp.getOauthConsumerSecret()); oAuthApplicationInfo.setClientName(createdApp.getApplicationName()); - oAuthApplicationInfo.addParameter(ApplicationConstants. - OAUTH_REDIRECT_URIS, createdApp.getCallbackUrl()); - oAuthApplicationInfo.addParameter(ApplicationConstants. - OAUTH_CLIENT_GRANT, createdApp.getGrantTypes()); - + oAuthApplicationInfo.addParameter( + ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, createdApp.getCallbackUrl()); + oAuthApplicationInfo.addParameter( + ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, createdApp.getGrantTypes()); return oAuthApplicationInfo; - } catch (IdentityApplicationManagementException e) { APIUtil.handleException("Error occurred while creating ServiceProvider for app " + applicationName, e); } catch (Exception e) { @@ -250,9 +247,8 @@ public class ClientRegistrationServiceImpl implements RegistrationService { return null; } - public void unregisterApplication(String userId, String applicationName, String consumerKey) - throws APIManagementException { - + public void unregisterApplication(String userId, String applicationName, + String consumerKey) throws APIManagementException { String tenantDomain = MultitenantUtils.getTenantDomain(userId); String baseUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = MultitenantUtils.getTenantAwareUsername(userId); @@ -262,7 +258,8 @@ public class ClientRegistrationServiceImpl implements RegistrationService { PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName); if (userId == null || userId.isEmpty()) { - throw new APIManagementException("Error occurred while unregistering Application: userId cannot be null/empty"); + throw new APIManagementException("Error occurred while unregistering Application: userId cannot " + + "be null/empty"); } try { OAuthAdminService oAuthAdminService = new OAuthAdminService(); @@ -270,7 +267,7 @@ public class ClientRegistrationServiceImpl implements RegistrationService { if (oAuthConsumerAppDTO == null) { throw new APIManagementException("Couldn't retrieve OAuth Consumer Application associated with the " + - "given consumer key: " + consumerKey); + "given consumer key: " + consumerKey); } oAuthAdminService.removeOAuthApplicationData(consumerKey); @@ -291,4 +288,5 @@ public class ClientRegistrationServiceImpl implements RegistrationService { PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(baseUser); } } + } diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/RegistrationProfile.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/RegistrationProfile.java similarity index 98% rename from components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/RegistrationProfile.java rename to components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/RegistrationProfile.java index e1e819110f..2c1a42bae3 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/RegistrationProfile.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/RegistrationProfile.java @@ -16,7 +16,7 @@ * under the License. * */ -package org.wso2.carbon.identity.oauth.extension; +package org.wso2.carbon.identity.oauth.extension.profile; public class RegistrationProfile { diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/UnregistrationProfile.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/UnregistrationProfile.java similarity index 95% rename from components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/UnregistrationProfile.java rename to components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/UnregistrationProfile.java index ac3f4f317b..a7959a7ded 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/UnregistrationProfile.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/UnregistrationProfile.java @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.wso2.carbon.identity.oauth.extension; +package org.wso2.carbon.identity.oauth.extension.profile; /** * This bean class represents the data that are required to unregister diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/oauth-extensions/dynamic-client-manager/src/main/webapp/WEB-INF/cxf-servlet.xml index a38fa222e6..78ccf40375 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/oauth-extensions/dynamic-client-manager/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -33,10 +33,12 @@ + - + + From 85aec417e584cdfc761357f6e15af4f80ade62ff Mon Sep 17 00:00:00 2001 From: prabathabey Date: Wed, 8 Jul 2015 23:23:45 +0530 Subject: [PATCH 2/6] Setting target version of maven compiler plugin to 1.7 --- .../extension/FaultMessageBodyWriter.java | 8 +------- pom.xml | 20 +++++++++---------- 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/FaultMessageBodyWriter.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/FaultMessageBodyWriter.java index 6311b4c80d..ff43d4aad9 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/FaultMessageBodyWriter.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/FaultMessageBodyWriter.java @@ -55,17 +55,11 @@ public class FaultMessageBodyWriter implements MessageBodyWriter public void writeTo(FaultResponse faultResponse, Class aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap stringObjectMultivaluedMap, OutputStream outputStream) throws IOException, WebApplicationException { - OutputStreamWriter writer = null; - try { - writer = new OutputStreamWriter(outputStream, UTF_8); + try (OutputStreamWriter writer = new OutputStreamWriter(outputStream, UTF_8)) { JsonObject response = new JsonObject(); response.addProperty("error", faultResponse.getCode().getValue()); response.addProperty("error_description", faultResponse.getDescription()); getGson().toJson(response, type, writer); - } finally { - if (writer != null) { - writer.close(); - } } } diff --git a/pom.xml b/pom.xml index b4fc802f87..f31068a457 100644 --- a/pom.xml +++ b/pom.xml @@ -945,16 +945,16 @@ - - - - - - - - - - + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.1 + + UTF-8 + 1.7 + 1.7 + + org.apache.maven.plugins maven-release-plugin From 8073d46f58c8eede4d1960b026cc32b7b23b28cb Mon Sep 17 00:00:00 2001 From: prabathabey Date: Thu, 9 Jul 2015 15:37:27 +0530 Subject: [PATCH 3/6] Cleaning up Dynamic Client Registration implementation --- .../DynamicClientRegistrationUtil.java | 244 ++++++++++++++++++ .../impl/RegistrationServiceImpl.java | 205 +-------------- 2 files changed, 248 insertions(+), 201 deletions(-) create mode 100644 components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/DynamicClientRegistrationUtil.java diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/DynamicClientRegistrationUtil.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/DynamicClientRegistrationUtil.java new file mode 100644 index 0000000000..4322655725 --- /dev/null +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/DynamicClientRegistrationUtil.java @@ -0,0 +1,244 @@ +/* + * 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.identity.oauth.extension; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONException; +import org.json.JSONObject; +import org.wso2.carbon.apimgt.api.APIManagementException; +import org.wso2.carbon.apimgt.impl.utils.APIUtil; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; +import org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig; +import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig; +import org.wso2.carbon.identity.application.common.model.Property; +import org.wso2.carbon.identity.application.common.model.ServiceProvider; +import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; +import org.wso2.carbon.identity.base.IdentityException; +import org.wso2.carbon.identity.oauth.OAuthAdminService; +import org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO; +import org.wso2.carbon.identity.oauth.extension.profile.RegistrationProfile; +import org.wso2.carbon.utils.multitenancy.MultitenantUtils; + +import java.util.Arrays; + +public class DynamicClientRegistrationUtil { + + private static final Log log = LogFactory.getLog(DynamicClientRegistrationUtil.class); + + public static OAuthApplicationInfo registerApplication(RegistrationProfile profile) throws APIManagementException { + OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); + + //Subscriber's name should be passed as a parameter, since it's under the subscriber the OAuth App is created. + String userId = profile.getOwner(); + String applicationName = profile.getClientName(); + String grantType = profile.getGrantType(); + + if (log.isDebugEnabled()) { + log.debug("Trying to create OAuth application: '" + applicationName + "'"); + } + + String callBackURL = profile.getCallbackUrl(); + + String tokenScope = profile.getTokenScope(); + String tokenScopes[] = new String[1]; + tokenScopes[0] = tokenScope; + + oAuthApplicationInfo.addParameter("tokenScope", Arrays.toString(tokenScopes)); + OAuthApplicationInfo info; + try { + info = createOAuthApplication(userId, applicationName, callBackURL, grantType); + } catch (Exception e) { + throw new APIManagementException("Can not create OAuth application : " + applicationName, e); + } + + if (info == null || info.getJsonString() == null) { + throw new APIManagementException("OAuth app does not contain required data: '" + applicationName + "'"); + } + + oAuthApplicationInfo.setClientName(info.getClientName()); + oAuthApplicationInfo.setClientId(info.getClientId()); + oAuthApplicationInfo.setCallBackURL(info.getCallBackURL()); + oAuthApplicationInfo.setClientSecret(info.getClientSecret()); + + try { + JSONObject jsonObject = new JSONObject(info.getJsonString()); + if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)) { + oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, + jsonObject.get(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)); + } + + if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)) { + oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata. + OAUTH_CLIENT_GRANT, jsonObject.get(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)); + } + } catch (JSONException e) { + throw new APIManagementException("Can not retrieve information of the created OAuth application", e); + } + return oAuthApplicationInfo; + } + + public static OAuthApplicationInfo createOAuthApplication( + String userId, String applicationName, String callbackUrl, String grantType) + throws APIManagementException, IdentityException { + if (userId == null || userId.isEmpty()) { + return null; + } + + String tenantDomain = MultitenantUtils.getTenantDomain(userId); + String baseUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); + String userName = MultitenantUtils.getTenantAwareUsername(userId); + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); + + // Acting as the provided user. When creating Service Provider/OAuth App, + // username is fetched from CarbonContext + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName); + + try { + // Append the username before Application name to make application name unique across two users. + applicationName = userName + "_" + applicationName; + + // Create the Service Provider + ServiceProvider serviceProvider = new ServiceProvider(); + serviceProvider.setApplicationName(applicationName); + serviceProvider.setDescription("Service Provider for application " + applicationName); + + ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); + appMgtService.createApplication(serviceProvider); + + ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName); + if (createdServiceProvider == null) { + throw new APIManagementException("Couldn't create Service Provider Application " + applicationName); + } + + // Then Create OAuthApp + OAuthAdminService oAuthAdminService = new OAuthAdminService(); + + OAuthConsumerAppDTO oAuthConsumerAppDTO = new OAuthConsumerAppDTO(); + oAuthConsumerAppDTO.setApplicationName(applicationName); + oAuthConsumerAppDTO.setCallbackUrl(callbackUrl); + oAuthConsumerAppDTO.setGrantTypes(grantType); + if (log.isDebugEnabled()) { + log.debug("Creating OAuth App " + applicationName); + } + + oAuthAdminService.registerOAuthApplicationData(oAuthConsumerAppDTO); + if (log.isDebugEnabled()) { + log.debug("Created OAuth App " + applicationName); + } + + OAuthConsumerAppDTO createdApp = oAuthAdminService.getOAuthApplicationDataByAppName(oAuthConsumerAppDTO + .getApplicationName()); + if (log.isDebugEnabled()) { + log.debug("Retrieved Details for OAuth App " + createdApp.getApplicationName()); + } + // Set the OAuthApp in InboundAuthenticationConfig + InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig(); + InboundAuthenticationRequestConfig[] inboundAuthenticationRequestConfigs = new + InboundAuthenticationRequestConfig[1]; + InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new + InboundAuthenticationRequestConfig(); + + inboundAuthenticationRequestConfig.setInboundAuthKey(createdApp.getOauthConsumerKey()); + inboundAuthenticationRequestConfig.setInboundAuthType("oauth2"); + if (createdApp.getOauthConsumerSecret() != null && !createdApp. + getOauthConsumerSecret().isEmpty()) { + Property property = new Property(); + property.setName("oauthConsumerSecret"); + property.setValue(createdApp.getOauthConsumerSecret()); + Property[] properties = {property}; + inboundAuthenticationRequestConfig.setProperties(properties); + } + + inboundAuthenticationRequestConfigs[0] = inboundAuthenticationRequestConfig; + inboundAuthenticationConfig.setInboundAuthenticationRequestConfigs(inboundAuthenticationRequestConfigs); + createdServiceProvider.setInboundAuthenticationConfig(inboundAuthenticationConfig); + + // Update the Service Provider app to add OAuthApp as an Inbound Authentication Config + appMgtService.updateApplication(createdServiceProvider); + + OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); + oAuthApplicationInfo.setClientId(createdApp.getOauthConsumerKey()); + oAuthApplicationInfo.setCallBackURL(createdApp.getCallbackUrl()); + oAuthApplicationInfo.setClientSecret(createdApp.getOauthConsumerSecret()); + oAuthApplicationInfo.setClientName(createdApp.getApplicationName()); + + oAuthApplicationInfo.addParameter( + ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, createdApp.getCallbackUrl()); + oAuthApplicationInfo.addParameter( + ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, createdApp.getGrantTypes()); + return oAuthApplicationInfo; + } catch (IdentityApplicationManagementException e) { + APIUtil.handleException("Error occurred while creating ServiceProvider for app " + applicationName, e); + } catch (Exception e) { + APIUtil.handleException("Error occurred while creating OAuthApp " + applicationName, e); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(baseUser); + } + return null; + } + + public static void unregisterApplication(String userId, String applicationName, + String consumerKey) throws APIManagementException { + String tenantDomain = MultitenantUtils.getTenantDomain(userId); + String baseUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); + String userName = MultitenantUtils.getTenantAwareUsername(userId); + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName); + + if (userId == null || userId.isEmpty()) { + throw new APIManagementException("Error occurred while unregistering Application: userId cannot " + + "be null/empty"); + } + try { + OAuthAdminService oAuthAdminService = new OAuthAdminService(); + OAuthConsumerAppDTO oAuthConsumerAppDTO = oAuthAdminService.getOAuthApplicationData(consumerKey); + + if (oAuthConsumerAppDTO == null) { + throw new APIManagementException("Couldn't retrieve OAuth Consumer Application associated with the " + + "given consumer key: " + consumerKey); + } + oAuthAdminService.removeOAuthApplicationData(consumerKey); + + ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); + ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName); + + if (createdServiceProvider == null) { + throw new APIManagementException("Couldn't retrieve Service Provider Application " + applicationName); + } + appMgtService.deleteApplication(applicationName); + + } catch (IdentityApplicationManagementException e) { + APIUtil.handleException("Error occurred while removing ServiceProvider for app " + applicationName, e); + } catch (Exception e) { + APIUtil.handleException("Error occurred while removing OAuthApp " + applicationName, e); + } finally { + PrivilegedCarbonContext.endTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(baseUser); + } + } + +} diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/RegistrationServiceImpl.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/RegistrationServiceImpl.java index 030c357bbe..80b6fafd01 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/RegistrationServiceImpl.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/impl/RegistrationServiceImpl.java @@ -64,12 +64,13 @@ public class RegistrationServiceImpl implements RegistrationService { MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); - OAuthApplicationInfo info = this.registerApplication(profile); + OAuthApplicationInfo info = DynamicClientRegistrationUtil.registerApplication(profile); return Response.status(Response.Status.ACCEPTED).entity(info.toString()).build(); } catch (APIManagementException e) { String msg = "Error occurred while registering client '" + profile.getClientName() + "'"; log.error(msg, e); - return Response.serverError().entity(new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build(); + return Response.status(Response.Status.BAD_REQUEST).entity( + new FaultResponse(ErrorCode.INVALID_CLIENT_METADATA, msg)).build(); } finally { PrivilegedCarbonContext.endTenantFlow(); } @@ -82,7 +83,7 @@ public class RegistrationServiceImpl implements RegistrationService { String consumerKey = profile.getConsumerKey(); String userId = profile.getUserId(); try { - this.unregisterApplication(userId, applicationName, consumerKey); + DynamicClientRegistrationUtil.unregisterApplication(userId, applicationName, consumerKey); return Response.status(Response.Status.ACCEPTED).build(); } catch (APIManagementException e) { String msg = "Error occurred while un-registering client '" + applicationName + "'"; @@ -91,202 +92,4 @@ public class RegistrationServiceImpl implements RegistrationService { } } - private OAuthApplicationInfo registerApplication(RegistrationProfile profile) throws APIManagementException { - OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); - - //Subscriber's name should be passed as a parameter, since it's under the subscriber the OAuth App is created. - String userId = profile.getOwner(); - String applicationName = profile.getClientName(); - String grantType = profile.getGrantType(); - - if (log.isDebugEnabled()) { - log.debug("Trying to create OAuth application: '" + applicationName + "'"); - } - - String callBackURL = profile.getCallbackUrl(); - - String tokenScope = profile.getTokenScope(); - String tokenScopes[] = new String[1]; - tokenScopes[0] = tokenScope; - - oAuthApplicationInfo.addParameter("tokenScope", Arrays.toString(tokenScopes)); - OAuthApplicationInfo info; - try { - info = this.createOAuthApplication(userId, applicationName, callBackURL, grantType); - } catch (Exception e) { - throw new APIManagementException("Can not create OAuth application : " + applicationName, e); - } - - if (info == null || info.getJsonString() == null) { - throw new APIManagementException("OAuth app does not contain required data: '" + applicationName + "'"); - } - - oAuthApplicationInfo.setClientName(info.getClientName()); - oAuthApplicationInfo.setClientId(info.getClientId()); - oAuthApplicationInfo.setCallBackURL(info.getCallBackURL()); - oAuthApplicationInfo.setClientSecret(info.getClientSecret()); - - try { - JSONObject jsonObject = new JSONObject(info.getJsonString()); - if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)) { - oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, - jsonObject.get(ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS)); - } - - if (jsonObject.has(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)) { - oAuthApplicationInfo.addParameter(ApplicationConstants.ClientMetadata. - OAUTH_CLIENT_GRANT, jsonObject.get(ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT)); - } - } catch (JSONException e) { - throw new APIManagementException("Can not retrieve information of the created OAuth application", e); - } - return oAuthApplicationInfo; - } - - public OAuthApplicationInfo createOAuthApplication( - String userId, String applicationName, String callbackUrl, String grantType) - throws APIManagementException, IdentityException { - - if (userId == null || userId.isEmpty()) { - return null; - } - - String tenantDomain = MultitenantUtils.getTenantDomain(userId); - String baseUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); - String userName = MultitenantUtils.getTenantAwareUsername(userId); - - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - - // Acting as the provided user. When creating Service Provider/OAuth App, - // username is fetched from CarbonContext - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName); - - try { - // Append the username before Application name to make application name unique across two users. - applicationName = userName + "_" + applicationName; - - // Create the Service Provider - ServiceProvider serviceProvider = new ServiceProvider(); - serviceProvider.setApplicationName(applicationName); - serviceProvider.setDescription("Service Provider for application " + applicationName); - - ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); - appMgtService.createApplication(serviceProvider); - - ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName); - if (createdServiceProvider == null) { - throw new APIManagementException("Couldn't create Service Provider Application " + applicationName); - } - - // Then Create OAuthApp - OAuthAdminService oAuthAdminService = new OAuthAdminService(); - - OAuthConsumerAppDTO oAuthConsumerAppDTO = new OAuthConsumerAppDTO(); - oAuthConsumerAppDTO.setApplicationName(applicationName); - oAuthConsumerAppDTO.setCallbackUrl(callbackUrl); - oAuthConsumerAppDTO.setGrantTypes(grantType); - if (log.isDebugEnabled()) { - log.debug("Creating OAuth App " + applicationName); - } - - oAuthAdminService.registerOAuthApplicationData(oAuthConsumerAppDTO); - if (log.isDebugEnabled()) { - log.debug("Created OAuth App " + applicationName); - } - - OAuthConsumerAppDTO createdApp = oAuthAdminService.getOAuthApplicationDataByAppName(oAuthConsumerAppDTO - .getApplicationName()); - if (log.isDebugEnabled()) { - log.debug("Retrieved Details for OAuth App " + createdApp.getApplicationName()); - } - // Set the OAuthApp in InboundAuthenticationConfig - InboundAuthenticationConfig inboundAuthenticationConfig = new InboundAuthenticationConfig(); - InboundAuthenticationRequestConfig[] inboundAuthenticationRequestConfigs = new - InboundAuthenticationRequestConfig[1]; - InboundAuthenticationRequestConfig inboundAuthenticationRequestConfig = new - InboundAuthenticationRequestConfig(); - - inboundAuthenticationRequestConfig.setInboundAuthKey(createdApp.getOauthConsumerKey()); - inboundAuthenticationRequestConfig.setInboundAuthType("oauth2"); - if (createdApp.getOauthConsumerSecret() != null && !createdApp. - getOauthConsumerSecret().isEmpty()) { - Property property = new Property(); - property.setName("oauthConsumerSecret"); - property.setValue(createdApp.getOauthConsumerSecret()); - Property[] properties = {property}; - inboundAuthenticationRequestConfig.setProperties(properties); - } - - inboundAuthenticationRequestConfigs[0] = inboundAuthenticationRequestConfig; - inboundAuthenticationConfig.setInboundAuthenticationRequestConfigs(inboundAuthenticationRequestConfigs); - createdServiceProvider.setInboundAuthenticationConfig(inboundAuthenticationConfig); - - // Update the Service Provider app to add OAuthApp as an Inbound Authentication Config - appMgtService.updateApplication(createdServiceProvider); - - OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo(); - oAuthApplicationInfo.setClientId(createdApp.getOauthConsumerKey()); - oAuthApplicationInfo.setCallBackURL(createdApp.getCallbackUrl()); - oAuthApplicationInfo.setClientSecret(createdApp.getOauthConsumerSecret()); - oAuthApplicationInfo.setClientName(createdApp.getApplicationName()); - - oAuthApplicationInfo.addParameter( - ApplicationConstants.ClientMetadata.OAUTH_REDIRECT_URIS, createdApp.getCallbackUrl()); - oAuthApplicationInfo.addParameter( - ApplicationConstants.ClientMetadata.OAUTH_CLIENT_GRANT, createdApp.getGrantTypes()); - return oAuthApplicationInfo; - } catch (IdentityApplicationManagementException e) { - APIUtil.handleException("Error occurred while creating ServiceProvider for app " + applicationName, e); - } catch (Exception e) { - APIUtil.handleException("Error occurred while creating OAuthApp " + applicationName, e); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(baseUser); - } - return null; - } - - public void unregisterApplication(String userId, String applicationName, - String consumerKey) throws APIManagementException { - String tenantDomain = MultitenantUtils.getTenantDomain(userId); - String baseUser = CarbonContext.getThreadLocalCarbonContext().getUsername(); - String userName = MultitenantUtils.getTenantAwareUsername(userId); - - PrivilegedCarbonContext.startTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName); - - if (userId == null || userId.isEmpty()) { - throw new APIManagementException("Error occurred while unregistering Application: userId cannot " + - "be null/empty"); - } - try { - OAuthAdminService oAuthAdminService = new OAuthAdminService(); - OAuthConsumerAppDTO oAuthConsumerAppDTO = oAuthAdminService.getOAuthApplicationData(consumerKey); - - if (oAuthConsumerAppDTO == null) { - throw new APIManagementException("Couldn't retrieve OAuth Consumer Application associated with the " + - "given consumer key: " + consumerKey); - } - oAuthAdminService.removeOAuthApplicationData(consumerKey); - - ApplicationManagementService appMgtService = ApplicationManagementService.getInstance(); - ServiceProvider createdServiceProvider = appMgtService.getApplication(applicationName); - - if (createdServiceProvider == null) { - throw new APIManagementException("Couldn't retrieve Service Provider Application " + applicationName); - } - appMgtService.deleteApplication(applicationName); - - } catch (IdentityApplicationManagementException e) { - APIUtil.handleException("Error occurred while removing ServiceProvider for app " + applicationName, e); - } catch (Exception e) { - APIUtil.handleException("Error occurred while removing OAuthApp " + applicationName, e); - } finally { - PrivilegedCarbonContext.endTenantFlow(); - PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(baseUser); - } - } - } From fd6793a9afa8eac11cec1fbd82d63790901329f7 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Thu, 9 Jul 2015 22:07:15 +0530 Subject: [PATCH 4/6] Fixing device management API structure --- .../device/mgt/common/DeviceManager.java | 7 -- .../common/spi/DeviceManagementService.java | 16 +++- .../DeviceManagementPluginRepository.java | 4 +- ...ApplicationManagerProviderServiceImpl.java | 4 +- .../DeviceManagementServiceComponent.java | 4 +- .../DeviceManagementProviderServiceImpl.java | 48 +++++------ .../core/DeviceManagementRepositoryTests.java | 6 +- .../mgt/core/TestDeviceManagementService.java | 80 ++++--------------- .../profile/UnregistrationProfile.java | 1 + 9 files changed, 65 insertions(+), 105 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManager.java index 3c87246713..111b7a3be2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManager.java @@ -24,13 +24,6 @@ import java.util.List; * device type plugin implementation intended to be managed through CDM. */ public interface DeviceManager { - /** - * Method to retrieve the provider type that implements DeviceManager interface. - * - * @return Returns provider type - */ - String getProviderType(); - /** * Method to return feature manager implementation associated with a particular platform-specific plugin. * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java index df97aede20..941d51c473 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/DeviceManagementService.java @@ -18,6 +18,7 @@ */ package org.wso2.carbon.device.mgt.common.spi; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManager; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; @@ -25,6 +26,19 @@ import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; * Composite interface that acts as the SPI exposing all device management as well as application management * functionalities */ -public interface DeviceManagementService extends DeviceManager, ApplicationManager { +public interface DeviceManagementService extends ApplicationManager { + + /** + * Method to retrieve the provider type that implements DeviceManager interface. + * + * @return Returns provider type + */ + String getType(); + + void init() throws DeviceManagementException; + + DeviceManager getDeviceManager(); + + ApplicationManager getApplicationManager(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java index 85093ad284..488f2f9866 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java @@ -34,7 +34,7 @@ public class DeviceManagementPluginRepository { } public void addDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { - String deviceType = provider.getProviderType(); + String deviceType = provider.getType(); try { DeviceManagerUtil.registerDeviceType(deviceType); } catch (DeviceManagementException e) { @@ -45,7 +45,7 @@ public class DeviceManagementPluginRepository { } public void removeDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { - String deviceType = provider.getProviderType(); + String deviceType = provider.getType(); providers.remove(deviceType); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java index 69a7e8eb8a..c2ec4f8d7f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java @@ -203,7 +203,7 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem pluginRepository.addDeviceManagementProvider(deviceManagementService); } catch (DeviceManagementException e) { log.error("Error occurred while registering device management plugin '" + - deviceManagementService.getProviderType() + "'", e); + deviceManagementService.getType() + "'", e); } } @@ -213,7 +213,7 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem pluginRepository.removeDeviceManagementProvider(deviceManagementService); } catch (DeviceManagementException e) { log.error("Error occurred while un-registering device management plugin '" + - deviceManagementService.getProviderType() + "'", e); + deviceManagementService.getType() + "'", e); } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java index 48b695f2e9..2d480dfbc6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -242,7 +242,7 @@ public class DeviceManagementServiceComponent { protected void setDeviceManagementService(DeviceManagementService deviceManagementService) { if (log.isDebugEnabled()) { log.debug("Setting Device Management Service Provider: '" + - deviceManagementService.getProviderType() + "'"); + deviceManagementService.getType() + "'"); } synchronized (LOCK) { deviceManagers.add(deviceManagementService); @@ -260,7 +260,7 @@ public class DeviceManagementServiceComponent { protected void unsetDeviceManagementService(DeviceManagementService deviceManagementService) { if (log.isDebugEnabled()) { log.debug("Un setting Device Management Service Provider : '" + - deviceManagementService.getProviderType() + "'"); + deviceManagementService.getType() + "'"); } for (PluginInitializationListener listener : listeners) { listener.unregisterDeviceManagementService(deviceManagementService); 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 150287fdbd..c10541362e 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 @@ -21,7 +21,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.*; -import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; @@ -68,11 +67,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv DeviceManagementServiceComponent.registerPluginInitializationListener(this); } - @Override - public String getProviderType() { - return null; - } - @Override public FeatureManager getFeatureManager() { return null; @@ -81,14 +75,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public FeatureManager getFeatureManager(String type) { DeviceManager dms = - this.getPluginRepository().getDeviceManagementService(type); + this.getPluginRepository().getDeviceManagementService(type).getDeviceManager(); return dms.getFeatureManager(); } @Override public boolean enrollDevice(Device device) throws DeviceManagementException { DeviceManager dms = - this.getPluginRepository().getDeviceManagementService(device.getType()); + this.getPluginRepository().getDeviceManagementService(device.getType()).getDeviceManager(); boolean status = dms.enrollDevice(device); try { if (dms.isClaimable(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()))) { @@ -134,7 +128,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public boolean modifyEnrollment(Device device) throws DeviceManagementException { DeviceManager dms = - this.getPluginRepository().getDeviceManagementService(device.getType()); + this.getPluginRepository().getDeviceManagementService(device.getType()).getDeviceManager(); boolean status = dms.modifyEnrollment(device); try { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); @@ -167,7 +161,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); DeviceManager dms = - this.getPluginRepository().getDeviceManagementService(deviceId.getType()); + this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager(); try { Device device = deviceDAO.getDevice(deviceId,tenantId); DeviceType deviceType = deviceTypeDAO.getDeviceType(device.getType()); @@ -188,14 +182,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException { DeviceManager dms = - this.getPluginRepository().getDeviceManagementService(deviceId.getType()); + this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager(); return dms.isEnrolled(deviceId); } @Override public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException { DeviceManager dms = - this.getPluginRepository().getDeviceManagementService(deviceId.getType()); + this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager(); return dms.isActive(deviceId); } @@ -203,7 +197,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv public boolean setActive(DeviceIdentifier deviceId, boolean status) throws DeviceManagementException { DeviceManager dms = - this.getPluginRepository().getDeviceManagementService(deviceId.getType()); + this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager(); return dms.setActive(deviceId, status); } @@ -227,7 +221,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } for (Device device : allDevices) { Device dmsDevice = - this.getPluginRepository().getDeviceManagementService(device.getType()).getDevice( + this.getPluginRepository().getDeviceManagementService( + device.getType()).getDeviceManager().getDevice( new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); device.setFeatures(dmsDevice.getFeatures()); device.setProperties(dmsDevice.getProperties()); @@ -257,7 +252,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv for (Device device : allDevices) { Device dmsDevice = - this.getPluginRepository().getDeviceManagementService(device.getType()).getDevice( + this.getPluginRepository().getDeviceManagementService( + device.getType()).getDeviceManager().getDevice( new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); device.setFeatures(dmsDevice.getFeatures()); device.setProperties(dmsDevice.getProperties()); @@ -407,7 +403,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } } if (device != null) { - DeviceManager dms = this.getPluginRepository().getDeviceManagementService(deviceId.getType()); + DeviceManager dms = + this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager(); Device pluginSpecificInfo = dms.getDevice(deviceId); device.setProperties(pluginSpecificInfo.getProperties()); device.setFeatures(pluginSpecificInfo.getFeatures()); @@ -418,7 +415,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException { DeviceManager dms = - this.getPluginRepository().getDeviceManagementService(device.getType()); + this.getPluginRepository().getDeviceManagementService(device.getType()).getDeviceManager(); return dms.updateDeviceInfo(deviceIdentifier, device); } @@ -426,14 +423,14 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) throws DeviceManagementException { DeviceManager dms = - this.getPluginRepository().getDeviceManagementService(deviceId.getType()); + this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager(); return dms.setOwnership(deviceId, ownershipType); } @Override public boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException { DeviceManager dms = - this.getPluginRepository().getDeviceManagementService(deviceId.getType()); + this.getPluginRepository().getDeviceManagementService(deviceId.getType()).getDeviceManager(); return dms.isClaimable(deviceId); } @@ -552,7 +549,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv for (Device device : userDevices) { Device dmsDevice = - this.getPluginRepository().getDeviceManagementService(device.getType()).getDevice( + this.getPluginRepository().getDeviceManagementService( + device.getType()).getDeviceManager().getDevice( new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); device.setFeatures(dmsDevice.getFeatures()); device.setProperties(dmsDevice.getProperties()); @@ -594,7 +592,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } for (Device device : userDevices) { Device dmsDevice = - this.getPluginRepository().getDeviceManagementService(device.getType()).getDevice( + this.getPluginRepository().getDeviceManagementService( + device.getType()).getDeviceManager().getDevice( new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); device.setFeatures(dmsDevice.getFeatures()); device.setProperties(dmsDevice.getProperties()); @@ -641,7 +640,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv } for (Device device : allDevices) { Device dmsDevice = - this.getPluginRepository().getDeviceManagementService(device.getType()).getDevice( + this.getPluginRepository().getDeviceManagementService( + device.getType()).getDeviceManager().getDevice( new DeviceIdentifier(device.getDeviceIdentifier(), device.getType())); device.setFeatures(dmsDevice.getFeatures()); device.setProperties(dmsDevice.getProperties()); @@ -673,7 +673,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv pluginRepository.addDeviceManagementProvider(deviceManagementService); } catch (DeviceManagementException e) { log.error("Error occurred while registering device management plugin '" + - deviceManagementService.getProviderType() + "'", e); + deviceManagementService.getType() + "'", e); } } @@ -683,7 +683,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv pluginRepository.removeDeviceManagementProvider(deviceManagementService); } catch (DeviceManagementException e) { log.error("Error occurred while un-registering device management plugin '" + - deviceManagementService.getProviderType() + "'", e); + deviceManagementService.getType() + "'", e); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/DeviceManagementRepositoryTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/DeviceManagementRepositoryTests.java index 26e40ca524..d4d54b6a62 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/DeviceManagementRepositoryTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/DeviceManagementRepositoryTests.java @@ -41,9 +41,9 @@ public class DeviceManagementRepositoryTests { } catch (DeviceManagementException e) { Assert.fail("Unexpected error occurred while invoking addDeviceManagementProvider functionality", e); } - DeviceManager targetProvider = + DeviceManagementService targetProvider = this.getRepository().getDeviceManagementService(TestDeviceManagementService.DEVICE_TYPE_TEST); - Assert.assertEquals(targetProvider.getProviderType(), sourceProvider.getProviderType()); + Assert.assertEquals(targetProvider.getType(), sourceProvider.getType()); } @Test(dependsOnMethods = "testAddDeviceManagementService") @@ -54,7 +54,7 @@ public class DeviceManagementRepositoryTests { } catch (DeviceManagementException e) { Assert.fail("Unexpected error occurred while invoking removeDeviceManagementProvider functionality", e); } - DeviceManager targetProvider = + DeviceManagementService targetProvider = this.getRepository().getDeviceManagementService(TestDeviceManagementService.DEVICE_TYPE_TEST); Assert.assertNull(targetProvider); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java index f074adc2e5..58f583edee 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/TestDeviceManagementService.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core; import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; @@ -29,98 +30,49 @@ public class TestDeviceManagementService implements DeviceManagementService { public static final String DEVICE_TYPE_TEST = "Test"; - @Override - public String getProviderType() { - return TestDeviceManagementService.DEVICE_TYPE_TEST; - } - - @Override - public FeatureManager getFeatureManager() { - return null; - } - - @Override - public boolean enrollDevice(Device device) throws DeviceManagementException { - return false; - } - - @Override - public boolean modifyEnrollment(Device device) throws DeviceManagementException { - return false; - } - - @Override - public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException { - return false; - } - - @Override - public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException { - return false; - } @Override - public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException { - return false; - } - - @Override - public boolean setActive(DeviceIdentifier deviceId, boolean status) throws DeviceManagementException { - return false; - } - - @Override - public List getAllDevices() throws DeviceManagementException { - return null; - } - - @Override - public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException { - return null; - } - - @Override - public boolean updateDeviceInfo(DeviceIdentifier deviceId, Device device) throws DeviceManagementException { - return false; + public String getType() { + return TestDeviceManagementService.DEVICE_TYPE_TEST; } @Override - public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType) throws DeviceManagementException { - return false; + public void init() throws DeviceManagementException { + } @Override - public boolean isClaimable(DeviceIdentifier deviceId) throws DeviceManagementException { - return false; + public DeviceManager getDeviceManager() { + return null; } @Override - public boolean setStatus(DeviceIdentifier deviceId, String currentOwner, - EnrolmentInfo.Status status) throws DeviceManagementException { - return false; + public ApplicationManager getApplicationManager() { + return null; } @Override public Application[] getApplications(String domain, int pageNumber, int size) throws ApplicationManagementException { - return new Application[0]; + return new Application[0]; } @Override public void updateApplicationStatus(DeviceIdentifier deviceId, Application application, String status) throws ApplicationManagementException { - + } @Override public String getApplicationStatus(DeviceIdentifier deviceId, Application application) throws ApplicationManagementException { - return null; + return null; } @Override - public void installApplication(Operation operation, List deviceIdentifiers) - throws ApplicationManagementException { - + public void installApplication(Operation operation, + List deviceIdentifiers) throws ApplicationManagementException { + } + } diff --git a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/UnregistrationProfile.java b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/UnregistrationProfile.java index a7959a7ded..4f3930f5d0 100644 --- a/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/UnregistrationProfile.java +++ b/components/oauth-extensions/dynamic-client-manager/src/main/java/org/wso2/carbon/identity/oauth/extension/profile/UnregistrationProfile.java @@ -48,4 +48,5 @@ public class UnregistrationProfile { public void setUserId(String userId) { this.userId = userId; } + } From a88643000508183ddc534ea46db64fe641c0ff85 Mon Sep 17 00:00:00 2001 From: prabathabey Date: Thu, 9 Jul 2015 22:17:22 +0530 Subject: [PATCH 5/6] Initializing Device Management providers --- .../device/mgt/core/DeviceManagementPluginRepository.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java index 488f2f9866..4c276405ff 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java @@ -36,6 +36,8 @@ public class DeviceManagementPluginRepository { public void addDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { String deviceType = provider.getType(); try { + /* Initializing Device Management Service Provider */ + provider.init(); DeviceManagerUtil.registerDeviceType(deviceType); } catch (DeviceManagementException e) { throw new DeviceManagementException("Error occurred while adding device management provider '" + From d048913e068972cb21157391483f8545e6bfb100 Mon Sep 17 00:00:00 2001 From: geethkokila Date: Mon, 13 Jul 2015 10:55:27 +0530 Subject: [PATCH 6/6] Adding the momitoring task partialy --- .../mgt/common/Monitor/ComplianceData.java | 25 +++ .../Monitor/ComplianceDecisionPoint.java | 5 +- .../policy/mgt/common/ProfileFeature.java | 3 +- .../common/spi/PolicyMonitoringService.java | 3 +- .../policy/mgt/core/dao/MonitoringDAO.java | 6 +- .../mgt/core/dao/impl/MonitoringDAOImpl.java | 16 +- .../impl/ComplianceDecisionPointImpl.java | 170 +++++++++++++++++- .../core/mgt/impl/MonitoringManagerImpl.java | 10 +- .../policy/mgt/core/task/MonitoringTask.java | 30 +++- .../core/util/PolicyManagementConstants.java | 6 + .../mgt/core/util/PolicyManagerUtil.java | 2 + 11 files changed, 261 insertions(+), 15 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Monitor/ComplianceData.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Monitor/ComplianceData.java index ea64f96417..5511604078 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Monitor/ComplianceData.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Monitor/ComplianceData.java @@ -19,6 +19,8 @@ package org.wso2.carbon.policy.mgt.common.monitor; +import org.wso2.carbon.policy.mgt.common.Policy; + import java.util.List; public class ComplianceData { @@ -30,6 +32,13 @@ public class ComplianceData { private boolean status; private String message; + /** + * This parameter is to inform the policy core, weather related device type plugins does need the full policy or + * the part which is none compliance. + */ + private boolean completePolicy; + private Policy policy; + public int getId() { return id; } @@ -77,4 +86,20 @@ public class ComplianceData { public void setMessage(String message) { this.message = message; } + + public boolean isCompletePolicy() { + return completePolicy; + } + + public void setCompletePolicy(boolean completePolicy) { + this.completePolicy = completePolicy; + } + + public Policy getPolicy() { + return policy; + } + + public void setPolicy(Policy policy) { + this.policy = policy; + } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Monitor/ComplianceDecisionPoint.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Monitor/ComplianceDecisionPoint.java index fa751528ab..ada9b19a89 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Monitor/ComplianceDecisionPoint.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/Monitor/ComplianceDecisionPoint.java @@ -31,7 +31,8 @@ public interface ComplianceDecisionPoint { void setDeviceAsReachable(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException; - void reEnforcePolicy(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException; + void reEnforcePolicy(DeviceIdentifier deviceIdentifier, ComplianceData complianceData) throws + PolicyComplianceException; void markDeviceAsNoneCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException; @@ -41,7 +42,7 @@ public interface ComplianceDecisionPoint { void activateDevice(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException; - void validateDevicePolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy) throws + void validateDevicePolicyCompliance(DeviceIdentifier deviceIdentifier, ComplianceData complianceData) throws PolicyComplianceException; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/ProfileFeature.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/ProfileFeature.java index 9c677b72e9..00e3b65d96 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/ProfileFeature.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/ProfileFeature.java @@ -19,10 +19,11 @@ package org.wso2.carbon.policy.mgt.common; import java.io.Serializable; -import org.wso2.carbon.device.mgt.common.Feature; public class ProfileFeature implements Serializable { + private static final long serialVersionUID = 19981018L; + private int id; private String featureCode; private int profileId; diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/spi/PolicyMonitoringService.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/spi/PolicyMonitoringService.java index 890a72aaee..81478b6ba4 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/spi/PolicyMonitoringService.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/spi/PolicyMonitoringService.java @@ -21,6 +21,7 @@ package org.wso2.carbon.policy.mgt.common.spi; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature; import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; import org.wso2.carbon.policy.mgt.common.Policy; @@ -31,6 +32,6 @@ public interface PolicyMonitoringService { void notifyDevices(List devices) throws PolicyComplianceException; - List checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy, Object response) + ComplianceData checkPolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy, Object response) throws PolicyComplianceException; } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/MonitoringDAO.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/MonitoringDAO.java index a29928f8c4..426935e4e0 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/MonitoringDAO.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/MonitoringDAO.java @@ -37,5 +37,9 @@ public interface MonitoringDAO { List getNoneComplianceFeatures(int policyComplianceStatusId) throws MonitoringDAOException; - void deleteNoneComplianceData(int deviceId) throws MonitoringDAOException; + void deleteNoneComplianceData(int policyComplianceStatusId) throws MonitoringDAOException; + + void updateAttempts(int deviceId, boolean reset) throws MonitoringDAOException; + + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/MonitoringDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/MonitoringDAOImpl.java index 8676709c09..e6bb638537 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/MonitoringDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/MonitoringDAOImpl.java @@ -80,9 +80,10 @@ public class MonitoringDAOImpl implements MonitoringDAO { PreparedStatement stmt = null; try { conn = this.getConnection(); - String query = "DELETE FROM DM_POLICY_COMPLIANCE_STATUS WHERE DEVICE_ID = ?"; + String query = "UPDATE DM_POLICY_COMPLIANCE_STATUS SET STATUS = ? WHERE DEVICE_ID = ?"; stmt = conn.prepareStatement(query); - stmt.setInt(1, deviceId); + stmt.setInt(1, 1); + stmt.setInt(2, deviceId); stmt.executeUpdate(); @@ -193,15 +194,15 @@ public class MonitoringDAOImpl implements MonitoringDAO { } @Override - public void deleteNoneComplianceData(int deviceId) throws MonitoringDAOException { + public void deleteNoneComplianceData(int policyComplianceStatusId) throws MonitoringDAOException { Connection conn; PreparedStatement stmt = null; try { conn = this.getConnection(); - String query = "DELETE FROM DM_POLICY_COMPLIANCE_STATUS WHERE DEVICE_ID = ?"; + String query = "DELETE FROM DM_POLICY_COMPLIANCE_FEATURES WHERE COMPLIANCE_STATUS_ID = ?"; stmt = conn.prepareStatement(query); - stmt.setInt(1, deviceId); + stmt.setInt(1, policyComplianceStatusId); stmt.executeUpdate(); } catch (SQLException e) { @@ -214,6 +215,11 @@ public class MonitoringDAOImpl implements MonitoringDAO { } + @Override + public void updateAttempts(int deviceId, boolean reset) throws MonitoringDAOException { + + } + private Connection getConnection() throws MonitoringDAOException { try { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java index 313b427276..5506bcb363 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java @@ -21,15 +21,31 @@ package org.wso2.carbon.policy.mgt.core.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.EnrolmentInfo; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; 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.EnrolmentDAO; +import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation; +import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation; import org.wso2.carbon.policy.mgt.common.Policy; +import org.wso2.carbon.policy.mgt.common.ProfileFeature; +import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceDecisionPoint; +import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature; import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; +import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.PolicyManager; import org.wso2.carbon.policy.mgt.core.mgt.impl.PolicyManagerImpl; +import org.wso2.carbon.policy.mgt.core.util.PolicyManagementConstants; +import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; + +import java.util.ArrayList; +import java.util.List; public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { @@ -54,41 +70,191 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { @Override public void setDeviceAsUnreachable(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { + try { + int tenantId = PolicyManagerUtil.getTenantId(); + Device device = deviceDAO.getDevice(deviceIdentifier, tenantId); + enrolmentDAO.setStatus(device.getId(), device.getEnrolmentInfo().getOwner(), + EnrolmentInfo.Status.UNREACHABLE, tenantId); + + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while setting the device as unreachable for " + + deviceIdentifier.getId() + " - " + deviceIdentifier.getType(); + log.error(msg, e); + throw new PolicyComplianceException(msg, e); + } + } @Override public void setDeviceAsReachable(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { + try { + int tenantId = PolicyManagerUtil.getTenantId(); + Device device = deviceDAO.getDevice(deviceIdentifier, tenantId); + enrolmentDAO.setStatus(device.getId(), device.getEnrolmentInfo().getOwner(), + EnrolmentInfo.Status.ACTIVE, tenantId); + + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while setting the device as reachable for " + + deviceIdentifier.getId() + " - " + deviceIdentifier.getType(); + log.error(msg, e); + throw new PolicyComplianceException(msg, e); + } + } @Override - public void reEnforcePolicy(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { + public void reEnforcePolicy(DeviceIdentifier deviceIdentifier, ComplianceData complianceData) throws + PolicyComplianceException { + + try { + Policy policy = complianceData.getPolicy(); + if (policy != null) { + List deviceIdentifiers = new ArrayList(); + deviceIdentifiers.add(deviceIdentifier); + + + List profileOperationList = new ArrayList(); + + PolicyOperation policyOperation = new PolicyOperation(); + policyOperation.setEnabled(true); + policyOperation.setType(Operation.Type.POLICY); + policyOperation.setCode(PolicyOperation.POLICY_OPERATION_CODE); + + + if (complianceData.isCompletePolicy()) { + List effectiveFeatures = policy.getProfile().getProfileFeaturesList(); + + for (ProfileFeature feature : effectiveFeatures) { + ProfileOperation profileOperation = new ProfileOperation(); + profileOperation.setCode(feature.getFeatureCode()); + profileOperation.setEnabled(true); + profileOperation.setStatus(Operation.Status.PENDING); + profileOperation.setType(Operation.Type.PROFILE); + profileOperation.setPayLoad(feature.getContent()); + profileOperationList.add(profileOperation); + } + } else { + List noneComplianceFeatures = complianceData.getComplianceFeatures(); + for (ComplianceFeature feature : noneComplianceFeatures) { + ProfileOperation profileOperation = new ProfileOperation(); + + profileOperation.setCode(feature.getFeatureCode()); + profileOperation.setEnabled(true); + profileOperation.setStatus(Operation.Status.PENDING); + profileOperation.setType(Operation.Type.PROFILE); + profileOperation.setPayLoad(feature.getFeature().getContent()); + profileOperationList.add(profileOperation); + } + } + policyOperation.setProfileOperations(profileOperationList); + policyOperation.setPayLoad(policyOperation.getProfileOperations()); + PolicyManagementDataHolder.getInstance().getDeviceManagementService(). + addOperation(policyOperation, deviceIdentifiers); + + } + + } catch (OperationManagementException e) { + String msg = "Error occurred while re-enforcing the policy to device " + deviceIdentifier.getId() + " - " + + deviceIdentifier.getType(); + log.error(msg, e); + throw new PolicyComplianceException(msg, e); + } } @Override public void markDeviceAsNoneCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { + try { + int tenantId = PolicyManagerUtil.getTenantId(); + Device device = deviceDAO.getDevice(deviceIdentifier, tenantId); + enrolmentDAO.setStatus(device.getId(), device.getEnrolmentInfo().getOwner(), + EnrolmentInfo.Status.BLOCKED, tenantId); + + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while marking device as none compliance " + deviceIdentifier.getId() + " - " + + deviceIdentifier.getType(); + log.error(msg, e); + throw new PolicyComplianceException(msg, e); + } } @Override public void markDeviceAsCompliance(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { + try { + int tenantId = PolicyManagerUtil.getTenantId(); + Device device = deviceDAO.getDevice(deviceIdentifier, tenantId); + enrolmentDAO.setStatus(device.getId(), device.getEnrolmentInfo().getOwner(), + EnrolmentInfo.Status.ACTIVE, tenantId); + + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while marking device as compliance " + deviceIdentifier.getId() + " - " + + deviceIdentifier.getType(); + log.error(msg, e); + throw new PolicyComplianceException(msg, e); + } + } @Override public void deactivateDevice(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { + try { + int tenantId = PolicyManagerUtil.getTenantId(); + Device device = deviceDAO.getDevice(deviceIdentifier, tenantId); + enrolmentDAO.setStatus(device.getId(), device.getEnrolmentInfo().getOwner(), + EnrolmentInfo.Status.INACTIVE, tenantId); + + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while deactivating the device " + deviceIdentifier.getId() + " - " + + deviceIdentifier.getType(); + log.error(msg, e); + throw new PolicyComplianceException(msg, e); + } } @Override public void activateDevice(DeviceIdentifier deviceIdentifier) throws PolicyComplianceException { + try { + int tenantId = PolicyManagerUtil.getTenantId(); + Device device = deviceDAO.getDevice(deviceIdentifier, tenantId); + enrolmentDAO.setStatus(device.getId(), device.getEnrolmentInfo().getOwner(), + EnrolmentInfo.Status.ACTIVE, tenantId); + + } catch (DeviceManagementDAOException e) { + String msg = "Error occurred while activating the device " + deviceIdentifier.getId() + " - " + + deviceIdentifier.getType(); + log.error(msg, e); + throw new PolicyComplianceException(msg, e); + } } @Override - public void validateDevicePolicyCompliance(DeviceIdentifier deviceIdentifier, Policy policy) throws + public void validateDevicePolicyCompliance(DeviceIdentifier deviceIdentifier, ComplianceData complianceData) throws PolicyComplianceException { + Policy policy = complianceData.getPolicy(); + String compliance = this.getNoneComplianceRule(policy); + + if (compliance.equals("")) { + String msg = "Compliance rule is empty for the policy " + policy.getPolicyName() + ". Therefore " + + "Monitoring Engine cannot run."; + throw new PolicyComplianceException(msg); + } + + if (PolicyManagementConstants.ENFORCE.equalsIgnoreCase(compliance)) { + this.reEnforcePolicy(deviceIdentifier, complianceData); + } + + if (PolicyManagementConstants.WARN.equalsIgnoreCase(compliance)) { + this.markDeviceAsNoneCompliance(deviceIdentifier); + } + + if (PolicyManagementConstants.BLOCK.equalsIgnoreCase(compliance)) { + this.markDeviceAsNoneCompliance(deviceIdentifier); + } } } 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 d5143122a3..37b3b6491d 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 @@ -27,6 +27,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.policy.mgt.common.monitor.ComplianceData; +import org.wso2.carbon.policy.mgt.common.monitor.ComplianceDecisionPoint; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceFeature; import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; import org.wso2.carbon.policy.mgt.common.Policy; @@ -37,6 +38,7 @@ import org.wso2.carbon.policy.mgt.core.dao.MonitoringDAOException; import org.wso2.carbon.policy.mgt.core.dao.PolicyDAO; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory; import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException; +import org.wso2.carbon.policy.mgt.core.impl.ComplianceDecisionPointImpl; import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; import org.wso2.carbon.policy.mgt.core.mgt.MonitoringManager; import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil; @@ -48,6 +50,7 @@ public class MonitoringManagerImpl implements MonitoringManager { private PolicyDAO policyDAO; private DeviceDAO deviceDAO; private MonitoringDAO monitoringDAO; + private ComplianceDecisionPoint complianceDecisionPoint; private static final Log log = LogFactory.getLog(MonitoringManagerImpl.class); @@ -55,6 +58,7 @@ public class MonitoringManagerImpl implements MonitoringManager { this.policyDAO = PolicyManagementDAOFactory.getPolicyDAO(); this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO(); this.monitoringDAO = PolicyManagementDAOFactory.getMonitoringDAO(); + this.complianceDecisionPoint = new ComplianceDecisionPointImpl(); } @Override @@ -71,13 +75,15 @@ public class MonitoringManagerImpl implements MonitoringManager { PolicyMonitoringService monitoringService = PolicyManagementDataHolder.getInstance(). getPolicyMonitoringService(deviceIdentifier.getType()); - complianceFeatures = monitoringService.checkPolicyCompliance(deviceIdentifier, + ComplianceData complianceData = monitoringService.checkPolicyCompliance(deviceIdentifier, policy, deviceResponse); + complianceData.setPolicy(policy); + complianceFeatures = complianceData.getComplianceFeatures(); if (!complianceFeatures.isEmpty()) { int complianceId = monitoringDAO.setDeviceAsNoneCompliance(device.getId(), policy.getId()); monitoringDAO.addNoneComplianceFeatures(complianceId, device.getId(), complianceFeatures); - + complianceDecisionPoint.validateDevicePolicyCompliance(deviceIdentifier, complianceData); List profileFeatures = policy.getProfile().getProfileFeaturesList(); for (ComplianceFeature compFeature : complianceFeatures) { for (ProfileFeature profFeature : profileFeatures) { diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java index e68c55e921..cf62d08b07 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/task/MonitoringTask.java @@ -19,12 +19,22 @@ package org.wso2.carbon.policy.mgt.core.task; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.ntask.core.Task; +import org.wso2.carbon.policy.mgt.common.spi.PolicyMonitoringService; +import org.wso2.carbon.policy.mgt.core.internal.PolicyManagementDataHolder; +import java.util.List; import java.util.Map; public class MonitoringTask implements Task { + private DeviceTypeDAO deviceTypeDAO; + @Override public void setProperties(Map map) { @@ -32,11 +42,29 @@ public class MonitoringTask implements Task { @Override public void init() { - + deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO(); } @Override public void execute() { + try { + List deviceTypes = deviceTypeDAO.getDeviceTypes(); + + + DeviceManagementProviderService deviceManagementProviderService = + PolicyManagementDataHolder.getInstance().getDeviceManagementService(); + + for (DeviceType deviceType : deviceTypes) { + PolicyMonitoringService monitoringService = + PolicyManagementDataHolder.getInstance().getPolicyMonitoringService(deviceType.getName()); + + List devices = deviceManagementProviderService.getAllDevices(deviceType.getName()); + monitoringService.notifyDevices(devices); + } + + } catch (Exception e) { + + } } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java index fa390ffdb2..477e9bcb32 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagementConstants.java @@ -24,4 +24,10 @@ public final class PolicyManagementConstants { public static final String ANY = "ANY"; public static final String POLICY_BUNDLE = "POLICY_BUNDLE"; + public static final String MONITOR = "MONITOR"; + public static final String ENFORCE = "ENFORCE"; + public static final String WARN = "WARN"; + public static final String BLOCK = "BLOCK"; + + } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java index 8e2ca941d0..7cbcabeac0 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java @@ -98,4 +98,6 @@ public class PolicyManagerUtil { } return tenantId; } + + }