Refactored MQTT management admin service component

revert-dabc3590
Milan Perera 7 years ago
parent 0ed4525b20
commit 057b735b77

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>mb-extensions</artifactId> <artifactId>mb-extensions</artifactId>
<version>4.0.2-SNAPSHOT</version> <version>4.0.73-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -1,71 +0,0 @@
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "Scope", description = "Template of the authorization scope")
public class Scope {
@ApiModelProperty(name = "scope key", value = "An unique string as a key.", required = true)
private String key;
@ApiModelProperty(name = "scope name", value = "Scope name.", required = true)
private String name;
@ApiModelProperty(name = "roles", value = "List of roles to be associated with the scope", required = true)
private String roles;
@ApiModelProperty(name = "scope description", value = "A description of the scope", required = true)
private String description;
public Scope() {
}
public String getKey() {
return this.key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getRoles() {
return this.roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
}

@ -1,55 +0,0 @@
/*
* Copyright (c) 2016, 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.andes.extensions.device.mgt.jaxrs.exception;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.util.Constants;
//import org.wso2.carbon.andes.extensionstensions.device.mgt.jaxrs.util.DeviceMgtUtil;
import javax.validation.ConstraintViolation;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.util.Set;
public class ConstraintViolationException extends WebApplicationException {
private String message;
public <T> ConstraintViolationException(Set<ConstraintViolation<T>> violations) {
// super(Response.status(Response.Status.BAD_REQUEST)
// .entity(DeviceMgtUtil.getConstraintViolationErrorDTO(violations))
// .header(Constants.DeviceConstants.HEADER_CONTENT_TYPE, Constants.DeviceConstants.APPLICATION_JSON)
// .build());
//
// //Set the error message
// StringBuilder stringBuilder = new StringBuilder();
// for (ConstraintViolation violation : violations) {
// stringBuilder.append(violation.getRootBeanClass().getSimpleName());
// stringBuilder.append(".");
// stringBuilder.append(violation.getPropertyPath());
// stringBuilder.append(": ");
// stringBuilder.append(violation.getMessage());
// stringBuilder.append(", ");
// }
//message = stringBuilder.toString();
}
@Override
public String getMessage() {
return message;
}
}

@ -1,86 +0,0 @@
/*
* Copyright (c) 2016, 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.andes.extensions.device.mgt.jaxrs.exception;
import java.util.ArrayList;
import java.util.List;
public class ErrorDTO {
private Long code = null;
private String message = null;
private String description = null;
public void setMoreInfo(String moreInfo) {
this.moreInfo = moreInfo;
}
public void setCode(Long code) {
this.code = code;
}
public void setMessage(String message) {
this.message = message;
}
public void setDescription(String description) {
this.description = description;
}
public void setError(List<ErrorDTO> error) {
this.error = error;
}
private String moreInfo = null;
public String getMessage() {
return message;
}
public Long getCode() {
return code;
}
public String getDescription() {
return description;
}
public String getMoreInfo() {
return moreInfo;
}
public List<ErrorDTO> getError() {
return error;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("class ErrorDTO {\n");
stringBuilder.append(" code: ").append(code).append("\n");
stringBuilder.append(" message: ").append(message).append("\n");
stringBuilder.append(" description: ").append(description).append("\n");
stringBuilder.append(" moreInfo: ").append(moreInfo).append("\n");
stringBuilder.append(" error: ").append(error).append("\n");
stringBuilder.append("}\n");
return stringBuilder.toString();
}
private List<ErrorDTO> error = new ArrayList<>();
}

@ -1,51 +0,0 @@
/*
* Copyright (c) 2016, 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.andes.extensions.device.mgt.jaxrs.exception;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.util.Constants;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
/**
* Exception class that is corresponding to 401 Forbidden response
*/
public class ForbiddenException extends WebApplicationException {
private String message;
public ForbiddenException() {
super(Response.status(Response.Status.FORBIDDEN)
.build());
}
public ForbiddenException(ErrorDTO errorDTO) {
super(Response.status(Response.Status.FORBIDDEN)
.entity(errorDTO)
.header(Constants.DeviceConstants.HEADER_CONTENT_TYPE, Constants.DeviceConstants.APPLICATION_JSON)
.build());
message = errorDTO.getDescription();
}
@Override
public String getMessage() {
return message;
}
}

@ -1,113 +0,0 @@
/*
* Copyright (c) 2016, 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.andes.extensions.device.mgt.jaxrs.exception;
import com.google.gson.JsonParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
//import org.wso2.carbon.andes.extensionsnsions.device.mgt.jaxrs.util.DeviceMgtUtil;
import javax.naming.AuthenticationException;
import javax.ws.rs.ClientErrorException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
/**
* Handle the cxf level exceptions.
*/
public class GlobalThrowableMapper implements ExceptionMapper {
private static final Log log = LogFactory.getLog(GlobalThrowableMapper.class);
private ErrorDTO e500 = new ErrorDTO();
GlobalThrowableMapper() {
e500.setCode((long) 500);
e500.setMessage("Internal server error.");
e500.setMoreInfo("");
e500.setDescription("The server encountered an internal error. Please contact administrator.");
}
@Override
public Response toResponse(Throwable e) {
// if (e instanceof JsonParseException) {
// String errorMessage = "Malformed request body.";
// if (log.isDebugEnabled()) {
// log.error(errorMessage, e);
// }
// return DeviceMgtUtil.buildBadRequestException(errorMessage).getResponse();
// }
if (e instanceof NotFoundException) {
return ((NotFoundException) e).getResponse();
}
if (e instanceof UnexpectedServerErrorException) {
if (log.isDebugEnabled()) {
log.error("Unexpected server error.", e);
}
return ((UnexpectedServerErrorException) e).getResponse();
}
if (e instanceof ConstraintViolationException) {
if (log.isDebugEnabled()) {
log.error("Constraint violation.", e);
}
return ((ConstraintViolationException) e).getResponse();
}
if (e instanceof IllegalArgumentException) {
ErrorDTO errorDetail = new ErrorDTO();
errorDetail.setCode((long) 400);
errorDetail.setMoreInfo("");
errorDetail.setMessage("");
errorDetail.setDescription(e.getMessage());
return Response
.status(Response.Status.BAD_REQUEST)
.entity(errorDetail)
.build();
}
if (e instanceof ClientErrorException) {
if (log.isDebugEnabled()) {
log.error("Client error.", e);
}
return ((ClientErrorException) e).getResponse();
}
if (e instanceof AuthenticationException) {
ErrorDTO errorDetail = new ErrorDTO();
errorDetail.setCode((long) 401);
errorDetail.setMoreInfo("");
errorDetail.setMessage("");
errorDetail.setDescription(e.getMessage());
return Response
.status(Response.Status.UNAUTHORIZED)
.entity(errorDetail)
.build();
}
if (e instanceof ForbiddenException) {
if (log.isDebugEnabled()) {
log.error("Resource forbidden.", e);
}
return ((ForbiddenException) e).getResponse();
}
//unknown exception log and return
if (log.isDebugEnabled()) {
log.error("An Unknown exception has been captured by global exception mapper.", e);
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).header("Content-Type", "application/json")
.entity(e500).build();
}
}

@ -0,0 +1,59 @@
/*
* Copyright (c) 2016, 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.andes.extensions.device.mgt.jaxrs.exception;
/**
* This class is used to handle MQTT configuration related exceptions
*/
public class MQTTConfigurationException extends Exception {
private static final long serialVersionUID = -3151279311929070288L;
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
setErrorMessage(errorMessage);
}
public MQTTConfigurationException(String errorMessage) {
super(errorMessage);
}
public MQTTConfigurationException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public MQTTConfigurationException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public MQTTConfigurationException() {
super();
}
public MQTTConfigurationException(Throwable cause) {
super(cause);
}
}

@ -1,47 +0,0 @@
/*
* Copyright (c) 2016, 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.andes.extensions.device.mgt.jaxrs.exception;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.util.Constants;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
public class NotFoundException extends WebApplicationException {
private String message;
private static final long serialVersionUID = 147943572342342340L;
public NotFoundException(ErrorResponse error) {
super(Response.status(Response.Status.NOT_FOUND).entity(error).build());
}
public NotFoundException(ErrorDTO errorDTO) {
super(Response.status(Response.Status.NOT_FOUND)
.entity(errorDTO)
.header(Constants.DeviceConstants.HEADER_CONTENT_TYPE, Constants.DeviceConstants.APPLICATION_JSON)
.build());
message = errorDTO.getDescription();
}
@Override
public String getMessage() {
return message;
}
}

@ -1,49 +0,0 @@
/*
* Copyright (c) 2016, 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.andes.extensions.device.mgt.jaxrs.exception;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.util.Constants;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
public class UnexpectedServerErrorException extends WebApplicationException {
private String message;
private static final long serialVersionUID = 147943579458906890L;
public UnexpectedServerErrorException(ErrorResponse error) {
super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build());
}
public UnexpectedServerErrorException(ErrorDTO errorDTO) {
super(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(errorDTO)
.header(Constants.DeviceConstants.HEADER_CONTENT_TYPE, Constants.DeviceConstants.APPLICATION_JSON)
.build());
message = errorDTO.getDescription();
}
@Override
public String getMessage() {
return message;
}
}

@ -1,122 +0,0 @@
/*
* Copyright (c) 2016, 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.andes.extensions.device.mgt.jaxrs.exception;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.jaxrs.lifecycle.ResourceProvider;
import org.apache.cxf.jaxrs.model.ClassResourceInfo;
import org.apache.cxf.jaxrs.model.OperationResourceInfo;
import org.apache.cxf.message.Message;
import org.apache.cxf.message.MessageContentsList;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
public class ValidationInterceptor extends AbstractPhaseInterceptor<Message> {
private Log log = LogFactory.getLog(getClass());
private Validator validator = null; //validator interface is thread-safe
public ValidationInterceptor() {
super(Phase.PRE_INVOKE);
ValidatorFactory defaultFactory = Validation.buildDefaultValidatorFactory();
validator = defaultFactory.getValidator();
if (validator == null) {
log.warn("Bean Validation provider could not be found, no validation will be performed");
} else {
log.debug("Validation In-Interceptor initialized successfully");
}
}
@Override
public void handleMessage(Message message) throws Fault {
final OperationResourceInfo operationResource = message.getExchange().get(OperationResourceInfo.class);
if (operationResource == null) {
log.info("OperationResourceInfo is not available, skipping validation");
return;
}
final ClassResourceInfo classResource = operationResource.getClassResourceInfo();
if (classResource == null) {
log.info("ClassResourceInfo is not available, skipping validation");
return;
}
final ResourceProvider resourceProvider = classResource.getResourceProvider();
if (resourceProvider == null) {
log.info("ResourceProvider is not available, skipping validation");
return;
}
final List<Object> arguments = MessageContentsList.getContentsList(message);
final Method method = operationResource.getAnnotatedMethod();
final Object instance = resourceProvider.getInstance(message);
if (method != null && arguments != null) {
//validate the parameters(arguments) over the invoked method
validate(method, arguments.toArray(), instance);
//validate the fields of each argument
for (Object arg : arguments) {
if (arg != null)
validate(arg);
}
}
}
public <T> void validate(final Method method, final Object[] arguments, final T instance) {
if (validator == null) {
log.warn("Bean Validation provider could not be found, no validation will be performed");
return;
}
ExecutableValidator methodValidator = validator.forExecutables();
Set<ConstraintViolation<T>> violations = methodValidator.validateParameters(instance,
method, arguments);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
}
public <T> void validate(final T object) {
if (validator == null) {
log.warn("Bean Validation provider could be found, no validation will be performed");
return;
}
Set<ConstraintViolation<T>> violations = validator.validate(object);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
}
public void handleFault(org.apache.cxf.message.Message messageParam) {
}
}

@ -16,7 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.andes.extensions.device.mgt.jaxrs.service.api.admin; package org.wso2.carbon.andes.extensions.device.mgt.jaxrs.service;
import io.swagger.annotations.SwaggerDefinition; import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Info; import io.swagger.annotations.Info;

@ -16,7 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.andes.extensions.device.mgt.jaxrs.service.impl.admin; package org.wso2.carbon.andes.extensions.device.mgt.jaxrs.service.impl;
import org.apache.axis2.AxisFault; import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.ConfigurationContext;
@ -29,11 +29,15 @@ import org.wso2.carbon.andes.core.types.xsd.MQTTSubscription;
import org.wso2.carbon.andes.core.types.xsd.Subscription; import org.wso2.carbon.andes.core.types.xsd.Subscription;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans.SubscriptionList; import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans.SubscriptionList;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.service.api.admin.MQTTManagementAdminService; import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.exception.MQTTConfigurationException;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.service.MQTTManagementAdminService;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.util.MQTTMgtAPIUtils;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.util.RequestValidationUtil;
import org.wso2.carbon.andes.mqtt.stub.AndesMQTTAdminServiceBrokerManagerAdminException; import org.wso2.carbon.andes.mqtt.stub.AndesMQTTAdminServiceBrokerManagerAdminException;
import org.wso2.carbon.andes.mqtt.stub.AndesMQTTAdminServiceStub; import org.wso2.carbon.andes.mqtt.stub.AndesMQTTAdminServiceStub;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.ServletConfig; import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*; import javax.ws.rs.*;
@ -105,7 +109,8 @@ public class MQTTManagementAdminServiceImpl implements MQTTManagementAdminServic
} }
return Response.status(Response.Status.OK).entity(topics).build(); return Response.status(Response.Status.OK).entity(topics).build();
} catch (RemoteException | AndesMQTTAdminServiceBrokerManagerAdminException e) { } catch (RemoteException | AndesMQTTAdminServiceBrokerManagerAdminException |
UserStoreException | MQTTConfigurationException e) {
String msg = "Error occurred at server side while fetching topic list."; String msg = "Error occurred at server side while fetching topic list.";
log.error(msg, e); log.error(msg, e);
return Response.serverError().entity( return Response.serverError().entity(
@ -118,28 +123,28 @@ public class MQTTManagementAdminServiceImpl implements MQTTManagementAdminServic
* *
* @param config the servlet configuration * @param config the servlet configuration
* @return an AndesAdminServiceStub * @return an AndesAdminServiceStub
* @throws AxisFault * @throws AxisFault, UserStoreException
*/ */
private static AndesMQTTAdminServiceStub getAndesMQTTAdminServiceStub(ServletConfig config) private static AndesMQTTAdminServiceStub getAndesMQTTAdminServiceStub(ServletConfig config)
throws AxisFault { throws AxisFault, UserStoreException, MQTTConfigurationException {
String hostName = System.getProperty("mqtt.broker.host"); String hostName = System.getProperty("mqtt.broker.host");
final String MQTT_ENDPOINT = System.getProperty("mqtt.broker.https.port"); String mqttPort = System.getProperty("mqtt.broker.https.port");
if (hostName == null) { if (hostName == null || mqttPort == null) {
hostName = System.getProperty("mqtt.broker.host"); throw new MQTTConfigurationException("MQTT hostname/port configuration is not available in system " +
"properties");
} }
String backendServerURL = "https://" + hostName + ":" + MQTT_ENDPOINT + String backendServerURL = "https://" + hostName + ":" + mqttPort +
"/services/AndesMQTTAdminService.AndesMQTTAdminServiceHttpsSoap11Endpoint/"; "/services/AndesMQTTAdminService.AndesMQTTAdminServiceHttpsSoap11Endpoint/";
ConfigurationContext configContext = ConfigurationContext configContext =
(ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); (ConfigurationContext) config.getServletContext().getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
AndesMQTTAdminServiceStub stub = new AndesMQTTAdminServiceStub(configContext, backendServerURL); AndesMQTTAdminServiceStub stub = new AndesMQTTAdminServiceStub(configContext, backendServerURL);
// TODO: Need to use JWT Authenticator instead of Basic Auth
HttpTransportProperties.Authenticator basicAuthentication = new HttpTransportProperties.Authenticator(); HttpTransportProperties.Authenticator basicAuthentication = new HttpTransportProperties.Authenticator();
basicAuthentication.setUsername("admin"); basicAuthentication.setUsername(MQTTMgtAPIUtils.getUserRealm().getRealmConfiguration().getAdminUserName());
basicAuthentication.setPassword("admin"); basicAuthentication.setPassword(MQTTMgtAPIUtils.getUserRealm().getRealmConfiguration().getAdminPassword());
stub._getServiceClient().getOptions().setProperty(HTTPConstants.AUTHENTICATE, basicAuthentication); stub._getServiceClient().getOptions().setProperty(HTTPConstants.AUTHENTICATE, basicAuthentication);
return stub; return stub;

@ -1,409 +0,0 @@
/*
* Copyright (c) 2014, 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.andes.extensions.device.mgt.jaxrs.service.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans.TopicPaginationRequest;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
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.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
import org.wso2.carbon.device.mgt.core.operation.mgt.util.DeviceIDHolder;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.user.api.TenantManager;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService;
import org.wso2.carbon.utils.NetworkUtils;
import javax.sql.DataSource;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.*;
public final class TopicManagerUtil {
private static final Log log = LogFactory.getLog(DeviceManagerUtil.class);
public static Document convertToDocument(File file) throws DeviceManagementException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
DocumentBuilder docBuilder = factory.newDocumentBuilder();
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
return docBuilder.parse(file);
} catch (Exception e) {
throw new DeviceManagementException("Error occurred while parsing file, while converting " +
"to a org.w3c.dom.Document", e);
}
}
/**
* Resolve data source from the data source definition.
*
* @param config data source configuration
* @return data source resolved from the data source definition
*/
public static DataSource resolveDataSource(DataSourceConfig config) {
DataSource dataSource = null;
if (config == null) {
throw new RuntimeException("Device Management Repository data source configuration is null and thus, " +
"is not initialized");
}
JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition();
if (jndiConfig != null) {
if (log.isDebugEnabled()) {
log.debug("Initializing Device Management Repository data source using the JNDI Lookup Definition");
}
List<JNDILookupDefinition.JNDIProperty> jndiPropertyList =
jndiConfig.getJndiProperties();
if (jndiPropertyList != null) {
Hashtable<Object, Object> jndiProperties = new Hashtable<Object, Object>();
for (JNDILookupDefinition.JNDIProperty prop : jndiPropertyList) {
jndiProperties.put(prop.getName(), prop.getValue());
}
dataSource = DeviceManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), jndiProperties);
} else {
dataSource = DeviceManagementDAOUtil.lookupDataSource(jndiConfig.getJndiName(), null);
}
}
return dataSource;
}
/**
* Adds a new device type to the database if it does not exists.
*
* @param typeName device type
* @param tenantId provider tenant Id
* @param isSharedWithAllTenants is this device type shared with all tenants.
* @return status of the operation
*/
public static boolean registerDeviceType(String typeName, int tenantId, boolean isSharedWithAllTenants)
throws DeviceManagementException {
boolean status;
try {
DeviceManagementDAOFactory.beginTransaction();
DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
DeviceType deviceType = deviceTypeDAO.getDeviceType(typeName, tenantId);
if (deviceType == null) {
deviceType = new DeviceType();
deviceType.setName(typeName);
deviceTypeDAO.addDeviceType(deviceType, tenantId, isSharedWithAllTenants);
}
DeviceManagementDAOFactory.commitTransaction();
status = true;
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while registering the device type '"
+ typeName + "'", e);
} catch (TransactionManagementException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("SQL occurred while registering the device type '"
+ typeName + "'", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
return status;
}
/**
* Un-registers an existing device type from the device management metadata repository.
*
* @param typeName device type
* @return status of the operation
*/
public static boolean unregisterDeviceType(String typeName, int tenantId) throws DeviceManagementException {
try {
DeviceManagementDAOFactory.beginTransaction();
DeviceTypeDAO deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
DeviceType deviceType = deviceTypeDAO.getDeviceType(typeName, tenantId);
if (deviceType != null) {
deviceTypeDAO.removeDeviceType(typeName, tenantId);
}
DeviceManagementDAOFactory.commitTransaction();
return true;
} catch (DeviceManagementDAOException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("Error occurred while registering the device type '" +
typeName + "'", e);
} catch (TransactionManagementException e) {
DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceManagementException("SQL occurred while registering the device type '" +
typeName + "'", e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
public static Map<String, String> convertDevicePropertiesToMap(List<Device.Property> properties) {
Map<String, String> propertiesMap = new HashMap<String, String>();
for (Device.Property prop : properties) {
propertiesMap.put(prop.getName(), prop.getValue());
}
return propertiesMap;
}
public static List<DeviceIdentifier> convertDevices(List<Device> devices) {
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
for (Device device : devices) {
DeviceIdentifier identifier = new DeviceIdentifier();
identifier.setId(device.getDeviceIdentifier());
identifier.setType(device.getType());
deviceIdentifiers.add(identifier);
}
return deviceIdentifiers;
}
public static List<DeviceIdentifier> getValidDeviceIdentifiers(List<Device> devices) {
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
for (Device device : devices) {
if (device.getEnrolmentInfo() != null) {
switch (device.getEnrolmentInfo().getStatus()) {
case BLOCKED:
case REMOVED:
case SUSPENDED:
break;
default:
DeviceIdentifier identifier = new DeviceIdentifier();
identifier.setId(device.getDeviceIdentifier());
identifier.setType(device.getType());
deviceIdentifiers.add(identifier);
}
}
}
return deviceIdentifiers;
}
public static String getServerBaseHttpsUrl() {
String hostName = "localhost";
try {
hostName = NetworkUtils.getMgtHostName();
} catch (Exception ignored) {
}
String mgtConsoleTransport = CarbonUtils.getManagementTransport();
ConfigurationContextService configContextService =
DeviceManagementDataHolder.getInstance().getConfigurationContextService();
int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
int httpsProxyPort =
CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
mgtConsoleTransport);
if (httpsProxyPort > 0) {
port = httpsProxyPort;
}
return "https://" + hostName + ":" + port;
}
public static String getServerBaseHttpUrl() {
String hostName = "localhost";
try {
hostName = NetworkUtils.getMgtHostName();
} catch (Exception ignored) {
}
ConfigurationContextService configContextService =
DeviceManagementDataHolder.getInstance().getConfigurationContextService();
int port = CarbonUtils.getTransportPort(configContextService, "http");
int httpProxyPort =
CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(),
"http");
if (httpProxyPort > 0) {
port = httpProxyPort;
}
return "http://" + hostName + ":" + port;
}
/**
* returns the tenant Id of the specific tenant Domain
*
* @param tenantDomain
* @return
* @throws DeviceManagementException
*/
public static int getTenantId(String tenantDomain) throws DeviceManagementException {
try {
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
return MultitenantConstants.SUPER_TENANT_ID;
}
TenantManager tenantManager = DeviceManagementDataHolder.getInstance().getTenantManager();
int tenantId = tenantManager.getTenantId(tenantDomain);
if (tenantId == -1) {
throw new DeviceManagementException("invalid tenant Domain :" + tenantDomain);
}
return tenantId;
} catch (UserStoreException e) {
throw new DeviceManagementException("invalid tenant Domain :" + tenantDomain);
}
}
public static int validateActivityListPageSize(int limit) throws OperationManagementException {
if (limit == 0) {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig();
if (deviceManagementConfig != null) {
return deviceManagementConfig.getPaginationConfiguration().getActivityListPageSize();
} else {
throw new OperationManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
}
}
return limit;
}
public static PaginationRequest validateOperationListPageSize(PaginationRequest paginationRequest) throws
OperationManagementException {
if (paginationRequest.getRowCount() == 0) {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig();
if (deviceManagementConfig != null) {
paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration().
getOperationListPageSize());
} else {
throw new OperationManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
}
}
return paginationRequest;
}
public static PaginationRequest validateNotificationListPageSize(PaginationRequest paginationRequest) throws
NotificationManagementException {
if (paginationRequest.getRowCount() == 0) {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig();
if (deviceManagementConfig != null) {
paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration().
getNotificationListPageSize());
} else {
throw new NotificationManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
}
}
return paginationRequest;
}
public static TopicPaginationRequest validateTopicListPageSize(TopicPaginationRequest paginationRequest) throws
DeviceManagementException {
if (paginationRequest.getRowCount() == 0) {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig();
if (deviceManagementConfig != null) {
paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration().
getTopicListPageSize());
} else {
throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
}
}
return paginationRequest;
}
public static GroupPaginationRequest validateGroupListPageSize(GroupPaginationRequest paginationRequest) throws
GroupManagementException {
if (paginationRequest.getRowCount() == 0) {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance()
.getDeviceManagementConfig();
if (deviceManagementConfig != null) {
paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration()
.getDeviceListPageSize());
} else {
throw new GroupManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
}
}
return paginationRequest;
}
public static int validateDeviceListPageSize(int limit) throws DeviceManagementException {
if (limit == 0) {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig();
if (deviceManagementConfig != null) {
return deviceManagementConfig.getPaginationConfiguration().getDeviceListPageSize();
} else {
throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " +
"cdm-config.xml file.");
}
}
return limit;
}
public static DeviceIDHolder validateDeviceIdentifiers(List<DeviceIdentifier> deviceIDs) {
List<String> errorDeviceIdList = new ArrayList<String>();
List<DeviceIdentifier> validDeviceIDList = new ArrayList<DeviceIdentifier>();
int deviceIDCounter = 0;
for (DeviceIdentifier deviceIdentifier : deviceIDs) {
deviceIDCounter++;
String deviceID = deviceIdentifier.getId();
if (deviceID == null || deviceID.isEmpty()) {
errorDeviceIdList.add(String.format(OperationMgtConstants.DeviceConstants.DEVICE_ID_NOT_FOUND,
deviceIDCounter));
continue;
}
try {
if (isValidDeviceIdentifier(deviceIdentifier)) {
validDeviceIDList.add(deviceIdentifier);
} else {
errorDeviceIdList.add(deviceID);
}
} catch (DeviceManagementException e) {
errorDeviceIdList.add(deviceID);
}
}
DeviceIDHolder deviceIDHolder = new DeviceIDHolder();
deviceIDHolder.setValidDeviceIDList(validDeviceIDList);
deviceIDHolder.setErrorDeviceIdList(errorDeviceIdList);
return deviceIDHolder;
}
public static boolean isValidDeviceIdentifier(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier);
if (device == null || device.getDeviceIdentifier() == null ||
device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null) {
return false;
} else if (EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())) {
return false;
}
return true;
}
}

@ -16,7 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.andes.extensions.device.mgt.jaxrs.service.impl.util; package org.wso2.carbon.andes.extensions.device.mgt.jaxrs.util;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans.ErrorResponse;

@ -20,31 +20,16 @@ package org.wso2.carbon.andes.extensions.device.mgt.jaxrs.util;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
//import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService; //import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.user.api.AuthorizationManager; import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.api.UserRealm; import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import java.util.List;
/** /**
* MDMAPIUtils class provides utility function used by CDM REST-API classes. * MDMAPIUtils class provides utility function used by CDM REST-API classes.

@ -16,7 +16,7 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.andes.extensions.device.mgt.jaxrs.service.impl.util; package org.wso2.carbon.andes.extensions.device.mgt.jaxrs.util;
import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans.*; import org.wso2.carbon.andes.extensions.device.mgt.jaxrs.beans.*;

@ -37,10 +37,6 @@
<bean id="swaggerWriter" class="io.swagger.jaxrs.listing.SwaggerSerializers"/> <bean id="swaggerWriter" class="io.swagger.jaxrs.listing.SwaggerSerializers"/>
<bean id="swaggerResource" class="io.swagger.jaxrs.listing.ApiListingResource"/> <bean id="swaggerResource" class="io.swagger.jaxrs.listing.ApiListingResource"/>
<bean id="ValidationInterceptor"
class="org.wso2.carbon.andes.extensions.device.mgt.jaxrs.exception.ValidationInterceptor"/>
<bean id="GlobalExceptionMapper"
class="org.wso2.carbon.andes.extensions.device.mgt.jaxrs.exception.GlobalThrowableMapper"/>
<bean id="swaggerConfig" class="io.swagger.jaxrs.config.BeanConfig"> <bean id="swaggerConfig" class="io.swagger.jaxrs.config.BeanConfig">
<property name="resourcePackage" value="org.wso2.carbon.device.mgt.jaxrs"/> <property name="resourcePackage" value="org.wso2.carbon.device.mgt.jaxrs"/>
@ -56,7 +52,7 @@
</bean> </bean>
<bean id="mqttManagementService" <bean id="mqttManagementService"
class="org.wso2.carbon.andes.extensions.device.mgt.jaxrs.service.impl.admin.MQTTManagementAdminServiceImpl"/> class="org.wso2.carbon.andes.extensions.device.mgt.jaxrs.service.impl.MQTTManagementAdminServiceImpl"/>
<bean id="jsonProvider" class="org.wso2.carbon.andes.extensions.device.mgt.jaxrs.common.GsonMessageBodyHandler"/> <bean id="jsonProvider" class="org.wso2.carbon.andes.extensions.device.mgt.jaxrs.common.GsonMessageBodyHandler"/>
<cxf:bus> <cxf:bus>

@ -24,7 +24,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>extensions-feature</artifactId> <artifactId>extensions-feature</artifactId>
<version>4.0.2-SNAPSHOT</version> <version>4.0.73-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

@ -1157,7 +1157,7 @@
<javax.ws.rs.version>1.1.1</javax.ws.rs.version> <javax.ws.rs.version>1.1.1</javax.ws.rs.version>
<!-- Carbon Device Management --> <!-- Carbon Device Management -->
<carbon.devicemgt.version>3.0.75</carbon.devicemgt.version> <carbon.devicemgt.version>3.0.107-SNAPSHOT</carbon.devicemgt.version>
<carbon.devicemgt.version.range>[3.0.0, 4.0.0)</carbon.devicemgt.version.range> <carbon.devicemgt.version.range>[3.0.0, 4.0.0)</carbon.devicemgt.version.range>
<!-- Carbon App Management --> <!-- Carbon App Management -->

Loading…
Cancel
Save