Merge branch 'master' of ssh://repository.entgra.net:222/community/device-mgt-core

app-icon-change
kavindya_devindi 2 years ago
commit ed81c55380

@ -22,7 +22,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>grafana-mgt</artifactId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>grafana-mgt</artifactId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>grafana-mgt</artifactId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -68,8 +68,23 @@ public class GrafanaQueryServiceImpl implements GrafanaQueryService {
int datasourceId = datasourceIdJson.getAsInt();
CacheManager cacheManager = CacheManager.getInstance();
String encodedQuery = cacheManager.getEncodedQueryCache().getIfPresent(rawSql);
if (cacheManager.getEncodedQueryCache().getIfPresent(rawSql) != null) {
queryObj.addProperty(GrafanaConstants.RAW_SQL_KEY, encodedQuery);
if (encodedQuery != null && !encodedQuery.isEmpty()) {
// Checks if the tenant ID in the cached query (encodedQuery) is matching the current tenant ID
// taken from Carbon Context and if it's not matching then the query is modified with the current
// tenant ID and then added to the cache
if (encodedQuery.contains(GrafanaConstants.ENCODED_QUERY_TENANT_ID_KEY)) {
String encodedQueryTenantId = GrafanaPreparedQueryBuilder.getEncodedQueryTenantId(encodedQuery);
boolean isMatchingTenantId = GrafanaPreparedQueryBuilder.isMatchingTenantId(encodedQueryTenantId);
if (isMatchingTenantId) {
queryObj.addProperty(GrafanaConstants.RAW_SQL_KEY, encodedQuery);
} else {
String modifiedEncodedQuery = GrafanaPreparedQueryBuilder.modifyEncodedQuery(encodedQuery);
CacheManager.getInstance().getEncodedQueryCache().put(rawSql, modifiedEncodedQuery);
queryObj.addProperty(GrafanaConstants.RAW_SQL_KEY, modifiedEncodedQuery);
}
} else {
queryObj.addProperty(GrafanaConstants.RAW_SQL_KEY, encodedQuery);
}
return;
}
Datasource datasource = cacheManager.getDatasourceAPICache().getIfPresent(datasourceId);

@ -38,6 +38,7 @@ public class GrafanaPreparedQueryBuilder {
private static final String VAR_PARAM_TEMPLATE = "$param";
private static final String GRAFANA_QUOTED_VAR_REGEX = "('\\$(\\d|\\w|_)+')|('\\$\\{.*?\\}')|(\"\\$(\\d|\\w|_)+\")|(\"\\$\\{.*?\\}\")";
private static final String GRAFANA_VAR_REGEX = "(\\$(\\d|\\w|_)+)|(\\$\\{.*?\\})";
private static final String ENCODED_QUERY_TENANT_ID_REGEX = "TENANT_ID\\s=\\s('[^']+'|-?[1-9]\\d*|0)";
public static PreparedQuery build(String queryTemplate, String rawQuery) throws QueryMisMatch {
@ -125,6 +126,60 @@ public class GrafanaPreparedQueryBuilder {
return new PreparedQuery(preparedQueryBuilder.toString(), parameters);
}
/**
* Get the tenant ID used in the cached query with the matching regex pattern which are integers that
* may or may not have surrounding single quotes and could have a minus sign (e.g., '-1234')
* @param encodedQuery the cached query
* @return returns the tenant ID extracted from the cached query
*/
public static String getEncodedQueryTenantId(String encodedQuery) {
Pattern pattern = Pattern.compile(ENCODED_QUERY_TENANT_ID_REGEX);
Matcher matcher = pattern.matcher(encodedQuery);
String encodedQueryTenantId = "";
while (matcher.find()) {
encodedQueryTenantId = matcher.group(1);
if (encodedQueryTenantId != null && !encodedQueryTenantId.isEmpty()) {
break;
}
}
return unQuoteString(encodedQueryTenantId);
}
/**
* Checks if passed tenant ID is matching with tenant ID from Carbon Context
* @param encodedQueryTenantId the tenant ID
* @return true if tenant IDs match otherwise false
*/
public static boolean isMatchingTenantId(String encodedQueryTenantId) {
if (encodedQueryTenantId != null && !encodedQueryTenantId.isEmpty()) {
return GrafanaUtil.getTenantId() == Integer.parseInt(encodedQueryTenantId);
}
return false;
}
/**
* Modify the tenant ID used in the cached query to the current tenant ID taken from Carbon Context
* with the matching regex pattern which are integers that may or may not have surrounding single quotes and
* could have a minus sign (e.g., '-1234')
* @param encodedQuery the cached query
* @return returns the modified query with the current tenant ID
*/
public static String modifyEncodedQuery(String encodedQuery) {
Pattern pattern = Pattern.compile(ENCODED_QUERY_TENANT_ID_REGEX);
Matcher matcher = pattern.matcher(encodedQuery);
StringBuffer stringBuffer = new StringBuffer(encodedQuery.length());
String encodedQueryTenantId = "";
while (matcher.find()) {
encodedQueryTenantId = matcher.group(1);
if (encodedQueryTenantId != null && !encodedQueryTenantId.isEmpty()) {
matcher.appendReplacement(stringBuffer, Matcher.quoteReplacement(
GrafanaConstants.ENCODED_QUERY_TENANT_ID_KEY + " " + GrafanaUtil.getTenantId()));
}
}
matcher.appendTail(stringBuffer);
return stringBuffer.toString();
}
private static String[] splitByComma(String str) {
// Using regex to avoid splitting by comma inside quotes
return str.split("(\\s|\\t)*,(\\s|\\t)*(?=(?:[^'\"]*['|\"][^'\"]*['|\"])*[^'\"]*$)");
@ -194,5 +249,4 @@ public class GrafanaPreparedQueryBuilder {
private static String singleQuoteString(String str) {
return "'" + str + "'";
}
}

@ -39,6 +39,7 @@ public class GrafanaConstants {
public static final int IFRAME_URL_DASHBOARD_UID_INDEX = 1;
public static final String TENANT_ID_VAR_NAME = "tenantId";
public static final String ENCODED_QUERY_TENANT_ID_KEY = "TENANT_ID =";
public static final String VAR_PREFIX = "$";
public static final String TENANT_ID_VAR = VAR_PREFIX + TENANT_ID_VAR_NAME;
public static final String QUERY_PARAM_VAR_PREFIX = "var-";

@ -22,7 +22,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>analytics-mgt</artifactId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -3,7 +3,7 @@
<parent>
<artifactId>carbon-devicemgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>

@ -0,0 +1,119 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
~
~ Entgra (Pvt) Ltd. 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.25-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>io.entgra.device.mgt.core.apimgt.analytics.extension</artifactId>
<packaging>bundle</packaging>
<name>Entgra - API mgt analytics extension</name>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/Abstract*</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>API Management Application Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.apimgt.application.extension.internal</Private-Package>
<Import-Packages>
io.entgra.device.mgt.core.apimgt.analytics.extension.dto,
org.apache.velocity,
org.apache.velocity.app,
org.apache.velocity.context,
org.wso2.carbon.utils;version="[4.6,5)"
</Import-Packages>
<Export-Package>
io.entgra.device.mgt.core.apimgt.analytics.extension.*
</Export-Package>
<Embed-Dependency>
scribe;scope=compile|runtime;inline=false;
</Embed-Dependency>
</instructions>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,176 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.analytics.extension;
import io.entgra.device.mgt.core.apimgt.analytics.extension.dto.EventPublisherData;
import io.entgra.device.mgt.core.apimgt.analytics.extension.dto.EventReceiverData;
import io.entgra.device.mgt.core.apimgt.analytics.extension.dto.EventStreamData;
import io.entgra.device.mgt.core.apimgt.analytics.extension.dto.MetaData;
import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventPublisherDeployerException;
import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventReceiverDeployerException;
import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventStreamDeployerException;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
public class AnalyticsArtifactsDeployer {
public static final String TEMPLATE_LOCATION = "repository" + File.separator + "resources" + File.separator + "iot-analytics-templates";
public static final String EVENT_STREAM_LOCATION = "eventstreams";
public static final String EVENT_PUBLISHER_LOCATION = "eventpublishers";
public static final String EVENT_RECEIVER_LOCATION = "eventreceivers";
public static final String EVENT_STREAM_TEMPLATE = TEMPLATE_LOCATION + File.separator + "event_stream.json.template";
public static final String EVENT_PUBLISHER_TEMPLATE = TEMPLATE_LOCATION + File.separator + "event_publisher.xml.template";
public static final String EVENT_RECEIVER_TEMPLATE = TEMPLATE_LOCATION + File.separator + "event_receiver.xml.template";
public void deployEventStream(EventStreamData eventStreamData, int tenantId) throws EventStreamDeployerException {
try {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
ve.init();
Template template = ve.getTemplate(EVENT_STREAM_TEMPLATE);
VelocityContext context = populateContextForEventStreams(eventStreamData);
StringWriter writer = new StringWriter();
template.merge(context, writer);
String fileName = eventStreamData.getName() + "_" + eventStreamData.getVersion() + ".json";
String fileLocation = null;
if (MultitenantConstants.SUPER_TENANT_ID == tenantId) {
fileLocation = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "deployment"
+ File.separator + "server" + File.separator + EVENT_STREAM_LOCATION + File.separator + fileName;
} else {
fileLocation = CarbonUtils.getCarbonTenantsDirPath() + File.separator + tenantId + File.separator
+ EVENT_STREAM_LOCATION + File.separator + fileName;
}
PrintWriter printWriter = new PrintWriter(fileLocation, "UTF-8");
printWriter.println(writer.toString());
printWriter.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
throw new EventStreamDeployerException("Error while persisting event stream definition ", e);
}
}
public void deployEventPublisher(EventPublisherData eventPublisherData, int tenantId) throws EventPublisherDeployerException {
try {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
ve.init();
Template template = ve.getTemplate(EVENT_PUBLISHER_TEMPLATE);
VelocityContext context = populateContextForEventPublisher(eventPublisherData);
StringWriter writer = new StringWriter();
template.merge(context, writer);
String fileName = eventPublisherData.getName() + ".xml";
String fileLocation = null;
if (MultitenantConstants.SUPER_TENANT_ID == tenantId) {
fileLocation = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "deployment"
+ File.separator + "server" + File.separator + EVENT_PUBLISHER_LOCATION + File.separator + fileName;
} else {
fileLocation = CarbonUtils.getCarbonTenantsDirPath() + File.separator + tenantId + File.separator
+ EVENT_PUBLISHER_LOCATION + File.separator + fileName;
}
PrintWriter printWriter = new PrintWriter(fileLocation, "UTF-8");
printWriter.println(writer.toString());
printWriter.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
throw new EventPublisherDeployerException("Error while persisting rdbms event publisher ", e);
}
}
public void deployEventReceiver(EventReceiverData eventReceiverData, int tenantId) throws EventReceiverDeployerException {
try {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
ve.init();
Template template = ve.getTemplate(EVENT_RECEIVER_TEMPLATE);
VelocityContext context = populateContextForEventReceiver(eventReceiverData);
StringWriter writer = new StringWriter();
template.merge(context, writer);
String fileName = eventReceiverData.getName() + ".xml";
String fileLocation = null;
if (MultitenantConstants.SUPER_TENANT_ID == tenantId) {
fileLocation = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "deployment"
+ File.separator + "server" + File.separator + EVENT_RECEIVER_LOCATION + File.separator + fileName;
} else {
fileLocation = CarbonUtils.getCarbonTenantsDirPath() + File.separator + tenantId + File.separator
+ EVENT_RECEIVER_LOCATION + File.separator + fileName;
}
PrintWriter printWriter = new PrintWriter(fileLocation, "UTF-8");
printWriter.println(writer.toString());
printWriter.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
throw new EventReceiverDeployerException("Error while persisting oauth mqtt event receiver ", e);
}
}
private VelocityContext populateContextForEventStreams(EventStreamData eventStreamData) {
VelocityContext context = new VelocityContext();
context.put("name", eventStreamData.getName());
context.put("version", eventStreamData.getVersion());
context.put("metaData",
eventStreamData.getMetaData() != null ? eventStreamData.getMetaData() : new MetaData("deviceId", "STRING"));
if (eventStreamData.getPayloadData() != null) {
context.put("properties", eventStreamData.getPayloadData());
}
return context;
}
private VelocityContext populateContextForEventPublisher(EventPublisherData eventPublisherData) {
VelocityContext context = new VelocityContext();
context.put("name", eventPublisherData.getName());
context.put("streamName", eventPublisherData.getStreamName());
context.put("streamVersion", eventPublisherData.getStreamVersion());
context.put("properties", eventPublisherData.getPropertyList());
context.put("eventAdapterType", eventPublisherData.getEventAdaptorType());
context.put("customMappingType", eventPublisherData.getCustomMappingType());
return context;
}
private VelocityContext populateContextForEventReceiver(EventReceiverData eventReceiverData) {
VelocityContext context = new VelocityContext();
context.put("name", eventReceiverData.getName());
context.put("streamName", eventReceiverData.getStreamName());
context.put("streamVersion", eventReceiverData.getStreamVersion());
context.put("properties", eventReceiverData.getPropertyList());
context.put("eventAdapterType", eventReceiverData.getEventAdapterType());
context.put("customMappingType", eventReceiverData.getCustomMappingType());
return context;
}
}

@ -0,0 +1,80 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.analytics.extension.dto;
import java.util.List;
public class EventPublisherData {
private String name;
private String streamVersion;
private String streamName;
private List<Property> propertyList;
private String eventAdaptorType;
private String customMappingType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreamVersion() {
return streamVersion;
}
public void setStreamVersion(String streamVersion) {
this.streamVersion = streamVersion;
}
public String getStreamName() {
return streamName;
}
public void setStreamName(String streamName) {
this.streamName = streamName;
}
public List<Property> getPropertyList() {
return propertyList;
}
public void setPropertyList(List<Property> propertyList) {
this.propertyList = propertyList;
}
public String getEventAdaptorType() {
return eventAdaptorType;
}
public void setEventAdaptorType(String eventAdaptorType) {
this.eventAdaptorType = eventAdaptorType;
}
public String getCustomMappingType() {
return customMappingType;
}
public void setCustomMappingType(String customMappingType) {
this.customMappingType = customMappingType;
}
}

@ -0,0 +1,81 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.analytics.extension.dto;
import java.util.List;
public class EventReceiverData {
private String name;
private String streamVersion;
private String streamName;
private String eventAdapterType;
List<Property> propertyList;
private String customMappingType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreamVersion() {
return streamVersion;
}
public void setStreamVersion(String streamVersion) {
this.streamVersion = streamVersion;
}
public String getStreamName() {
return streamName;
}
public void setStreamName(String streamName) {
this.streamName = streamName;
}
public String getEventAdapterType() {
return eventAdapterType;
}
public void setEventAdapterType(String eventAdapterType) {
this.eventAdapterType = eventAdapterType;
}
public List<Property> getPropertyList() {
return propertyList;
}
public void setPropertyList(List<Property> propertyList) {
this.propertyList = propertyList;
}
public String getCustomMappingType() {
return customMappingType;
}
public void setCustomMappingType(String customMappingType) {
this.customMappingType = customMappingType;
}
}

@ -0,0 +1,59 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.analytics.extension.dto;
import java.util.List;
public class EventStreamData {
private String name;
private String version;
private MetaData metaData;
private List<Property> payloadData;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public MetaData getMetaData() {
return metaData;
}
public void setMetaData(MetaData metaData) {
this.metaData = metaData;
}
public List<Property> getPayloadData() {
return payloadData;
}
public void setPayloadData(List<Property> payloadData) {
this.payloadData = payloadData;
}
}

@ -0,0 +1,44 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.analytics.extension.dto;
public class MetaData {
String name;
String type;
public MetaData(String name, String type){
this.setName(name);
this.setType(type);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}

@ -0,0 +1,45 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.analytics.extension.dto;
public class Property {
String name;
String value;
public Property(String name, String value){
this.setName(name);
this.setValue(value);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

@ -0,0 +1,43 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.analytics.extension.exception;
public class EventPublisherDeployerException extends Exception {
private static final long serialVersionUID = -3151279311929070299L;
public EventPublisherDeployerException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public EventPublisherDeployerException(String message, Throwable cause) {
super(message, cause);
}
public EventPublisherDeployerException(String msg) {
super(msg);
}
public EventPublisherDeployerException() {
super();
}
public EventPublisherDeployerException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,43 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.analytics.extension.exception;
public class EventReceiverDeployerException extends Exception {
private static final long serialVersionUID = -3151279311929070299L;
public EventReceiverDeployerException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public EventReceiverDeployerException(String message, Throwable cause) {
super(message, cause);
}
public EventReceiverDeployerException(String msg) {
super(msg);
}
public EventReceiverDeployerException() {
super();
}
public EventReceiverDeployerException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,43 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 io.entgra.device.mgt.core.apimgt.analytics.extension.exception;
public class EventStreamDeployerException extends Exception {
private static final long serialVersionUID = -3151279311929070298L;
public EventStreamDeployerException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public EventStreamDeployerException(String message, Throwable cause) {
super(message, cause);
}
public EventStreamDeployerException(String msg) {
super(msg);
}
public EventStreamDeployerException() {
super();
}
public EventStreamDeployerException(Throwable cause) {
super(cause);
}
}

@ -22,7 +22,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -21,7 +21,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -104,7 +104,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
if (StringUtils.isEmpty(username)) {
username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername() + "@" + tenantDomain;
}
try {
APIConsumer apiConsumer = API_MANAGER_FACTORY.getAPIConsumer(username);
@ -256,10 +256,14 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
keyManagerId = keyManagerConfigurationDTO.getUuid();
}
}
String applicationAccessTokenExpiryTime = "N/A";
if (!StringUtils.isEmpty(validityTime)) {
applicationAccessTokenExpiryTime = validityTime;
}
String jsonString = "{\"grant_types\":\"refresh_token,access_token," +
"urn:ietf:params:oauth:grant-type:saml2-bearer," +
"password,client_credentials,iwa:ntlm,urn:ietf:params:oauth:grant-type:jwt-bearer\"," +
"\"additionalProperties\":\"{\\\"application_access_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\"additionalProperties\":\"{\\\"application_access_token_expiry_time\\\":\\\"" + applicationAccessTokenExpiryTime + "\\\"," +
"\\\"user_access_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"refresh_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"id_token_expiry_time\\\":\\\"N\\/A\\\"}\"," +

@ -3,7 +3,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

@ -40,6 +40,9 @@ public class DCRRequest {
@XmlElement
private boolean isSaasApp;
@XmlElement
private int validityPeriod;
public String getApplicationName() {
return applicationName;
}
@ -87,4 +90,12 @@ public class DCRRequest {
public void setIsSaasApp(boolean saasApp) {
isSaasApp = saasApp;
}
public int getValidityPeriod() {
return validityPeriod;
}
public void setValidityPeriod(int validityPeriod) {
this.validityPeriod = validityPeriod;
}
}

@ -46,5 +46,6 @@ public interface KeyManagerService {
@FormParam("assertion") String assertion,
@FormParam("admin_access_token") String admin_access_token,
@FormParam("username") String username,
@FormParam("password") String password);
@FormParam("password") String password,
@FormParam("validityPeriod") int validityPeriod);
}

@ -51,7 +51,7 @@ public class KeyManagerServiceImpl implements KeyManagerService {
try {
KeyMgtService keyMgtService = new KeyMgtServiceImpl();
DCRResponse resp = keyMgtService.dynamicClientRegistration(dcrRequest.getApplicationName(), dcrRequest.getUsername(),
dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), dcrRequest.getIsSaasApp());
dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), dcrRequest.getIsSaasApp(), dcrRequest.getValidityPeriod());
return Response.status(Response.Status.CREATED).entity(gson.toJson(resp)).build();
} catch (KeyMgtException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
@ -69,7 +69,8 @@ public class KeyManagerServiceImpl implements KeyManagerService {
@FormParam("assertion") String assertion,
@FormParam("admin_access_token") String admin_access_token,
@FormParam("username") String username,
@FormParam("password") String password) {
@FormParam("password") String password,
@FormParam("validityPeriod") int validityPeriod) {
try {
if (basicAuthHeader == null) {
String msg = "Invalid credentials. Make sure your API call is invoked with a Basic Authorization header.";
@ -80,7 +81,7 @@ public class KeyManagerServiceImpl implements KeyManagerService {
TokenResponse resp = keyMgtService.generateAccessToken(
new TokenRequest(encodedClientCredentials.split(":")[0],
encodedClientCredentials.split(":")[1], refreshToken, scope,
grantType, assertion, admin_access_token, username, password));
grantType, assertion, admin_access_token, username, password, validityPeriod));
return Response.status(Response.Status.OK).entity(gson.toJson(resp)).build();
} catch (KeyMgtException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();

@ -3,7 +3,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -29,8 +29,10 @@ public class TokenRequest {
private String username;
private String password;
private int validityPeriod;
public TokenRequest(String clientId, String clientSecret, String refreshToken, String scope, String grantType,
String assertion, String admin_access_token, String username, String password) {
String assertion, String admin_access_token, String username, String password, int validityPeriod) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.refreshToken = refreshToken;
@ -40,6 +42,7 @@ public class TokenRequest {
this.admin_access_token = admin_access_token;
this.username = username;
this.password = password;
this.validityPeriod = validityPeriod;
}
public String getClientId() {
@ -113,4 +116,12 @@ public class TokenRequest {
public void setPassword(String password) {
this.password = password;
}
public int getValidityPeriod() {
return validityPeriod;
}
public void setValidityPeriod(int validityPeriod) {
this.validityPeriod = validityPeriod;
}
}

@ -39,7 +39,7 @@ public interface KeyMgtService {
* @throws KeyMgtException if any error occurs during DCR process
*/
DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl,
String[] tags, boolean isSaasApp) throws KeyMgtException;
String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException;
/***
* This method will handle the access token requests

@ -77,7 +77,7 @@ public class KeyMgtServiceImpl implements KeyMgtService {
String subTenantUserUsername, subTenantUserPassword, keyManagerName, msg = null;
public DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl,
String[] tags, boolean isSaasApp) throws KeyMgtException {
String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException {
if (owner == null) {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
@ -105,13 +105,13 @@ public class KeyMgtServiceImpl implements KeyMgtService {
kmConfig = getKeyManagerConfig();
if (KeyMgtConstants.SUPER_TENANT.equals(tenantDomain)) {
OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags);
OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags, validityPeriod);
return new DCRResponse(dcrApplication.getClientId(), dcrApplication.getClientSecret());
} else {
// super-tenant admin dcr and token generation
OAuthApplication superTenantOauthApp = createOauthApplication(
KeyMgtConstants.RESERVED_OAUTH_APP_NAME_PREFIX + KeyMgtConstants.SUPER_TENANT,
kmConfig.getAdminUsername(), null);
kmConfig.getAdminUsername(), null, validityPeriod);
String superAdminAccessToken = createAccessToken(superTenantOauthApp);
// create new key manager for the tenant, under super-tenant space
@ -133,7 +133,7 @@ public class KeyMgtServiceImpl implements KeyMgtService {
createUserIfNotExists(subTenantUserUsername, subTenantUserPassword);
// DCR for the requesting user
OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags);
OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags, validityPeriod);
String requestingUserAccessToken = createAccessToken(dcrApplication);
// get application id
@ -167,7 +167,8 @@ public class KeyMgtServiceImpl implements KeyMgtService {
case "client_credentials":
appTokenPayload = new FormBody.Builder()
.add("grant_type", "client_credentials")
.add("scope", tokenRequest.getScope()).build();
.add("scope", tokenRequest.getScope())
.add("validityPeriod", String.valueOf(tokenRequest.getValidityPeriod())).build();
break;
case "password":
appTokenPayload = new FormBody.Builder()
@ -322,8 +323,8 @@ public class KeyMgtServiceImpl implements KeyMgtService {
* @return @{@link OAuthApplication} OAuth application object
* @throws KeyMgtException if any error occurs while creating response object
*/
private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags) throws KeyMgtException {
String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags);
private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags, int validityPeriod) throws KeyMgtException {
String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags, validityPeriod);
RequestBody oauthAppCreationPayload = RequestBody.Companion.create(oauthAppCreationPayloadStr, JSON);
kmConfig = getKeyManagerConfig();
String dcrEndpoint = kmConfig.getServerUrl() + KeyMgtConstants.DCR_ENDPOINT;
@ -442,11 +443,12 @@ public class KeyMgtServiceImpl implements KeyMgtService {
}
}
private String createOauthAppCreationPayload(String clientName, String owner, String[] tags) {
private String createOauthAppCreationPayload(String clientName, String owner, String[] tags, int validityPeriod) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("applicationName", clientName);
jsonObject.put("username", owner);
jsonObject.put("tags", tags);
jsonObject.put("validityPeriod", validityPeriod);
return jsonObject.toString();
}

@ -22,7 +22,7 @@
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
@ -39,6 +39,7 @@
<module>org.wso2.carbon.apimgt.annotations</module>
<module>org.wso2.carbon.apimgt.keymgt.extension</module>
<module>org.wso2.carbon.apimgt.keymgt.extension.api</module>
<module>io.entgra.device.mgt.core.apimgt.analytics.extension</module>
</modules>
<build>

@ -20,7 +20,7 @@
<parent>
<artifactId>application-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>application-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -21,7 +21,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>application-mgt</artifactId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -17,7 +17,7 @@
package io.entgra.application.mgt.common.services;
import io.entgra.application.mgt.common.ApplicationType;
import io.entgra.application.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.common.Base64File;
import io.entgra.application.mgt.common.dto.ApplicationDTO;
import io.entgra.application.mgt.common.exception.ResourceManagementException;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;

@ -22,6 +22,7 @@ import io.entgra.application.mgt.common.dto.ApplicationReleaseDTO;
import io.entgra.application.mgt.common.exception.ApplicationStorageManagementException;
import io.entgra.application.mgt.common.exception.RequestValidatingException;
import io.entgra.application.mgt.common.exception.ResourceManagementException;
import org.wso2.carbon.device.mgt.core.common.exception.StorageManagementException;
import java.io.InputStream;
import java.util.List;
@ -121,4 +122,14 @@ public interface ApplicationStorageManager {
* @throws ApplicationStorageManagementException throws if an error occurs when accessing the file.
*/
InputStream getFileStream(String deviceType, String tenantDomain) throws ApplicationStorageManagementException;
/**
* Useful to generate MD5 string of {@link InputStream}
*
* @param inputStream {@link InputStream}
* @return md5 string of provided input stream
*
* @throws StorageManagementException if errors while generating md5 string
*/
String getMD5(InputStream inputStream) throws StorageManagementException;
}

@ -16,7 +16,7 @@
*/
package io.entgra.application.mgt.common.wrapper;
import io.entgra.application.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.common.Base64File;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ -16,7 +16,7 @@
*/
package io.entgra.application.mgt.common.wrapper;
import io.entgra.application.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.common.Base64File;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ -16,7 +16,7 @@
*/
package io.entgra.application.mgt.common.wrapper;
import io.entgra.application.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.common.Base64File;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ -16,7 +16,7 @@
*/
package io.entgra.application.mgt.common.wrapper;
import io.entgra.application.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.common.Base64File;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ -21,7 +21,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>application-mgt</artifactId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -28,7 +28,7 @@ public class Artifacts {
private String imageLocation;
private String binaryLocation;
@XmlElement(name = "ImageLocation", required = true)
@XmlElement(name = "ImageLocationType", required = true)
public String getImageLocation() {
return imageLocation;
}

@ -17,7 +17,7 @@
package io.entgra.application.mgt.core.impl;
import io.entgra.application.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.common.Base64File;
import io.entgra.application.mgt.core.dao.SPApplicationDAO;
import io.entgra.application.mgt.core.util.ApplicationManagementUtil;
import org.apache.commons.codec.digest.DigestUtils;
@ -86,7 +86,7 @@ import io.entgra.application.mgt.core.internal.DataHolder;
import io.entgra.application.mgt.core.lifecycle.LifecycleStateManager;
import io.entgra.application.mgt.core.util.ConnectionManagerUtil;
import io.entgra.application.mgt.core.util.Constants;
import io.entgra.application.mgt.core.util.StorageManagementUtil;
import org.wso2.carbon.device.mgt.core.common.exception.StorageManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
@ -402,7 +402,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
*/
private void validateRemoveAppFromFavouritesRequest(int appId) throws ApplicationManagementException {
if (!isFavouriteApp(appId)) {
String msg = "Provided appId " + appId + " is not a favourite app in order remove from favourites";
String msg = "Provided application is not a favourite app in order remove from favourites";
throw new BadRequestException(msg);
}
}
@ -417,11 +417,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
try {
getApplication(appId);
} catch (NotFoundException e) {
String msg = " No application exists for the provided appId " + appId;
String msg = "Requested application does not exists for add to favourites.";
throw new BadRequestException(msg);
}
if (isFavouriteApp(appId)) {
String msg = "Provided appId " + appId + " is already a favourite app";
String msg = "Requested application is already in favourites list.";
throw new BadRequestException(msg);
}
}
@ -600,16 +600,17 @@ public class ApplicationManagerImpl implements ApplicationManager {
*/
private String generateMD5OfApp(ApplicationArtifact applicationArtifact, byte[] content) throws ApplicationManagementException {
try {
String md5OfApp = StorageManagementUtil.getMD5(new ByteArrayInputStream(content));
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
String md5OfApp = applicationStorageManager.getMD5(new ByteArrayInputStream(content));
if (md5OfApp == null) {
String msg = "Error occurred while generating md5sum value of " + applicationArtifact.getInstallerName();
log.error(msg);
throw new ApplicationManagementException(msg);
}
return md5OfApp;
} catch( ApplicationStorageManagementException e) {
} catch(StorageManagementException e) {
String msg = "Error occurred while generating md5sum value of " + applicationArtifact.getInstallerName();
log.error(msg);
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
}
}
@ -689,7 +690,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg);
throw new ApplicationManagementException(msg);
}
String md5OfApp = StorageManagementUtil.getMD5(new ByteArrayInputStream(content));
String md5OfApp = applicationStorageManager.getMD5(new ByteArrayInputStream(content));
if (md5OfApp == null) {
String msg = "Error occurred while md5sum value retrieving process: application UUID "
+ applicationReleaseDTO.getUuid();
@ -708,6 +709,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
applicationStorageManager
.uploadReleaseArtifact(applicationReleaseDTO, deviceType, binaryDuplicate, tenantId);
}
} catch (StorageManagementException e) {
String msg = "Error occurred while md5sum value retrieving process: application UUID "
+ applicationReleaseDTO.getUuid();
log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "Error occurred when getting database connection for verifying app release data.";
log.error(msg, e);
@ -752,7 +758,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream());
try (ByteArrayInputStream binaryClone = new ByteArrayInputStream(content)) {
String md5OfApp = StorageManagementUtil.getMD5(binaryClone);
String md5OfApp = applicationStorageManager.getMD5(binaryClone);
if (md5OfApp == null) {
String msg = "Error occurred while retrieving md5sum value from the binary file for application "
@ -818,6 +824,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
}
}
}
} catch (StorageManagementException e) {
String msg = "Error occurred while retrieving md5sum value from the binary file for application "
+ "release UUID " + applicationReleaseDTO.getUuid();
log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e);
} catch (IOException e) {
String msg = "Error occurred when getting byte array of binary file. Installer name: " + applicationArtifact
.getInstallerName();
@ -1494,7 +1505,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg = "Error occured when getting, either application tags or application categories";
String msg = "Error occurred when getting, either application tags or application categories";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
@ -1768,7 +1779,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (LifeCycleManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured while deleting life-cycle state data of application releases of the application"
String msg = "Error occurred while deleting life-cycle state data of application releases of the application"
+ " which has application ID: " + applicationDTO.getId();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@ -1885,7 +1896,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occurred while verifying whether application relase has an subscription or "
String msg = "Error occurred while verifying whether application release has an subscription or "
+ "not. Application release UUID: " + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@ -1934,7 +1945,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
ConnectionManagerUtil.commitDBTransaction();
} catch (DBConnectionException e) {
String msg =
"Error occured when getting DB connection to update image artifacts of the application release "
"Error occurred when getting DB connection to update image artifacts of the application release "
+ "which has uuid " + uuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@ -1946,13 +1957,13 @@ public class ApplicationManagerImpl implements ApplicationManager {
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg =
"Error occured while getting application release data for updating image artifacts of the application release uuid "
"Error occurred while getting application release data for updating image artifacts of the application release uuid "
+ uuid + ".";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ResourceManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured while updating image artifacts of the application release uuid " + uuid + ".";
String msg = "Error occurred while updating image artifacts of the application release uuid " + uuid + ".";
log.error(msg, e);
throw new ApplicationManagementException(msg , e);
} finally {
@ -1981,7 +1992,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new BadRequestException(msg);
}
} catch (DeviceManagementException e) {
String msg = "Error occured while getting supported device types in IoTS";
String msg = "Error occurred while getting supported device types in IoTS";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
}
@ -2023,16 +2034,16 @@ public class ApplicationManagerImpl implements ApplicationManager {
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured while getting/updating APPM DB for updating application Installer.";
String msg = "Error occurred while getting/updating APPM DB for updating application Installer.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (TransactionManagementException e) {
String msg = "Error occured while starting the transaction to update application release artifact which has "
String msg = "Error occurred while starting the transaction to update application release artifact which has "
+ "application uuid " + releaseUuid + ".";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "Error occured when getting DB connection to update application release artifact of the "
String msg = "Error occurred when getting DB connection to update application release artifact of the "
+ "application release uuid " + releaseUuid + ".";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@ -2043,7 +2054,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ResourceManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured when updating application installer.";
String msg = "Error occurred when updating application installer.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
@ -2162,9 +2173,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
ConnectionManagerUtil.closeDBConnection();
}
}
public ApplicationRelease changeLifecycleState(ApplicationReleaseDTO applicationReleaseDTO, LifecycleChanger lifecycleChanger) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (lifecycleChanger == null || StringUtils.isEmpty(lifecycleChanger.getAction())) {
@ -2172,7 +2183,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg);
throw new BadRequestException(msg);
}
try{
if (lifecycleStateManager
.isValidStateChange(applicationReleaseDTO.getCurrentState(), lifecycleChanger.getAction(), userName,
@ -2241,7 +2252,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured when getting existing categories or when inserting new application categories.";
String msg = "Error occurred when getting existing categories or when inserting new application categories.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
@ -2563,7 +2574,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
applicationDAO.deleteApplicationTag(tag.getId(), applicationDTO.getId(), tenantId);
ConnectionManagerUtil.commitDBTransaction();
} else {
String msg = "Tag " + tagName + " is not an application tag. Application ID: " + appId;
String msg = "Tag " + tagName + " is not an application tag. Application name: " + applicationDTO.getName();
log.error(msg);
throw new BadRequestException(msg);
}
@ -2771,7 +2782,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
.collect(Collectors.toList());
} else {
String msg = "Tag list is either null or empty. In order to add new tags for application which has "
+ "application ID: " + appId +", tag list should be a list of Stings. Therefore please "
+ "application name: " + applicationDTO.getName() +", tag list should be a list of Stings. Therefore please "
+ "verify the payload.";
log.error(msg);
throw new BadRequestException(msg);
@ -2877,11 +2888,17 @@ public class ApplicationManagerImpl implements ApplicationManager {
@Override
public void updateCategory(String oldCategoryName, String newCategoryName) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
if (StringUtils.isEmpty(oldCategoryName) || StringUtils.isEmpty(newCategoryName)) {
String msg = "Either old category name or new category name contains empty/null value. Hence please verify the "
+ "request.";
log.error(msg);
throw new BadRequestException(msg);
}
try {
ConnectionManagerUtil.beginDBTransaction();
CategoryDTO category = applicationDAO.getCategoryForCategoryName(oldCategoryName, tenantId);
if (category == null){
String msg = "Couldn't found a category for tag name " + oldCategoryName + ".";
String msg = "Couldn't found a category for category name " + oldCategoryName + ".";
log.error(msg);
throw new NotFoundException(msg);
}
@ -2893,7 +2910,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (TransactionManagementException e) {
String msg = "Database access error is occurred when updating categiry.";
String msg = "Database access error is occurred when updating category.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
@ -3068,11 +3085,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured when updating Ent Application release of UUID: " + releaseUuid;
String msg = "Error occurred when updating Ent Application release of UUID: " + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ResourceManagementException e) {
String msg = "Error occured when updating application release artifact in the file system. Ent App release "
String msg = "Error occurred when updating application release artifact in the file system. Ent App release "
+ "UUID:" + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@ -3137,11 +3154,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured when updating public app release of UUID: " + releaseUuid;
String msg = "Error occurred when updating public app release of UUID: " + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ResourceManagementException e) {
String msg = "Error occured when updating public app release artifact in the file system. Public app "
String msg = "Error occurred when updating public app release artifact in the file system. Public app "
+ "release UUID:" + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@ -3202,11 +3219,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured when updating web app release for web app Release UUID: " + releaseUuid;
String msg = "Error occurred when updating web app release for web app Release UUID: " + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ResourceManagementException e) {
String msg = "Error occured when updating web app release artifact in the file system. Web app "
String msg = "Error occurred when updating web app release artifact in the file system. Web app "
+ "release UUID:" + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@ -3254,7 +3271,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
try {
byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream());
try (ByteArrayInputStream binaryClone = new ByteArrayInputStream(content)) {
String md5OfApp = StorageManagementUtil.getMD5(binaryClone);
String md5OfApp = applicationStorageManager.getMD5(binaryClone);
if (md5OfApp == null) {
String msg = "Error occurred while retrieving md5sum value from the binary file for "
+ "application release UUID " + applicationReleaseDTO.get().getUuid();
@ -3300,6 +3317,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
}
}
}
} catch (StorageManagementException e) {
String msg = "Error occurred while retrieving md5sum value from the binary file for "
+ "application release UUID " + applicationReleaseDTO.get().getUuid();
log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e);
} catch (IOException e) {
String msg = "Error occurred when getting byte array of binary file. Installer name: "
+ applicationArtifact.getInstallerName();
@ -3327,11 +3349,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured when updating Ent Application release of UUID: " + releaseUuid;
String msg = "Error occurred when updating Ent Application release of UUID: " + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ResourceManagementException e) {
String msg = "Error occured when updating application release artifact in the file system. Ent App release "
String msg = "Error occurred when updating application release artifact in the file system. Ent App release "
+ "UUID:" + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@ -3705,7 +3727,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new BadRequestException(msg);
}
if (StringUtils.isEmpty(webAppReleaseWrapper.getUrl())) {
String msg = "URL should't be null for the application release creating request for application type "
String msg = "URL shouldn't be null for the application release creating request for application type "
+ "WEB_CLIP";
log.error(msg);
throw new BadRequestException(msg);
@ -3885,11 +3907,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
}
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
String msg = "Error occured while updating app subscription status of the device.";
String msg = "Error occurred while updating app subscription status of the device.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "Error occurred while obersving the database connection to update aoo subscription status of "
String msg = "Error occurred while observing the database connection to update aoo subscription status of "
+ "device.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@ -3916,11 +3938,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
}
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
String msg = "Error occured while updating app subscription status of the device.";
String msg = "Error occurred while updating app subscription status of the device.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "Error occurred while obersving the database connection to update aoo subscription status of "
String msg = "Error occurred while observing the database connection to update aoo subscription status of "
+ "device.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);

@ -19,6 +19,7 @@ package io.entgra.application.mgt.core.impl;
import com.dd.plist.NSDictionary;
import net.dongliu.apk.parser.bean.ApkMeta;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -31,12 +32,13 @@ import io.entgra.application.mgt.common.services.ApplicationStorageManager;
import io.entgra.application.mgt.core.exception.ParsingException;
import io.entgra.application.mgt.core.util.ArtifactsParser;
import io.entgra.application.mgt.core.util.Constants;
import io.entgra.application.mgt.core.util.StorageManagementUtil;
import org.wso2.carbon.device.mgt.core.common.exception.StorageManagementException;
import org.wso2.carbon.device.mgt.core.common.util.StorageManagementUtil;
import java.io.*;
import java.util.List;
import static io.entgra.application.mgt.core.util.StorageManagementUtil.saveFile;
import static org.wso2.carbon.device.mgt.core.common.util.StorageManagementUtil.saveFile;
/**
* This class contains the default concrete implementation of ApplicationStorage Management.
@ -112,6 +114,11 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
+ applicationReleaseDTO.getUuid();
log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e);
} catch (StorageManagementException e) {
String msg = "Error occurred while uploading image artifacts. UUID: "
+ applicationReleaseDTO.getUuid();
log.error(msg, e);
throw new ResourceManagementException(msg, e);
}
}
@ -159,6 +166,11 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
+ applicationReleaseDTO.getUuid();
log.error(msg, e);
throw new ResourceManagementException( msg, e);
} catch (StorageManagementException e) {
String msg = "Error occurred while uploading image artifacts. UUID: "
+ applicationReleaseDTO.getUuid();
log.error(msg, e);
throw new ResourceManagementException(msg, e);
}
}
@ -286,4 +298,15 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
throw new ApplicationStorageManagementException(msg);
}
}
@Override
public String getMD5(InputStream inputStream) throws StorageManagementException {
try {
return DigestUtils.md5Hex(inputStream);
} catch (IOException e) {
String msg = "IO Exception occurred while trying to get the md5sum value of application";
log.error(msg, e);
throw new StorageManagementException(msg, e);
}
}
}

@ -224,7 +224,7 @@ public class ReviewManagerImpl implements ReviewManager {
throw new ReviewManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured while verifying whether application release is exists or not for UUID " + uuid;
String msg = "Error occurred while verifying whether application release is exists or not for UUID " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} finally {
@ -360,7 +360,7 @@ public class ReviewManagerImpl implements ReviewManager {
return null;
} catch (ReviewManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured while getting reviewTmp with reviewTmp id " + reviewId + ".";
String msg = "Error occurred while getting reviewTmp with reviewTmp id " + reviewId + ".";
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (DBConnectionException e) {
@ -393,11 +393,11 @@ public class ReviewManagerImpl implements ReviewManager {
}
return getReviewTree(this.reviewDAO.getAllReleaseReviews(releaseDTO.getId(), request, tenantId));
} catch (ReviewManagementDAOException e) {
String msg = "Error occured while getting all reviews for application uuid: " + uuid;
String msg = "Error occurred while getting all reviews for application uuid: " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (DBConnectionException e) {
String msg ="Error occured while getting the DB connection to get all reviews for application release which"
String msg ="Error occurred while getting the DB connection to get all reviews for application release which"
+ " has UUID " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
@ -423,12 +423,12 @@ public class ReviewManagerImpl implements ReviewManager {
ConnectionManagerUtil.openDBConnection();
return getReviewTree(this.reviewDAO.getAllActiveAppReviews(applicationReleaseIds, request, tenantId));
} catch (ReviewManagementDAOException e) {
String msg = "Error occured while getting all reviews for application which has an "
String msg = "Error occurred while getting all reviews for application which has an "
+ "application release of uuid: " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "Error occured while getting the DB connection to get app app reviews.";
String msg = "Error occurred while getting the DB connection to get app app reviews.";
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} finally {
@ -458,12 +458,12 @@ public class ReviewManagerImpl implements ReviewManager {
}
return getReviewTree(reviewDtos);
} catch (ReviewManagementDAOException e) {
String msg = "Error occured while getting all " + username + "'s reviews for application which has an "
String msg = "Error occurred while getting all " + username + "'s reviews for application which has an "
+ "application release of uuid: " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "Error occured while getting DB connection to get all " + username + "'s reviews for "
String msg = "Error occurred while getting DB connection to get all " + username + "'s reviews for "
+ "application which has an application release of uuid: " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
@ -486,7 +486,7 @@ public class ReviewManagerImpl implements ReviewManager {
.collect(Collectors.toList());
} catch (DBConnectionException e) {
String msg =
"Error occured while getting the DB connection to get application which has application release"
"Error occurred while getting the DB connection to get application which has application release"
+ " of UUID: " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
@ -526,7 +526,7 @@ public class ReviewManagerImpl implements ReviewManager {
paginationResult.setRecordsTotal(numOfReviews);
return paginationResult;
} catch (ReviewManagementDAOException e) {
String msg = "Error occured while getting all reply comments for given review list";
String msg = "Error occurred while getting all reply comments for given review list";
log.error(msg, e);
throw new ReviewManagementException(msg, e);
}
@ -635,11 +635,11 @@ public class ReviewManagerImpl implements ReviewManager {
throw new ReviewManagementException(msg, e);
} catch (ReviewManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg = "Error occured while deleting review with review id " + reviewId + ".";
String msg = "Error occurred while deleting review with review id " + reviewId + ".";
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (TransactionManagementException e) {
String msg = "Error occurred when handleing transaction to delete application reviews.";
String msg = "Error occurred when handling transaction to delete application reviews.";
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} finally {
@ -663,16 +663,16 @@ public class ReviewManagerImpl implements ReviewManager {
return rating;
} catch (ApplicationManagementDAOException e) {
String msg =
"Error occured while getting the rating value of the application release uuid: " + appReleaseUuid;
"Error occurred while getting the rating value of the application release uuid: " + appReleaseUuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "DB Connection error occured while getting the rating value of the application release uuid: "
String msg = "DB Connection error occurred while getting the rating value of the application release uuid: "
+ appReleaseUuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (ReviewManagementDAOException e) {
String msg = "Error occured while getting all rating values for the application release UUID: "
String msg = "Error occurred while getting all rating values for the application release UUID: "
+ appReleaseUuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
@ -704,18 +704,18 @@ public class ReviewManagerImpl implements ReviewManager {
return rating;
} catch (DBConnectionException e) {
String msg =
"DB Connection error occured while getting app rating of the application which has application "
"DB Connection error occurred while getting app rating of the application which has application "
+ "release for uuid: " + appReleaseUuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
String msg = "Error occured while getting the application DTO for the application release uuid: "
String msg = "Error occurred while getting the application DTO for the application release uuid: "
+ appReleaseUuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (ReviewManagementDAOException e) {
String msg =
"Error occured while getting all rating values of application which has the application release "
"Error occurred while getting all rating values of application which has the application release "
+ "for UUID: " + appReleaseUuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);

@ -49,6 +49,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.routines.UrlValidator;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.common.util.HttpUtil;
import java.util.ArrayList;
import java.util.List;
@ -327,9 +328,7 @@ public class SPApplicationManagerImpl implements SPApplicationManager {
* @throws BadRequestException if url is invalid
*/
private void validateIdentityServerUrl(String url) throws BadRequestException {
String[] schemes = {"http","https"};
UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);
if (!urlValidator.isValid(url)) {
if (!HttpUtil.isHttpUrlValid(url)) {
String msg = "Identity server url is not a valid url";
log.error(msg);
throw new BadRequestException(msg);

@ -367,14 +367,14 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
try {
device = DataHolder.getInstance().getDeviceManagementService().getDevice(deviceIdentifier, false);
if (device == null) {
String msg = "Invalid device identifier is received and couldn't find an deveice for the requested "
String msg = "Invalid device identifier is received and couldn't find an device for the requested "
+ "device identifier. Device UUID: " + deviceIdentifier.getId() + " Device Type: "
+ deviceIdentifier.getType();
log.error(msg);
throw new BadRequestException(msg);
}
} catch (DeviceManagementException e) {
String msg = "Error occured while getting device data for given device identifier.Device UUID: "
String msg = "Error occurred while getting device data for given device identifier.Device UUID: "
+ deviceIdentifier.getId() + " Device Type: " + deviceIdentifier.getType();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);

@ -18,13 +18,11 @@
package io.entgra.application.mgt.core.util;
import io.entgra.application.mgt.common.ApplicationArtifact;
import io.entgra.application.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.common.Base64File;
import io.entgra.application.mgt.common.FileDataHolder;
import io.entgra.application.mgt.common.dto.ApplicationDTO;
import io.entgra.application.mgt.common.dto.ApplicationReleaseDTO;
import io.entgra.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.application.mgt.common.exception.RequestValidatingException;
import io.entgra.application.mgt.common.exception.ResourceManagementException;
import io.entgra.application.mgt.common.services.SPApplicationManager;
import io.entgra.application.mgt.common.wrapper.ApplicationWrapper;
import io.entgra.application.mgt.common.wrapper.CustomAppReleaseWrapper;

@ -23,7 +23,8 @@ import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.entgra.application.mgt.common.exception.ResourceManagementException;
import io.entgra.application.mgt.core.util.StorageManagementUtil;
import org.wso2.carbon.device.mgt.core.common.exception.StorageManagementException;
import org.wso2.carbon.device.mgt.core.common.util.StorageManagementUtil;
import java.io.File;
import java.io.FileInputStream;
@ -47,14 +48,14 @@ public class StorageManagementUtilTest {
public void testCreateArtifactDirectory() {
try {
StorageManagementUtil.createArtifactDirectory(TEMP_FOLDER);
} catch (ResourceManagementException e) {
} catch (StorageManagementException e) {
e.printStackTrace();
Assert.fail("Directory creation failed.");
}
}
@Test
public void testSaveFile() throws IOException, ResourceManagementException {
public void testSaveFile() throws IOException, ResourceManagementException, StorageManagementException {
StorageManagementUtil.createArtifactDirectory(TEMP_FOLDER);
InputStream apk = new FileInputStream(APK_FILE);
StorageManagementUtil.saveFile(apk, TEMP_FOLDER + APK_FILE_NAME);
@ -65,7 +66,7 @@ public class StorageManagementUtilTest {
}
@AfterMethod
public void deleteFileTest() throws IOException, ResourceManagementException {
public void deleteFileTest() throws IOException, StorageManagementException {
File file = new File(TEMP_FOLDER);
StorageManagementUtil.delete(file);
if (file.exists()) {

@ -42,19 +42,16 @@ import io.entgra.application.mgt.core.impl.ApplicationManagerImpl;
import io.entgra.application.mgt.core.internal.DataHolder;
import io.entgra.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.core.common.util.FileUtil;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ApplicationManagementTest extends BaseTestCase {

@ -22,7 +22,7 @@
<parent>
<artifactId>application-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -17,7 +17,7 @@
*/
package io.entgra.application.mgt.publisher.api.services;
import io.entgra.application.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.common.Base64File;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@ -18,7 +18,7 @@ package io.entgra.application.mgt.publisher.api.services.impl;
import io.entgra.application.mgt.common.ApplicationArtifact;
import io.entgra.application.mgt.common.ApplicationList;
import io.entgra.application.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.common.Base64File;
import io.entgra.application.mgt.common.Filter;
import io.entgra.application.mgt.common.LifecycleChanger;
import io.entgra.application.mgt.common.exception.ResourceManagementException;
@ -89,11 +89,11 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
ApplicationList applications = applicationManager.getApplications(filter);
return Response.status(Response.Status.OK).entity(applications).build();
} catch (BadRequestException e) {
String msg = "Incompatible request payload is found. Please try with valid request payload.";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (UnexpectedServerErrorException e) {
String msg = "Error Occured when getting supported device types by Entgra IoTS";
String msg = "Error occurred when getting supported device types by Entgra IoTS";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ApplicationManagementException e) {
@ -173,7 +173,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
try {
return createApplication(applicationWrapper, isPublished);
} catch (BadRequestException e) {
String msg = "Found incompatible payload with ent. app creating request.";
String msg = "Found incompatible payload with ent. app creating request. Please try with valid request payload.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@ -195,7 +195,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
try {
return createApplication(webAppWrapper, isPublished);
} catch (BadRequestException e) {
String msg = "Found incompatible payload with web app creating request.";
String msg = "Found incompatible payload with web app creating request. Please try with valid request payload.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@ -217,7 +217,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
try {
return createApplication(publicAppWrapper, isPublished);
} catch (BadRequestException e) {
String msg = "Found incompatible payload with pub app creating request.";
String msg = "Found incompatible payload with pub app creating request. Please try with valid request payload.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@ -239,7 +239,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
try {
return createApplication(customAppWrapper, isPublished);
} catch (BadRequestException e) {
String msg = "Found incompatible payload with custom app creating request.";
String msg = "Found incompatible payload with custom app creating request. Please try with valid request payload.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@ -267,7 +267,11 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
ApplicationRelease release = applicationManager.createEntAppRelease(appId, entAppReleaseWrapper, isPublished);
return Response.status(Response.Status.CREATED).entity(release).build();
} catch (RequestValidatingException e) {
String msg = "Error occurred while validating binaryArtifact";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e){
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@ -291,6 +295,10 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
applicationManager.validatePublicAppReleaseCreatingRequest(publicAppReleaseWrapper, deviceTypeName);
ApplicationRelease applicationRelease = applicationManager.createPubAppRelease(appId, publicAppReleaseWrapper, isPublished);
return Response.status(Response.Status.CREATED).entity(applicationRelease).build();
} catch (BadRequestException e) {
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while creating application release for the application with the id " + appId;
log.error(msg, e);
@ -300,7 +308,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (RequestValidatingException e) {
String msg = "Invalid payload found in public app release create request";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
@ -318,6 +326,10 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
applicationManager.validateWebAppReleaseCreatingRequest(webAppReleaseWrapper);
ApplicationRelease applicationRelease= applicationManager.createWebAppRelease(appId, webAppReleaseWrapper, isPublished);
return Response.status(Response.Status.CREATED).entity(applicationRelease).build();
} catch (BadRequestException e) {
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ResourceManagementException e) {
String msg = "Error occurred while uploading application release artifacts";
log.error(msg, e);
@ -327,7 +339,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (RequestValidatingException e) {
String msg = "Invalid payload found in web app release create request";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
@ -346,8 +358,12 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
applicationManager.validateCustomAppReleaseCreatingRequest(customAppReleaseWrapper, deviceTypeName);
ApplicationRelease release = applicationManager.createCustomAppRelease(appId, customAppReleaseWrapper, isPublished);
return Response.status(Response.Status.CREATED).entity(release).build();
} catch (BadRequestException e) {
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (RequestValidatingException e) {
String msg = "Error occurred while validating binaryArtifact";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ResourceManagementException e) {
@ -386,7 +402,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
}
return Response.status(Response.Status.OK).build();
} catch (BadRequestException e) {
String msg = "Found invalid device type to check application existence.";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@ -460,6 +476,10 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
String msg = "Found an invalid device type: " + deviceType + " with the request";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while updating the image artifacts of the application with the uuid "
+ applicationReleaseUuid;
@ -483,8 +503,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Error occurred while modifying the application. Found bad request payload for updating the "
+ "application";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@ -514,8 +533,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
}
return Response.status(Response.Status.OK).entity(applicationRelease).build();
} catch (BadRequestException e) {
String msg =
"Invalid request to update ent app release for application release UUID " + applicationUUID;
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) {
@ -555,7 +573,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
}
return Response.status(Response.Status.OK).entity(applicationRelease).build();
} catch (BadRequestException e) {
String msg = "Invalid request to update public app release for application release UUID " + applicationUUID;
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) {
@ -595,7 +613,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
}
return Response.status(Response.Status.OK).entity(applicationRelease).build();
} catch (BadRequestException e) {
String msg = "Invalid request to update web app release for web app release UUID " + applicationUUID;
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) {
@ -634,8 +652,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
}
return Response.status(Response.Status.OK).entity(applicationRelease).build();
} catch (BadRequestException e) {
String msg =
"Invalid request to update ent app release for application release UUID " + applicationUUID;
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) {
@ -685,7 +702,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
.changeLifecycleState(applicationUuid, lifecycleChanger);
return Response.status(Response.Status.CREATED).entity(applicationRelease).build();
} catch (BadRequestException e) {
String msg = "Request payload contains invalid data, hence verify the request payload.";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).build();
} catch (ForbiddenException e) {
@ -847,6 +864,10 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
try {
List<String> applicationTags = applicationManager.addApplicationTags(appId, tagNames);
return Response.status(Response.Status.OK).entity(applicationTags).build();
} catch (BadRequestException e) {
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) {
String msg = e.getMessage();
log.error(msg, e);

@ -96,6 +96,7 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String msg = "Identity server with the id " + id + " does not exist.";
log.error(msg, e);
// TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
@ -115,6 +116,7 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String msg = "Identity server with the id " + id + " does not exist.";
log.error(msg, e);
// TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
@ -134,9 +136,10 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String msg = "Identity server with the id " + id + " does not exist.";
log.error(msg, e);
// TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e) {
String errMsg = "Identity server request payload is invalid";
String errMsg = e.getMessage();
log.error(errMsg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build();
} catch (ApplicationManagementException e) {
@ -156,8 +159,8 @@ public class SPApplicationServiceImpl implements SPApplicationService {
IdentityServerResponse identityServer = spAppManager.createIdentityServer(identityServerDTO);
return Response.status(Response.Status.CREATED).entity(identityServer).build();
} catch (BadRequestException e) {
String errMsg = "Identity server request payload is invalid";
log.error(errMsg, e);
String errMsg = e.getMessage();
log.error(errMsg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
@ -232,6 +235,7 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String errMsg = "No Identity server exist with the id: " + identityServerId;
log.error(errMsg, e);
// TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
@ -252,6 +256,7 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String msg = "No identity server exist with the id " + identityServerId;
log.error(msg, e);
// TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Invalid appIds provided";
@ -277,6 +282,7 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String msg = "No identity server exist with the id " + identityServerId;
log.error(msg, e);
// TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Invalid appIds provided";
@ -343,6 +349,7 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String msg = "No identity server exist with the id " + identityServerId;
log.error(msg, e);
// TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Found incompatible payload with create service provider app request.";

@ -155,6 +155,10 @@ public class ApplicationManagementPublisherAdminAPIImpl implements ApplicationMa
applicationManager.updateCategory(oldCategoryName, newCategoryName);
return Response.status(Response.Status.OK)
.entity("Category is updated from " + oldCategoryName + " to " + newCategoryName).build();
} catch (BadRequestException e) {
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) {
String msg = e.getMessage();
log.error(msg, e);
@ -181,6 +185,10 @@ public class ApplicationManagementPublisherAdminAPIImpl implements ApplicationMa
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ForbiddenException e) {
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error Occurred while deleting registered category.";
log.error(msg, e);

@ -22,7 +22,7 @@
<parent>
<artifactId>application-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -58,7 +58,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
applicationManager.addAppToFavourites(appId);
return Response.status(Response.Status.OK).build();
} catch (BadRequestException e) {
String msg = "Invalid payload found in the request. Hence verify the request payload.";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@ -78,7 +78,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
applicationManager.removeAppFromFavourites(appId);
return Response.status(Response.Status.OK).build();
} catch (BadRequestException e) {
String msg = "Invalid payload found in the request. Hence verify the request payload.";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@ -147,7 +147,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
String msg = "Could not found an application release which is in " + applicationManager
.getInstallableLifecycleState() + " state.";
log.error(msg);
return Response.status(Response.Status.OK).entity(msg).build();
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(application).build();
} catch (NotFoundException e) {

@ -131,7 +131,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Found invalid payload data with the request. Hence, please verify the request payload.";
String msg = e.getMessage();
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@ -144,7 +144,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occured while accessing application release for UUID: " + uuid;
String msg = "Error occurred while accessing application release for UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
@ -164,7 +164,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
if (isRepliedForReview) {
return Response.status(Response.Status.CREATED).entity(reviewWrapper).build();
} else {
String msg = "Error occured when adding reply comment for the review. Please contact the administrator..";
String msg = "Error occurred when adding reply comment for the review. Please contact the administrator..";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
@ -173,7 +173,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Found invalid payload data with the request to add reply comment. Hence, please verify the "
String msg = "Invalid payload data found with the requested add reply comment. Hence, please verify the "
+ "request payload.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
@ -182,7 +182,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occured while accessing application release for UUID: " + uuid;
String msg = "Error occurred while accessing application release for UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
@ -214,8 +214,12 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
String msg = "Couldn't found application release data for UUID " + uuid + " or Review for review ID: " + reviewId;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Invalid payload data found with the request. Hence, please verify the request payload.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
String msg = "You dont have permission to update application release review.";
String msg = "You don't have permission to update application release review.";
log.error(msg, e);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
} catch (ApplicationManagementException e) {
@ -267,7 +271,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ReviewManagementException | ApplicationManagementException e) {
String msg = "Error occured while getting review data for application release UUID: " + uuid;
String msg = "Error occurred while getting review data for application release UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}

@ -93,12 +93,11 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
SubAction.valueOf(action.toUpperCase()), timestamp, properties);
}
} catch (NotFoundException e) {
String msg = "Couldn't found an application release for UUI: " + uuid;
String msg = "Couldn't found an application release for UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Found invalid payload for installing application which has UUID: " + uuid + ". Hence verify "
+ "the payload";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@ -147,8 +146,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Found invalid payload for installing application which has UUID: " + uuid + ". Hence verify "
+ "the payload";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@ -187,13 +185,12 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
SubAction.valueOf(SubAction.INSTALL.toString().toUpperCase()), timestamp, null);
}
} catch (NotFoundException e) {
String msg = "Couldn't found an application release for UUI: " + uuid + " to perform ent app installation "
String msg = "Couldn't found an application release for UUID: " + uuid + " to perform ent app installation "
+ "on subscriber's devices";
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Found invalid payload when performing ent app installation on application which has UUID: "
+ uuid + ". Hence verify the payload of the request.";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@ -237,8 +234,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Found invalid payload when performing ent app installation on application which has UUID: "
+ uuid + ". Hence verify the payload of the request.";
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@ -360,7 +356,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "User requested details are not valid";
String msg = "User requested details are not valid. Please verify the payload of the request.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@ -424,8 +420,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Found invalid payload for getting application which has UUID: " + uuid
+ ". Hence verify the payload";
String msg = "Invalid payload found when getting application. Hence verify the payload";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@ -502,6 +497,10 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
String msg = "Application with application release UUID: " + uuid + " is not found";
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Invalid payload found with the request. Please verify the payload.";
log.error(msg,e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while getting application with the application " +
"release uuid: " + uuid;

@ -133,7 +133,7 @@ public class SubscriptionManagementAdminAPIImpl implements SubscriptionManagemen
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
String msg = "User requested details are not valid";
String msg = "User requested details are not valid. Please verify the request payload.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {

@ -22,7 +22,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>certificate-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>certificate-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -38,7 +38,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>certificate-mgt</artifactId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -44,12 +44,17 @@ import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.util.Store;
import org.jscep.message.*;
import org.jscep.message.CertRep;
import org.jscep.message.MessageDecodingException;
import org.jscep.message.MessageEncodingException;
import org.jscep.message.PkcsPkiEnvelopeDecoder;
import org.jscep.message.PkcsPkiEnvelopeEncoder;
import org.jscep.message.PkiMessage;
import org.jscep.message.PkiMessageDecoder;
import org.jscep.message.PkiMessageEncoder;
import org.jscep.transaction.FailInfo;
import org.jscep.transaction.Nonce;
import org.jscep.transaction.TransactionId;
import org.wso2.carbon.certificate.mgt.core.cache.CertificateCacheManager;
import org.wso2.carbon.certificate.mgt.core.cache.impl.CertificateCacheManagerImpl;
import org.wso2.carbon.certificate.mgt.core.dao.CertificateDAO;
import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException;
import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory;
@ -72,13 +77,31 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.SignatureException;
import java.security.cert.Certificate;
import java.security.cert.*;
import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class CertificateGenerator {
@ -757,4 +780,86 @@ public class CertificateGenerator {
return generateCertificateFromCSR(privateKeyCA, certificationRequest,
certCA.getIssuerX500Principal().getName());
}
}
public X509Certificate generateAlteredCertificateFromCSR(String csr)
throws KeystoreException {
byte[] byteArrayBst = DatatypeConverter.parseBase64Binary(csr);
PKCS10CertificationRequest certificationRequest;
KeyStoreReader keyStoreReader = new KeyStoreReader();
PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();
X509Certificate issuedCert;
try {
certificationRequest = new PKCS10CertificationRequest(byteArrayBst);
JcaContentSignerBuilder csBuilder =
new JcaContentSignerBuilder(CertificateManagementConstants.SIGNING_ALGORITHM);
ContentSigner signer = csBuilder.build(privateKeyCA);
BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());
X500Name issuerName = new X500Name(certCA.getSubjectDN().getName());
String commonName = certificationRequest.getSubject().getRDNs(BCStyle.CN)[0].getFirst()
.getValue().toString();
X500Name subjectName = new X500Name("O=" + commonName + "O=AndroidDevice,CN=" +
serialNumber);
Date startDate = new Date(System.currentTimeMillis());
Date endDate = new Date(System.currentTimeMillis()
+ TimeUnit.DAYS.toMillis(365 * 100));
PublicKey publicKey = getPublicKeyFromRequest(certificationRequest);
X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(
issuerName, serialNumber, startDate, endDate,
subjectName, publicKey);
X509CertificateHolder certHolder = certBuilder.build(signer);
CertificateFactory certificateFactory = CertificateFactory.getInstance
(CertificateManagementConstants.X_509);
byte[] encodedCertificate = certHolder.getEncoded();
issuedCert = (X509Certificate) certificateFactory
.generateCertificate(new ByteArrayInputStream(encodedCertificate));
org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate =
new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
certificate.setCertificate(issuedCert);
certificates.add(certificate);
saveCertInKeyStore(certificates);
} catch (OperatorCreationException e) {
String errorMsg = "Error creating the content signer";
log.error(errorMsg);
throw new KeystoreException(errorMsg, e);
} catch (CertificateException e) {
String errorMsg = "Error when opening the newly created certificate";
log.error(errorMsg);
throw new KeystoreException(errorMsg, e);
} catch (InvalidKeySpecException e) {
String errorMsg = "Public key is having invalid specification";
log.error(errorMsg);
throw new KeystoreException(errorMsg, e);
} catch (NoSuchAlgorithmException e) {
String errorMsg = "Could not find RSA algorithm";
log.error(errorMsg);
throw new KeystoreException(errorMsg, e);
} catch (IOException e) {
String errorMsg = "Error while reading the csr";
log.error(errorMsg);
throw new KeystoreException(errorMsg, e);
}
return issuedCert;
}
private static PublicKey getPublicKeyFromRequest(PKCS10CertificationRequest request)
throws InvalidKeySpecException, NoSuchAlgorithmException, IOException {
byte[] publicKeyBytes = request.getSubjectPublicKeyInfo().getEncoded();
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
return publicKey;
}
}

@ -79,4 +79,6 @@ public interface CertificateManagementService {
List<CertificateResponse> searchCertificates(String serialNumber) throws CertificateManagementException;
X509Certificate generateAlteredCertificateFromCSR(String csr) throws KeystoreException;
}

@ -234,4 +234,9 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe
}
}
@Override
public X509Certificate generateAlteredCertificateFromCSR(String csr) throws KeystoreException{
return certificateGenerator.generateAlteredCertificateFromCSR(csr);
}
}

@ -39,6 +39,7 @@ public final class CertificateManagementConstants {
public static final String RSA_PRIVATE_KEY_END_TEXT = "-----END RSA PRIVATE KEY-----";
public static final String EMPTY_TEXT = "";
public static final int RSA_KEY_LENGTH = 2048;
public static final String SIGNING_ALGORITHM = "SHA256withRSA";
public static final class DataBaseTypes {
private DataBaseTypes() {

@ -22,7 +22,7 @@
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>

@ -23,7 +23,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -48,6 +48,22 @@ public interface EntgraLogger extends Log {
void warn(Object object, Throwable t, LogContext logContext);
void info(String message, LogContext logContext);
void debug(String message, LogContext logContext);
void error(String message, LogContext logContext);
void error(String message, Throwable t, LogContext logContext);
void warn(String message, LogContext logContext);
void warn(String message, Throwable t, LogContext logContext);
void trace(String message, LogContext logContext);
void fatal(String message, LogContext logContext);
void clearLogContext();
}

@ -23,7 +23,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>carbon-devicemgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

@ -91,9 +91,7 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig
if (properties == null || properties.isEmpty()) {
String msg = "Devices configuration retrieval criteria cannot be null or empty.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()
).build();
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
ObjectMapper mapper = new ObjectMapper();
@ -113,18 +111,15 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (DeviceNotFoundException e) {
log.warn(e.getMessage());
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(e.getMessage()).build()).build();
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (AmbiguousConfigurationException e) {
String msg = "Configurations are ambiguous. " + e.getMessage();
log.warn(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (JsonParseException | JsonMappingException e) {
String msg = "Malformed device property structure";
log.error(msg.concat(" ").concat(properties), e);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (IOException e) {
String msg = "Error occurred while parsing query param JSON data.";
log.error(msg.concat(" ").concat(properties), e);
@ -150,8 +145,7 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig
if (devicesTransferred.isEmpty()) {
String msg = "Devices are not enrolled to super tenant";
log.warn(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} else {
return Response.status(Response.Status.OK).entity(devicesTransferred).build();
}
@ -163,8 +157,7 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (DeviceNotFoundException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(e.getMessage()).build()).build();
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
}
}

@ -22,7 +22,7 @@
<parent>
<artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version>
<version>5.0.25-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
@ -425,5 +425,35 @@
<artifactId>io.entgra.application.mgt.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.keymgt.extension</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.stream.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.receiver.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.publisher.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.rdbms</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.device.mgt.core.apimgt.analytics.extension</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -0,0 +1,116 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import java.util.List;
@ApiModel(value = "DeviceConfig", description = "Device config")
public class DeviceConfig {
private String clientId;
private String clientSecret;
private String deviceId;
private String type;
private String accessToken;
private String refreshToken;
private String mqttGateway;
private String httpsGateway;
private String httpGateway;
private PlatformConfiguration platformConfiguration;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public String getMqttGateway() {
return mqttGateway;
}
public void setMqttGateway(String mqttGateway) {
this.mqttGateway = mqttGateway;
}
public String getHttpsGateway() {
return httpsGateway;
}
public void setHttpsGateway(String httpsGateway) {
this.httpsGateway = httpsGateway;
}
public String getHttpGateway() {
return httpGateway;
}
public void setHttpGateway(String httpGateway) {
this.httpGateway = httpGateway;
}
public PlatformConfiguration getPlatformConfiguration() {
return platformConfiguration;
}
public void setPlatformConfiguration(PlatformConfiguration platformConfiguration) {
this.platformConfiguration = platformConfiguration;
}
}

@ -20,14 +20,18 @@ package org.wso2.carbon.device.mgt.jaxrs.beans.analytics;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
/**
* This hold stats data record
*/
public class DeviceTypeEvent {
private String eventName;
private EventAttributeList eventAttributes;
private TransportType transport;
private String eventTopicStructure;
@ApiModelProperty(value = "Attributes related to device type event")
@JsonProperty("eventAttributes")
public EventAttributeList getEventAttributeList() {
@ -48,5 +52,25 @@ public class DeviceTypeEvent {
public void setTransportType(TransportType transport) {
this.transport = transport;
}
@ApiModelProperty(value = "event topic structure")
@JsonProperty("eventTopicStructure")
public String getEventTopicStructure() {
return eventTopicStructure;
}
public void setEventTopicStructure(String eventTopicStructure) {
this.eventTopicStructure = eventTopicStructure;
}
@ApiModelProperty(value = "event topic name")
@JsonProperty("eventName")
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
}

@ -29,6 +29,7 @@ import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
@SwaggerDefinition(
info = @Info(
@ -69,64 +70,64 @@ import javax.ws.rs.core.Response;
@Consumes(MediaType.APPLICATION_JSON)
public interface DeviceEventManagementService {
// @POST
// @Path("/{type}")
// @ApiOperation(
// produces = MediaType.APPLICATION_JSON,
// httpMethod = "POST",
// value = "Adding the Event Type Definition",
// notes = "Add the event definition for a device.",
// tags = "Device Event Management",
// extensions = {
// @Extension(properties = {
// @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events")
// })
// }
// )
// @ApiResponses(
// value = {
// @ApiResponse(
// code = 200,
// message = "OK. \n Successfully added the event defintion.",
// responseHeaders = {
// @ResponseHeader(
// name = "Content-Type",
// description = "The content type of the body"),
// @ResponseHeader(
// name = "ETag",
// description = "Entity Tag of the response resource.\n" +
// "Used by caches, or in conditional requests."),
// @ResponseHeader(
// name = "Last-Modified",
// description =
// "Date and time the resource was last modified.\n" +
// "Used by caches, or in conditional requests."),
// }
// ),
// @ApiResponse(
// code = 400,
// message =
// "Bad Request. \n"),
// @ApiResponse(
// code = 406,
// message = "Not Acceptable.\n The requested media type is not supported"),
// @ApiResponse(
// code = 500,
// message = "Internal Server Error. \n Server error occurred while fetching the " +
// "list of supported device types.",
// response = ErrorResponse.class)
// }
// )
// Response deployDeviceTypeEventDefinition(
// @ApiParam(name = "type", value = "The device type, such as android, ios, and windows.")
// @PathParam("type")String deviceType,
// @ApiParam(name = "skipPersist", value = "Is it required to persist the data or not")
// @QueryParam("skipPersist") boolean skipPersist,
// @ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants")
// @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
// @ApiParam(name = "deviceTypeEvent", value = "Add the data to complete the DeviceTypeEvent object.",
// required = true)
// @Valid DeviceTypeEvent deviceTypeEvent);
@POST
@Path("/{type}")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Adding the Event Type Definition",
notes = "Add the event definition for a device.",
tags = "Device Event Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully added the event defintion.",
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description =
"Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}
),
@ApiResponse(
code = 400,
message =
"Bad Request. \n"),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported"),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the " +
"list of supported device types.",
response = ErrorResponse.class)
}
)
Response deployDeviceTypeEventDefinition(
@ApiParam(name = "type", value = "The device type, such as android, ios, and windows.")
@PathParam("type")String deviceType,
@ApiParam(name = "skipPersist", value = "Is it required to persist the data or not")
@QueryParam("skipPersist") boolean skipPersist,
@ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants")
@QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
@ApiParam(name = "deviceTypeEvents", value = "Add the data to complete the DeviceTypeEvent object.",
required = true)
@Valid List<DeviceTypeEvent> deviceTypeEvent);
@DELETE
@Path("/{type}")

@ -188,6 +188,13 @@ import java.util.List;
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/devices/owning-device/add"}
),
@Scope(
name = "Viewing Enrollment Guide",
description = "Show enrollment guide to users",
key = "perm:devices:enrollment-guide:view",
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/devices/enrollment-guide/view"}
),
}
)
@Path("/devices")
@ -418,59 +425,6 @@ public interface DeviceManagementService {
@QueryParam("limit")
int limit);
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting Details of Registered Devices Owned by an Authenticated User to generate token for Traccar",
notes = "Provides details of devices enrolled by authenticated users to generate token for Traccar.",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
})
}
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.",
response = DeviceList.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. \n Empty body because the client already has the latest version of " +
"the requested resource.\n"),
@ApiResponse(
code = 400,
message = "The incoming request has more than one selection criteria defined via the query parameters.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "The search criteria did not match any device registered with the server.",
response = ErrorResponse.class),
@ApiResponse(
code = 406,
message = "Not Acceptable.\n The requested media type is not supported."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Server error occurred while fetching the device list.",
response = ErrorResponse.class)
})
@Path("/traccar-user-token")
Response getTraccarUserToken();
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{groupId}/location-history")
@ -553,12 +507,12 @@ public interface DeviceManagementService {
required = false,
defaultValue = "0")
@QueryParam("offset") int offset,
@ApiParam(
name = "limit",
value = "Provide how many device details you require from the starting pagination index/offset.",
required = false,
defaultValue = "100")
@QueryParam("limit") int limit
@ApiParam(
name = "limit",
value = "Provide how many device details you require from the starting pagination index/offset.",
required = false,
defaultValue = "100")
@QueryParam("limit") int limit
);
@GET
@ -802,6 +756,59 @@ public interface DeviceManagementService {
@QueryParam("requireDeviceInfo")
boolean requireDeviceInfo);
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/enrollment/guide")
@ApiOperation(
consumes = MediaType.MULTIPART_FORM_DATA,
produces = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Sending Enrollment Mode chosen by customer",
notes = "Enrollment mode selected and path is sent as parameters",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:enrollment-guide:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully mailed the Enrollment Guide of customer.",
response = Device.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while sending mail of the Enrollment Guide.",
response = ErrorResponse.class)
})
Response sendEnrollmentGuide(
@ApiParam(
name = "enrolmentGuide",
value = "The details of the enrolment path suggested.",
required = true)
String enrolmentGuide);
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/type/any/list")
@ -1059,6 +1066,82 @@ public interface DeviceManagementService {
@HeaderParam("If-Modified-Since")
String ifModifiedSince);
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/config")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Getting the Configuration of a Device",
notes = "Get the configuration of a device by specifying the device type and device identifier.",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the configuration of the device.",
response = DeviceInfo.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest version" +
" of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n Location data for the specified device was not found.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the device details.",
response = ErrorResponse.class)
})
Response getDeviceConfiguration(
@ApiParam(
name = "type",
value = "The device type name, such as ios, android, windows, or fire-alarm.",
required = true)
@PathParam("type")
@Size(max = 45)
String type,
@ApiParam(
name = "id",
value = "The device identifier of the device you want ot get details.",
required = true)
@PathParam("id")
@Size(max = 45)
String id,
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" +
"Provide the value in the following format: EEE, d MMM yyyy HH:mm:ss Z. \n" +
"Example: Mon, 05 Jan 2014 15:10:00 +0200",
required = false)
@HeaderParam("If-Modified-Since")
String ifModifiedSince);
//device rename request would looks like follows
//POST devices/type/virtual_firealarm/id/us06ww93auzp/rename
@POST
@ -1399,15 +1482,15 @@ public interface DeviceManagementService {
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified. \n" +
"Used by caches, or in conditional requests.")}),
"Used by caches, or in conditional requests.")}),
@ApiResponse(
code = 304,
message = "Not Modified. \n " +
"Empty body because the client already has the latest version of the requested resource.\n"),
"Empty body because the client already has the latest version of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
@ -1425,7 +1508,7 @@ public interface DeviceManagementService {
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while getting the device details.",
"Server error occurred while getting the device details.",
response = ErrorResponse.class)
})
Response queryDevicesByProperties(
@ -1447,7 +1530,7 @@ public interface DeviceManagementService {
name = "device property map",
value = "properties by which devices need filtered",
required = true)
PropertyMap map);
PropertyMap map);
@GET
@Produces(MediaType.APPLICATION_JSON)
@ -1873,140 +1956,141 @@ public interface DeviceManagementService {
@Size(max = 45)
String id);
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/getstatushistory")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get Device status history",
notes = "Get a list of status history associated with the device type and id",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the status history of matching devices.",
response = List.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest version" +
" of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n A device with the specified device type and id was not found.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the device details.",
response = ErrorResponse.class)
})
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/status-history")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get Device status history",
notes = "Get a list of status history associated with the device type and id",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the status history of matching devices.",
response = List.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest version" +
" of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n A device with the specified device type and id was not found.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the device details.",
response = ErrorResponse.class)
})
Response getDeviceStatusHistory(
@ApiParam(
name = "type",
value = "The device type, such as ios, android, or windows.",
required = true)
@PathParam("type")
@Size(max = 45)
String type,
@ApiParam(
name = "id",
value = "Device ID.",
required = true)
@PathParam("id")
@Size(max = 45)
String id);
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/getenrolmentstatushistory")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get Device Current Enrolment status history",
notes = "Get a list of status history associated with the device type and id for the current enrolment",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the status history of matching devices.",
response = List.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest version" +
" of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n A device with the specified device type and id was not found.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the device details.",
response = ErrorResponse.class)
})
@ApiParam(
name = "type",
value = "The device type, such as ios, android, or windows.",
required = true)
@PathParam("type")
@Size(max = 45)
String type,
@ApiParam(
name = "id",
value = "Device ID.",
required = true)
@PathParam("id")
@Size(max = 45)
String id);
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/enrolment-status-history")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Get Device Current Enrolment status history",
notes = "Get a list of status history associated with the device type and id for the current enrolment",
tags = "Device Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched the status history of matching devices.",
response = List.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest version" +
" of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class),
@ApiResponse(
code = 404,
message = "Not Found. \n A device with the specified device type and id was not found.",
response = ErrorResponse.class),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the device details.",
response = ErrorResponse.class)
})
Response getCurrentEnrolmentDeviceStatusHistory(
@ApiParam(
name = "type",
value = "The device type, such as ios, android, or windows.",
required = true)
@PathParam("type")
@Size(max = 45)
String type,
@ApiParam(
name = "id",
value = "Device ID.",
required = true)
@PathParam("id")
@Size(max = 45)
String id);
@ApiParam(
name = "type",
value = "The device type, such as ios, android, or windows.",
required = true)
@PathParam("type")
@Size(max = 45)
String type,
@ApiParam(
name = "id",
value = "Device ID.",
required = true)
@PathParam("id")
@Size(max = 45)
String id);
@PUT
@Produces(MediaType.APPLICATION_JSON)
@ -2171,16 +2255,16 @@ public interface DeviceManagementService {
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest version" +
" of the requested resource.\n"),
" of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
@ -2192,7 +2276,7 @@ public interface DeviceManagementService {
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the device details.",
"Server error occurred while retrieving the device details.",
response = ErrorResponse.class)
})
Response getDeviceCountByStatus(
@ -2240,16 +2324,16 @@ public interface DeviceManagementService {
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest version" +
" of the requested resource.\n"),
" of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
@ -2261,7 +2345,7 @@ public interface DeviceManagementService {
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving the device details.",
"Server error occurred while retrieving the device details.",
response = ErrorResponse.class)
})
Response getDeviceIdentifiersByStatus(
@ -2310,16 +2394,16 @@ public interface DeviceManagementService {
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" +
"Used by caches, or in conditional requests."),
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 304,
message = "Not Modified. Empty body because the client already has the latest " +
"version of the requested resource."),
"version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
@ -2331,7 +2415,7 @@ public interface DeviceManagementService {
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
"Server error occurred while retrieving information requested device.",
"Server error occurred while retrieving information requested device.",
response = ErrorResponse.class)
})
Response bulkUpdateDeviceStatus(
@ -2642,11 +2726,11 @@ public interface DeviceManagementService {
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 500,

@ -33,6 +33,7 @@ import org.apache.axis2.transport.http.HTTPConstants;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.mgt.common.metadata.mgt.Metadata;
import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.MetadataList;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;

@ -0,0 +1,324 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Extension;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Info;
import io.swagger.annotations.ResponseHeader;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import io.swagger.annotations.ApiParam;
import org.apache.axis2.transport.http.HTTPConstants;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.mgt.common.metadata.mgt.Metadata;
import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* Metadata related REST-API implementation.
*/
@SwaggerDefinition(
info = @Info(
version = "1.0.0",
title = "Whitelabel Service",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = "name", value = "WhiteLabelManagement"),
@ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/whitelabel"),
})
}
),
tags = {
@Tag(name = "device_management")
}
)
@Scopes(
scopes = {
@Scope(
name = "View Whitelabel",
description = "View whitelabel details",
key = "perm:whitelabel:view",
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/whitelabel/view"}
),
@Scope(
name = "Update Whitelabel",
description = "Updating whitelabel",
key = "perm:whitelabel:update",
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/whitelabel/update"}
),
}
)
@Api(value = "Whitelabel Management")
@Path("/whitelabel")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public interface WhiteLabelService {
@GET
@Path("/{tenantDomain}/favicon")
@ApiOperation(
httpMethod = HTTPConstants.HEADER_GET,
value = "Get whitelabel favicon",
notes = "Get whitelabel favicon for the tenant of the logged in user",
tags = "Tenant Metadata Management"
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved white label favicon.",
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 500,
message = "Internal Server Error. " +
"\n Server error occurred while getting white label artifact.",
response = ErrorResponse.class)
})
Response getWhiteLabelFavicon( @ApiParam(
name = "tenantDomain",
value = "The tenant domain.",
required = true) @PathParam("tenantDomain") String tenantDomain);
@GET
@Path("/{tenantDomain}/logo")
@ApiOperation(
httpMethod = HTTPConstants.HEADER_GET,
value = "Get whitelabel logo",
notes = "Get whitelabel logo for the tenant of the logged in user",
tags = "Tenant Metadata Management"
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved white label logo.",
response = Metadata.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 500,
message = "Internal Server Error. " +
"\n Server error occurred while getting white label artifact.",
response = ErrorResponse.class)
})
Response getWhiteLabelLogo(
@ApiParam(
name = "tenantDomain",
value = "The tenant domain.",
required = true)
@PathParam("tenantDomain") String tenantDomain);
@GET
@Path("/{tenantDomain}/icon")
@ApiOperation(
httpMethod = HTTPConstants.HEADER_GET,
value = "Get whitelabel logo icon",
notes = "Get whitelabel logo icon for the tenant of the logged in user",
tags = "Tenant Metadata Management"
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully retrieved white label logo.",
response = Metadata.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 500,
message = "Internal Server Error. " +
"\n Server error occurred while getting white label artifact.",
response = ErrorResponse.class)
})
Response getWhiteLabelLogoIcon( @ApiParam(
name = "tenantDomain",
value = "The tenant domain.",
required = true) @PathParam("tenantDomain") String tenantDomain);
@PUT
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HTTPConstants.HEADER_POST,
value = "Create whitelabel for tenant",
notes = "Create whitelabel for the tenant of the logged in user",
tags = "Tenant Metadata Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:whitelabel:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully created white label theme.",
response = Metadata.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 500,
message = "Internal Server Error. " +
"\n Server error occurred while creating white label theme.",
response = ErrorResponse.class)
})
Response updateWhiteLabelTheme(WhiteLabelThemeCreateRequest whiteLabelThemeCreateRequest);
@GET
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HTTPConstants.HEADER_POST,
value = "Get whitelabel for tenant",
notes = "Get whitelabel for the tenant of the logged in user",
tags = "Tenant Metadata Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:whitelabel:view")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched white label theme.",
response = Metadata.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 500,
message = "Internal Server Error. " +
"\n Server error occurred while fetching white label theme.",
response = ErrorResponse.class)
})
Response getWhiteLabelTheme();
@PUT
@Path("/reset")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = HTTPConstants.HEADER_POST,
value = "Reset whitelabel for tenant",
notes = "Reset whitelabel to default for the tenant of the logged in user",
tags = "Tenant Metadata Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:whitelabel:update")
})
}
)
@ApiResponses(
value = {
@ApiResponse(
code = 200,
message = "OK. \n Successfully fetched white label theme.",
response = Metadata.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 500,
message = "Internal Server Error. " +
"\n Server error occurred while deleting white label theme.",
response = ErrorResponse.class)
})
Response resetWhiteLabel();
}

@ -74,9 +74,9 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activity = dmService.getOperationByActivityId(id);
if (activity == null) {
return Response.status(404).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("No activity can be " +
"found upon the provided activity id '" + id + "'").build()).build();
String msg = "No activity can be " +
"found upon the provided activity id '" + id + "'";
return Response.status(404).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(activity).build();
} catch (OperationManagementException e) {
@ -98,10 +98,9 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
List<String> idList;
idList = activityIdList.getIdList();
if (idList == null || idList.isEmpty()) {
String msg = "Activity Ids shouldn't be empty";
String msg = "Activities should not be empty";
log.error(msg);
return Response.status(400).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
return Response.status(400).entity(msg).build();
}
Response validationFailedResponse = validateAdminPermission();
if (validationFailedResponse == null) {
@ -125,8 +124,7 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
} else {
String msg = "No activity found with the given IDs.";
log.error(msg);
return Response.status(404).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
return Response.status(404).entity(msg).build();
}
} catch (OperationManagementException e) {
String msg = "ErrorResponse occurred while fetching the activity list for the supplied ids.";
@ -162,9 +160,9 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activity = dmService.getOperationByActivityIdAndDevice(id, deviceIdentifier);
if (activity == null) {
return Response.status(404).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("No activity can be " +
"found upon the provided activity id '" + id + "'").build()).build();
String msg = "No activity can be " +
"found upon the provided activity id '" + id + "'";
return Response.status(404).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(activity).build();
} catch (OperationManagementException e) {
@ -247,9 +245,8 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
try {
ifSinceDate = format.parse(ifModifiedSince);
} catch (ParseException e) {
return Response.status(400).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(
"Invalid date string is provided in 'If-Modified-Since' header").build()).build();
String msg = "Invalid date string is provided in [If-Modified-Since] header.";
return Response.status(400).entity(msg).build();
}
ifModifiedSinceTimestamp = ifSinceDate.getTime();
timestamp = ifModifiedSinceTimestamp / 1000;
@ -259,9 +256,8 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
try {
sinceDate = format.parse(since);
} catch (ParseException e) {
return Response.status(400).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(
"Invalid date string is provided in 'since' filter").build()).build();
String msg = "Invalid date string is provided in [since] filter.";
return Response.status(400).entity(msg).build();
}
sinceTimestamp = sinceDate.getTime();
timestamp = sinceTimestamp / 1000;

@ -1,11 +1,19 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import io.entgra.device.mgt.core.apimgt.analytics.extension.AnalyticsArtifactsDeployer;
import io.entgra.device.mgt.core.apimgt.analytics.extension.dto.*;
import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventReceiverDeployerException;
import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventPublisherDeployerException;
import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventStreamDeployerException;
import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Stub;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.databridge.commons.StreamDefinition;
import org.wso2.carbon.databridge.commons.exception.MalformedStreamDefinitionException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.Attribute;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.AttributeType;
@ -15,26 +23,40 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.TransportType;
import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceEventManagementService;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
import org.wso2.carbon.event.publisher.core.EventPublisherService;
import org.wso2.carbon.event.publisher.core.config.EventPublisherConfiguration;
import org.wso2.carbon.event.publisher.core.config.mapping.JSONOutputMapping;
import org.wso2.carbon.event.publisher.core.config.mapping.MapOutputMapping;
import org.wso2.carbon.event.publisher.core.exception.EventPublisherConfigurationException;
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceCallbackHandler;
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub;
import org.wso2.carbon.event.receiver.core.EventReceiverService;
import org.wso2.carbon.event.receiver.core.config.EventReceiverConfiguration;
import org.wso2.carbon.event.receiver.core.config.mapping.JSONInputMapping;
import org.wso2.carbon.event.receiver.core.config.mapping.WSO2EventInputMapping;
import org.wso2.carbon.event.receiver.core.exception.EventReceiverConfigurationException;
import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceCallbackHandler;
import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub;
import org.wso2.carbon.event.receiver.stub.types.BasicInputAdapterPropertyDto;
import org.wso2.carbon.event.receiver.stub.types.EventReceiverConfigurationDto;
import org.wso2.carbon.event.stream.core.EventStreamService;
import org.wso2.carbon.event.stream.core.exception.EventStreamConfigurationException;
import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub;
import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto;
import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.validation.Valid;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
@ -173,65 +195,129 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
/**
* Deploy Event Stream, Receiver, Publisher and Store Configuration.
*/
// @POST
// @Path("/{type}")
// @Override
// public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType,
// @QueryParam("skipPersist") boolean skipPersist,
// @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
// @Valid DeviceTypeEvent deviceTypeEvent) {
// TransportType transportType = deviceTypeEvent.getTransportType();
// EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList();
// String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
// try {
// if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 ||
// deviceType == null || transportType == null ||
// !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
// String errorMessage = "Invalid Payload";
// log.error(errorMessage);
// return Response.status(Response.Status.BAD_REQUEST).build();
// }
// String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain);
// String streamNameWithVersion = streamName + ":" + Constants.DEFAULT_STREAM_VERSION;
// publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes);
// publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType);
// if (!skipPersist) {
// publishEventStore(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes);
// }
// publishWebsocketPublisherDefinition(streamNameWithVersion, deviceType);
// try {
// PrivilegedCarbonContext.startTenantFlow();
// PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
// MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
// if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
// publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes);
// publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType);
// }
// } finally {
// PrivilegedCarbonContext.endTenantFlow();
// }
// return Response.ok().build();
// } catch (AxisFault e) {
// log.error("Failed to create event definitions for tenantDomain:" + tenantDomain, e);
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
// } catch (RemoteException e) {
// log.error("Failed to connect with the remote services:" + tenantDomain, e);
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
// } catch (JWTClientException e) {
// log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e);
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
// } catch (UserStoreException e) {
// log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e);
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
// } catch (DeviceManagementException e) {
// log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e);
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
// } catch (EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException e) {
// log.error("Failed to create event store for, tenantDomain: " + tenantDomain + " deviceType" + deviceType,
// e);
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
// }
// }
@POST
@Path("/{type}")
@Override
public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType,
@QueryParam("skipPersist") boolean skipPersist,
@QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
@Valid List<DeviceTypeEvent> deviceTypeEvents) {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
for (DeviceTypeEvent deviceTypeEvent : deviceTypeEvents) {
TransportType transportType = deviceTypeEvent.getTransportType();
EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList();
String eventName = deviceTypeEvent.getEventName();
if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 ||
deviceType == null || transportType == null ||
!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
String errorMessage = "Invalid Payload";
log.error(errorMessage);
return Response.status(Response.Status.BAD_REQUEST).build();
}
// event stream
String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain, eventName);
AnalyticsArtifactsDeployer artifactsDeployer = new AnalyticsArtifactsDeployer();
List<Property> props = new ArrayList<>();
for (Attribute attribute : eventAttributes.getList()) {
props.add(new Property(attribute.getName(), attribute.getType().name()));
}
EventStreamData eventStreamData = new EventStreamData();
eventStreamData.setName(streamName);
eventStreamData.setVersion(Constants.DEFAULT_STREAM_VERSION);
eventStreamData.setMetaData(new MetaData(DEFAULT_DEVICE_ID_ATTRIBUTE, "STRING"));
eventStreamData.setPayloadData(props);
artifactsDeployer.deployEventStream(eventStreamData, tenantId);
// event receiver
String receiverName = getReceiverName(deviceType, tenantDomain, transportType, eventName);
EventReceiverData receiverData = new EventReceiverData();
receiverData.setName(receiverName);
receiverData.setStreamName(streamName);
receiverData.setStreamVersion(Constants.DEFAULT_STREAM_VERSION);
List<Property> propertyList = new ArrayList<>();
if (transportType == TransportType.MQTT) {
receiverData.setEventAdapterType(OAUTH_MQTT_ADAPTER_TYPE);
propertyList.add(new Property(MQTT_CONTENT_TRANSFORMER_TYPE, MQTT_CONTENT_TRANSFORMER));
propertyList.add(new Property(MQTT_CONTENT_VALIDATOR_TYPE, MQTT_CONTENT_VALIDATOR));
String topic;
if (!StringUtils.isEmpty(deviceTypeEvent.getEventTopicStructure())) {
if (isSharedWithAllTenants) {
topic = deviceTypeEvent.getEventTopicStructure().replace("${deviceId}", "+")
.replace("${deviceType}", deviceType)
.replace("${tenantDomain}", "+");
} else {
topic = deviceTypeEvent.getEventTopicStructure().replace("${deviceId}", "+")
.replace("${deviceType}", deviceType)
.replace("${tenantDomain}", tenantDomain);
}
} else {
if (isSharedWithAllTenants) {
topic = "+/" + deviceType + "/+/events";
} else {
topic = tenantDomain + "/" + deviceType + "/+/events";
}
}
propertyList.add(new Property("topic", topic));
receiverData.setCustomMappingType("json");
} else {
receiverData.setEventAdapterType(THRIFT_ADAPTER_TYPE);
propertyList.add(new Property("events.duplicated.in.cluster", "false"));
receiverData.setCustomMappingType("wso2event");
}
receiverData.setPropertyList(propertyList);
artifactsDeployer.deployEventReceiver(receiverData, tenantId);
if (!skipPersist) {
// rdbms event publisher
String rdbmsPublisherName = getPublisherName(deviceType, tenantDomain, eventName) + "_rdbms_publisher";
EventPublisherData eventPublisherData = new EventPublisherData();
eventPublisherData.setName(rdbmsPublisherName);
eventPublisherData.setStreamName(streamName);
eventPublisherData.setStreamVersion(Constants.DEFAULT_STREAM_VERSION);
eventPublisherData.setEventAdaptorType("rdbms");
eventPublisherData.setCustomMappingType("map");
List<Property> publisherProps = new ArrayList<>();
publisherProps.add(new Property("datasource.name", "EVENT_DB"));
publisherProps.add(new Property("table.name", "table_" + rdbmsPublisherName.replace(".", "")));
publisherProps.add(new Property("execution.mode", "insert"));
eventPublisherData.setPropertyList(publisherProps);
artifactsDeployer.deployEventPublisher(eventPublisherData, tenantId);
}
// web socket event publisher
String wsPublisherName = getPublisherName(deviceType, tenantDomain, eventName) + "_ws_publisher";
EventPublisherData wsEventPublisherData = new EventPublisherData();
wsEventPublisherData.setName(wsPublisherName);
wsEventPublisherData.setStreamName(streamName);
wsEventPublisherData.setStreamVersion(Constants.DEFAULT_STREAM_VERSION);
wsEventPublisherData.setEventAdaptorType("websocket-local");
wsEventPublisherData.setCustomMappingType("json");
artifactsDeployer.deployEventPublisher(wsEventPublisherData, tenantId);
}
return Response.ok().build();
} catch (DeviceManagementException e) {
log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (EventStreamDeployerException e) {
log.error("Failed while deploying event stream definition, tenantDomain: " + tenantDomain, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (EventPublisherDeployerException e) {
log.error("Failed while deploying event publisher, tenantDomain: " + tenantDomain, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (EventReceiverDeployerException e) {
log.error("Failed while deploying event receiver, tenantDomain: " + tenantDomain, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
/**
* Delete device type specific artifacts from DAS.
@ -498,160 +584,174 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
// return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
// }
// }
private void publishEventReceivers(String streamNameWithVersion, TransportType transportType
, String requestedTenantDomain, boolean isSharedWithAllTenants, String deviceType)
throws RemoteException, UserStoreException, JWTClientException {
EventReceiverAdminServiceStub receiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub();
private void publishEventReceivers(String streamName, String version, TransportType transportType
, String requestedTenantDomain, boolean isSharedWithAllTenants, String deviceType,
String eventTopicStructure, String receiverName) throws EventReceiverConfigurationException {
EventReceiverService eventReceiverService = DeviceMgtAPIUtils.getEventReceiverService();
try {
TransportType transportTypeToBeRemoved = TransportType.HTTP;
if (transportType == TransportType.HTTP) {
transportTypeToBeRemoved = TransportType.MQTT;
}
String eventRecieverNameTobeRemoved = getReceiverName(deviceType, requestedTenantDomain, transportTypeToBeRemoved);
EventReceiverConfigurationDto eventReceiverConfigurationDto = receiverAdminServiceStub
.getActiveEventReceiverConfiguration(eventRecieverNameTobeRemoved);
if (eventReceiverConfigurationDto != null) {
EventReceiverAdminServiceCallbackHandler eventReceiverAdminServiceCallbackHandler =
new EventReceiverAdminServiceCallbackHandler() {
};
receiverAdminServiceStub.startundeployActiveEventReceiverConfiguration(eventRecieverNameTobeRemoved
, eventReceiverAdminServiceCallbackHandler);
// TransportType transportTypeToBeRemoved = TransportType.HTTP;
// if (transportType == TransportType.HTTP) {
// transportTypeToBeRemoved = TransportType.MQTT;
// }
// String eventRecieverNameTobeRemoved = getReceiverName(deviceType, requestedTenantDomain, transportTypeToBeRemoved);
EventReceiverConfiguration eventReceiverConfiguration =
eventReceiverService.getActiveEventReceiverConfiguration(receiverName);
if (eventReceiverConfiguration != null) {
eventReceiverService.undeployActiveEventReceiverConfiguration(receiverName);
}
String adapterType = OAUTH_MQTT_ADAPTER_TYPE;
BasicInputAdapterPropertyDto basicInputAdapterPropertyDtos[];
InputEventAdapterConfiguration inputEventAdapterConfiguration = new InputEventAdapterConfiguration();
Map<String, String> propertyMap = new HashMap<>();
if (transportType == TransportType.MQTT) {
basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[3];
inputEventAdapterConfiguration.setType(OAUTH_MQTT_ADAPTER_TYPE);
String topic;
if (isSharedWithAllTenants) {
topic = "+/" + deviceType + "/+/events";
if (!StringUtils.isEmpty(eventTopicStructure)) {
if (isSharedWithAllTenants) {
topic = eventTopicStructure.replace("${deviceId}", "+")
.replace("${deviceType}", deviceType)
.replace("${tenantDomain}", "+");
} else {
topic = eventTopicStructure.replace("${deviceId}", "+")
.replace("${deviceType}", deviceType)
.replace("${tenantDomain}", requestedTenantDomain);
}
} else {
topic = requestedTenantDomain + "/" + deviceType + "/+/events";
if (isSharedWithAllTenants) {
topic = "+/" + deviceType + "/+/events";
} else {
topic = requestedTenantDomain + "/" + deviceType + "/+/events";
}
}
basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("topic", topic);
basicInputAdapterPropertyDtos[1] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_TRANSFORMER_TYPE
, MQTT_CONTENT_TRANSFORMER);
basicInputAdapterPropertyDtos[2] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_VALIDATOR_TYPE
, MQTT_CONTENT_VALIDATOR);
propertyMap.put("topic", topic);
propertyMap.put(MQTT_CONTENT_TRANSFORMER_TYPE, MQTT_CONTENT_TRANSFORMER);
propertyMap.put(MQTT_CONTENT_VALIDATOR_TYPE, MQTT_CONTENT_VALIDATOR);
} else {
adapterType = THRIFT_ADAPTER_TYPE;
basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[1];
basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("events.duplicated.in.cluster", "false");
inputEventAdapterConfiguration.setType(THRIFT_ADAPTER_TYPE);
propertyMap.put("events.duplicated.in.cluster", "false");
}
String eventRecieverName = getReceiverName(deviceType, requestedTenantDomain, transportType);
if (receiverAdminServiceStub.getActiveEventReceiverConfiguration(eventRecieverName) == null) {
inputEventAdapterConfiguration.setProperties(propertyMap);
if (eventReceiverService.getActiveEventReceiverConfiguration(receiverName) == null) {
EventReceiverConfiguration configuration = new EventReceiverConfiguration();
configuration.setEventReceiverName(receiverName);
configuration.setToStreamName(streamName);
configuration.setToStreamVersion(version);
configuration.setFromAdapterConfiguration(inputEventAdapterConfiguration);
if (transportType == TransportType.MQTT) {
receiverAdminServiceStub.deployJsonEventReceiverConfiguration(eventRecieverName, streamNameWithVersion
, adapterType, null, basicInputAdapterPropertyDtos, false);
JSONInputMapping jsonInputMapping = new JSONInputMapping();
jsonInputMapping.setCustomMappingEnabled(false);
configuration.setInputMapping(jsonInputMapping);
eventReceiverService.deployEventReceiverConfiguration(configuration);
} else {
receiverAdminServiceStub.deployWso2EventReceiverConfiguration(eventRecieverName, streamNameWithVersion
, adapterType, null, null, null, basicInputAdapterPropertyDtos, false, null);
WSO2EventInputMapping wso2EventInputMapping = new WSO2EventInputMapping();
wso2EventInputMapping.setCustomMappingEnabled(false);
configuration.setInputMapping(wso2EventInputMapping);
eventReceiverService.deployEventReceiverConfiguration(configuration);
}
}
} finally {
cleanup(receiverAdminServiceStub);
} catch (EventReceiverConfigurationException e) {
log.error("Error while publishing event receiver" , e);
throw new EventReceiverConfigurationException(e);
}
}
private void publishStreamDefinitons(String streamName, String version, String deviceType
, EventAttributeList eventAttributes)
throws RemoteException, UserStoreException, JWTClientException {
EventStreamAdminServiceStub eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub();
private void publishStreamDefinitons(String streamName, String version, EventAttributeList eventAttributes)
throws MalformedStreamDefinitionException, EventStreamConfigurationException {
EventStreamService eventStreamService = DeviceMgtAPIUtils.getEventStreamService();
try {
EventStreamDefinitionDto eventStreamDefinitionDto = new EventStreamDefinitionDto();
eventStreamDefinitionDto.setName(streamName);
eventStreamDefinitionDto.setVersion(version);
EventStreamAttributeDto eventStreamAttributeDtos[] =
new EventStreamAttributeDto[eventAttributes.getList().size()];
EventStreamAttributeDto metaStreamAttributeDtos[] =
new EventStreamAttributeDto[1];
int i = 0;
StreamDefinition streamDefinition = new StreamDefinition(streamName, version);
List<org.wso2.carbon.databridge.commons.Attribute> payloadDataAttributes = new ArrayList<>();
for (Attribute attribute : eventAttributes.getList()) {
EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto();
eventStreamAttributeDto.setAttributeName(attribute.getName());
eventStreamAttributeDto.setAttributeType(attribute.getType().toString());
eventStreamAttributeDtos[i] = eventStreamAttributeDto;
i++;
payloadDataAttributes.add(new org.wso2.carbon.databridge.commons.Attribute(attribute.getName(),
org.wso2.carbon.databridge.commons.AttributeType.valueOf(attribute.getType().name())));
}
streamDefinition.setPayloadData(payloadDataAttributes);
List<org.wso2.carbon.databridge.commons.Attribute> metaDataAttributes = new ArrayList<>();
metaDataAttributes.add(new org.wso2.carbon.databridge.commons.Attribute(DEFAULT_DEVICE_ID_ATTRIBUTE,
org.wso2.carbon.databridge.commons.AttributeType.STRING));
streamDefinition.setMetaData(metaDataAttributes);
EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto();
eventStreamAttributeDto.setAttributeName(DEFAULT_DEVICE_ID_ATTRIBUTE);
eventStreamAttributeDto.setAttributeType(AttributeType.STRING.toString());
metaStreamAttributeDtos[0] = eventStreamAttributeDto;
eventStreamDefinitionDto.setPayloadData(eventStreamAttributeDtos);
eventStreamDefinitionDto.setMetaData(metaStreamAttributeDtos);
String streamId = streamName + ":" + version;
if (eventStreamAdminServiceStub.getStreamDefinitionDto(streamId) != null) {
eventStreamAdminServiceStub.editEventStreamDefinitionAsDto(eventStreamDefinitionDto, streamId);
if (eventStreamService.getStreamDefinition(streamDefinition.getStreamId()) != null) {
eventStreamService.removeEventStreamDefinition(streamName, version);
eventStreamService.addEventStreamDefinition(streamDefinition);
} else {
eventStreamAdminServiceStub.addEventStreamDefinitionAsDto(eventStreamDefinitionDto);
eventStreamService.addEventStreamDefinition(streamDefinition);
}
} finally {
cleanup(eventStreamAdminServiceStub);
} catch (MalformedStreamDefinitionException e) {
log.error("Error while initializing stream definition " , e);
throw new MalformedStreamDefinitionException(e);
} catch (EventStreamConfigurationException e) {
log.error("Error while configuring stream definition " , e);
throw new EventStreamConfigurationException(e);
}
}
/*
// private void publishEventStore(String streamName, String version, EventAttributeList eventAttributes)
// throws RemoteException, UserStoreException, JWTClientException,
// EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException {
// EventStreamPersistenceAdminServiceStub eventStreamPersistenceAdminServiceStub =
// DeviceMgtAPIUtils.getEventStreamPersistenceAdminServiceStub();
// try {
// AnalyticsTable analyticsTable = new AnalyticsTable();
// analyticsTable.setRecordStoreName(DEFAULT_EVENT_STORE_NAME);
// analyticsTable.setStreamVersion(version);
// analyticsTable.setTableName(streamName);
// analyticsTable.setMergeSchema(false);
// analyticsTable.setPersist(true);
// AnalyticsTableRecord analyticsTableRecords[] = new AnalyticsTableRecord[eventAttributes.getList().size() + 1];
// int i = 0;
// for (Attribute attribute : eventAttributes.getList()) {
// AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord();
// analyticsTableRecord.setColumnName(attribute.getName());
// analyticsTableRecord.setColumnType(attribute.getType().toString().toUpperCase());
// analyticsTableRecord.setFacet(false);
// analyticsTableRecord.setIndexed(false);
// analyticsTableRecord.setPersist(true);
// analyticsTableRecord.setPrimaryKey(false);
// analyticsTableRecord.setScoreParam(false);
// analyticsTableRecords[i] = analyticsTableRecord;
// i++;
// }
// AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord();
// analyticsTableRecord.setColumnName(DEFAULT_META_DEVICE_ID_ATTRIBUTE);
// analyticsTableRecord.setColumnType(AttributeType.STRING.toString().toUpperCase());
// analyticsTableRecord.setFacet(false);
// analyticsTableRecord.setIndexed(true);
// analyticsTableRecord.setPersist(true);
// analyticsTableRecord.setPrimaryKey(false);
// analyticsTableRecord.setScoreParam(false);
// analyticsTableRecords[i] = analyticsTableRecord;
// analyticsTable.setAnalyticsTableRecords(analyticsTableRecords);
// eventStreamPersistenceAdminServiceStub.addAnalyticsTable(analyticsTable);
// } finally {
// cleanup(eventStreamPersistenceAdminServiceStub);
// }
// }
*/
private void publishEventStore(String streamName, String version, String publisherName)
throws EventPublisherConfigurationException {
EventPublisherService eventPublisherService = DeviceMgtAPIUtils.getEventPublisherService();
private void publishWebsocketPublisherDefinition(String streamNameWithVersion, String deviceType)
throws RemoteException, UserStoreException, JWTClientException {
EventPublisherAdminServiceStub eventPublisherAdminServiceStub = DeviceMgtAPIUtils
.getEventPublisherAdminServiceStub();
try {
String eventPublisherName = deviceType.trim().replace(" ", "_") + "_websocket_publisher";
if (eventPublisherAdminServiceStub.getActiveEventPublisherConfiguration(eventPublisherName) == null) {
eventPublisherAdminServiceStub.deployJsonEventPublisherConfiguration(eventPublisherName
, streamNameWithVersion, DEFAULT_WEBSOCKET_PUBLISHER_ADAPTER_TYPE, null, null
, null, false);
if (eventPublisherService.getActiveEventPublisherConfiguration(publisherName) == null) {
EventPublisherConfiguration configuration = new EventPublisherConfiguration();
configuration.setEventPublisherName(publisherName);
configuration.setFromStreamName(streamName);
configuration.setFromStreamVersion(version);
MapOutputMapping mapOutputMapping = new MapOutputMapping();
mapOutputMapping.setCustomMappingEnabled(false);
configuration.setOutputMapping(mapOutputMapping);
OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration();
outputEventAdapterConfiguration.setType("rdbms");
Map<String, String> staticProperties = new HashMap<>();
staticProperties.put("datasource.name", "EVENT_DB");
staticProperties.put("execution.mode", "insert");
staticProperties.put("table.name", "table_" + publisherName.replace(".", ""));
outputEventAdapterConfiguration.setStaticProperties(staticProperties);
configuration.setProcessEnabled(true);
configuration.setToAdapterConfiguration(outputEventAdapterConfiguration);
eventPublisherService.deployEventPublisherConfiguration(configuration);
}
} finally {
cleanup(eventPublisherAdminServiceStub);
} catch (EventPublisherConfigurationException e) {
log.error("Error while publishing to rdbms store" , e);
throw new EventPublisherConfigurationException(e);
}
}
private void publishWebsocketPublisherDefinition(String streamName, String version, String publisherName)
throws EventPublisherConfigurationException {
EventPublisherService eventPublisherService = DeviceMgtAPIUtils.getEventPublisherService();
try {
if (eventPublisherService.getActiveEventPublisherConfiguration(publisherName) == null) {
EventPublisherConfiguration configuration = new EventPublisherConfiguration();
configuration.setEventPublisherName(publisherName);
configuration.setFromStreamName(streamName);
configuration.setFromStreamVersion(version);
JSONOutputMapping jsonOutputMapping = new JSONOutputMapping();
jsonOutputMapping.setCustomMappingEnabled(false);
configuration.setOutputMapping(jsonOutputMapping);
OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration();
outputEventAdapterConfiguration.setType("websocket-local");
configuration.setToAdapterConfiguration(outputEventAdapterConfiguration);
eventPublisherService.deployEventPublisherConfiguration(configuration);
}
} catch (EventPublisherConfigurationException e) {
log.error("Error while publishing to websocket-local" , e);
throw new EventPublisherConfigurationException(e);
}
}
private BasicInputAdapterPropertyDto getBasicInputAdapterPropertyDto(String key, String value) {
BasicInputAdapterPropertyDto basicInputAdapterPropertyDto = new BasicInputAdapterPropertyDto();
basicInputAdapterPropertyDto.setKey(key);
@ -667,6 +767,13 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
return deviceType.replace(" ", "_").trim() + "-" + tenantDomain + "-" + transportType.toString() + "-receiver";
}
private String getReceiverName(String deviceType, String tenantDomain, TransportType transportType, String eventName) {
return eventName + "-" + getReceiverName(deviceType, tenantDomain, transportType);
}
private String getPublisherName(String tenantDomain, String deviceType, String eventName) {
return eventName + "_" + tenantDomain.replace(".", "_") + "_" + deviceType;
}
private void cleanup(Stub stub) {
if (stub != null) {

@ -37,33 +37,26 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import com.google.gson.Gson;
import io.entgra.application.mgt.common.ApplicationInstallResponse;
import io.entgra.application.mgt.common.SubscriptionType;
import io.entgra.application.mgt.common.exception.SubscriptionManagementException;
import io.entgra.application.mgt.common.services.ApplicationManager;
import io.entgra.application.mgt.common.services.SubscriptionManager;
import io.entgra.application.mgt.core.util.HelperUtil;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
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.keymgt.extension.DCRResponse;
import org.wso2.carbon.apimgt.keymgt.extension.TokenRequest;
import org.wso2.carbon.apimgt.keymgt.extension.TokenResponse;
import org.wso2.carbon.apimgt.keymgt.extension.exception.KeyMgtException;
import org.wso2.carbon.apimgt.keymgt.extension.service.KeyMgtService;
import org.wso2.carbon.apimgt.keymgt.extension.service.KeyMgtServiceImpl;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.application.mgt.common.ApplicationInstallResponse;
import io.entgra.application.mgt.common.SubscriptionType;
import io.entgra.application.mgt.common.exception.SubscriptionManagementException;
import io.entgra.application.mgt.common.services.SubscriptionManager;
import io.entgra.application.mgt.core.util.HelperUtil;
import org.wso2.carbon.device.mgt.common.DeviceFilters;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.OperationLogFilters;
import org.wso2.carbon.device.mgt.common.MDMAppConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo;
import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo;
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.authorization.DeviceAccessAuthorizationException;
@ -72,12 +65,8 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshotWrapper;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException;
import org.wso2.carbon.device.mgt.common.exceptions.UnAuthorizedException;
import org.wso2.carbon.device.mgt.common.exceptions.*;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
@ -91,6 +80,8 @@ import org.wso2.carbon.device.mgt.common.search.PropertyMap;
import org.wso2.carbon.device.mgt.common.search.SearchContext;
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceStatus;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
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.dao.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
@ -103,19 +94,10 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService;
import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl;
import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceCompliance;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationList;
import org.wso2.carbon.device.mgt.jaxrs.beans.OperationStatusBean;
import org.wso2.carbon.device.mgt.jaxrs.beans.ComplianceDeviceList;
import org.wso2.carbon.device.mgt.jaxrs.beans.OperationRequest;
import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationUninstallation;
import org.wso2.carbon.device.mgt.jaxrs.beans.*;
import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
@ -128,29 +110,17 @@ import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerSer
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.validation.constraints.Size;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
@ -199,10 +169,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@QueryParam("limit") int limit) {
try {
if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(role)) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Request contains both name and role " +
"parameters. Only one is allowed " +
"at once.").build()).build();
String msg = "Request contains both name and role parameters. Only one is allowed at once.";
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
// RequestValidationUtil.validateSelectionCriteria(type, user, roleName, ownership, status);
RequestValidationUtil.validatePaginationParameters(offset, limit);
@ -291,9 +259,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
try {
sinceDate = format.parse(ifModifiedSince);
} catch (ParseException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Invalid date " +
"string is provided in 'If-Modified-Since' header").build()).build();
String msg = "Invalid date string is provided in [If-Modified-Since] header";
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
request.setSince(sinceDate);
if (requireDeviceInfo) {
@ -312,9 +279,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
try {
sinceDate = format.parse(since);
} catch (ParseException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Invalid date " +
"string is provided in 'since' filter").build()).build();
String msg = "Invalid date string is provided in [since] filter";
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
request.setSince(sinceDate);
if (requireDeviceInfo) {
@ -387,103 +353,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
}
@GET
@Override
@Path("/traccar-user-token")
public Response getTraccarUserToken() {
if (HttpReportingUtil.isTrackerEnabled()) {
String currentUser = CarbonContext.getThreadLocalCarbonContext().getUsername();
DeviceAPIClientService deviceAPIClientService = DeviceMgtAPIUtils.getDeviceAPIClientService();
JSONObject obj = new JSONObject(deviceAPIClientService.returnUser(currentUser));
if (obj.has("error")) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(obj.getString("error")).build();
} else {
int userId = obj.getInt("id");
List<Integer> traccarValidIdList = new ArrayList<>();
/*Get Device Id List*/
try {
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
DeviceMgtAPIUtils.getDeviceAccessAuthorizationService();
PaginationRequest request = new PaginationRequest(0, 0);
PaginationResult result;
DeviceList devices = new DeviceList();
List<String> status = new ArrayList<>();
status.add("ACTIVE");
status.add("INACTIVE");
status.add("CREATED");
status.add("UNREACHABLE");
request.setStatusList(status);
// this is the user who initiates the request
String authorizedUser = MultitenantUtils.getTenantAwareUsername(currentUser);
// check whether the user is device-mgt admin
if (!deviceAccessAuthorizationService.isDeviceAdminUser()) {
request.setOwner(authorizedUser);
}
result = dms.getAllDevicesIds(request);
if (result == null || result.getData() == null || result.getData().isEmpty()) {
devices.setList(new ArrayList<Device>());
devices.setCount(0);
} else {
devices.setList((List<Device>) result.getData());
devices.setCount(result.getRecordsTotal());
}
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
TrackerDeviceInfo trackerDevice;
for (Device device : devices.getList()) {
trackerDevice = deviceAPIClientService.getTrackerDevice(device.getId(), tenantId);
if(trackerDevice != null) {
int traccarDeviceId = trackerDevice.getTraccarDeviceId();
boolean getPermission = deviceAPIClientService.getUserIdofPermissionByDeviceIdNUserId(traccarDeviceId, userId);
traccarValidIdList.add(traccarDeviceId);
if (!getPermission) {
deviceAPIClientService.addTrackerUserDevicePermission(userId, traccarDeviceId);
}
}
}
//Remove necessary
List<TrackerPermissionInfo> getAllUserDevices =
deviceAPIClientService.getUserIdofPermissionByUserIdNIdList(userId, traccarValidIdList);
for (TrackerPermissionInfo getAllUserDevice : getAllUserDevices) {
deviceAPIClientService.removeTrackerUserDevicePermission(
getAllUserDevice.getTraccarUserId(),
getAllUserDevice.getTraccarDeviceId(),
TraccarHandlerConstants.Types.REMOVE_TYPE_SINGLE);
}
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching all enrolled devices. ";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceAccessAuthorizationException e) {
String msg = "Error occurred while checking device access authorization. ";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (TrackerManagementDAOException e) {
String msg = "Error occurred while mapping with deviceId .";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ExecutionException e) {
String msg = "Execution error occurred handling traccar device permissions";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (InterruptedException e) {
String msg = "Interruption error occurred handling traccar device permissions";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
/*Get Device Id List*/
return Response.status(Response.Status.OK).entity(obj.getString("token")).build();
}
} else {
return Response.status(Response.Status.BAD_REQUEST).entity("Traccar is not enabled").build();
}
}
/**
* Validate group Id and group Id greater than 0 and exist.
*
@ -547,6 +416,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
String msg = "Error occurred while retrieving role list of user '" + authorizedUser + "'";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}catch (BadRequestException e){
String msg = "Error occurred while validating the device group.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
PaginationResult result = dms.getAllDevices(request, false);
@ -563,7 +436,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
return Response.status(Response.Status.OK).entity(devices).build();
} catch (BadRequestException e) {
String msg = "Invalid type, use either 'path' or 'full'";
String msg = "Invalid type, use either [path] or [full]";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (UnAuthorizedException e) {
@ -597,12 +470,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
boolean response = deviceManagementProviderService.disenrollDevice(deviceIdentifier);
return Response.status(Response.Status.OK).entity(response).build();
} catch (DeviceManagementException e) {
String msg = "Error encountered while deleting device of type : " + deviceType + " and " +
"ID : " + deviceId;
String msg = "Error encountered while deleting requested device of type : " + deviceType ;
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()
).build();
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@ -624,11 +494,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.CREATED).entity(response).build();
} catch (DeviceManagementException e) {
log.error("Error encountered while updating device of type : " + deviceType + " and " +
"ID : " + deviceId);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Error while updating " +
"device of type " + deviceType + " and ID : " + deviceId).build()).build();
String msg = "Error encountered while updating requested device of type : " + deviceType ;
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@ -669,10 +537,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
sinceDate = format.parse(ifModifiedSince);
deviceData.setLastModifiedDate(sinceDate);
} catch (ParseException e) {
String msg = "Invalid date string is provided in 'If-Modified-Since' header";
String msg = "Invalid date string is provided in [If-Modified-Since] header";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@ -699,9 +566,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " +
"after the timestamp provided in 'If-Modified-Since' header").build();
}
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_NOT_FOUND).setMessage("Requested device of type '" +
type + "', which carries id '" + id + "' does not exist").build()).build();
String msg = "Requested device of type " + type + " does not exist";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(device).build();
}
@ -722,7 +588,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
dms);
return Response.status(Response.Status.OK).entity(snapshotWrapper).build();
} catch (BadRequestException e) {
String msg = "Invalid type, use either 'path' or 'full'";
String msg = "Invalid type, use either [path] or [full]";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (UnAuthorizedException e) {
@ -768,12 +634,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
try {
sinceDate = format.parse(ifModifiedSince);
} catch (ParseException e) {
String message = "Error occurred while parse the since date.Invalid date string is provided in " +
"'If-Modified-Since' header";
String message = "Invalid date string is provided in [If-Modified-Since] header";
log.error(message, e);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Invalid date " +
"string is provided in 'If-Modified-Since' header").build()).build();
return Response.status(Response.Status.BAD_REQUEST).entity(message).build();
}
}
if (sinceDate != null) {
@ -782,16 +645,15 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
String message = "No device is modified after the timestamp provided in 'If-Modified-Since' header";
log.error(message);
return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " +
"after the timestamp provided in 'If-Modified-Since' header").build();
"after the timestamp provided in [If-Modified-Since] header").build();
}
} else {
device = dms.getDevice(id, requireDeviceInfo);
}
if (device == null) {
String message = "Device does not exist with id '" + id + "'";
String message = "Device does not exist";
log.error(message);
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage(message).build()).build();
return Response.status(Response.Status.NOT_FOUND).entity(message).build();
}
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, device.getType());
// check whether the user is authorized
@ -816,6 +678,32 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.OK).entity(device).build();
}
@POST
@Path("/enrollment/guide")
@Override
public Response sendEnrollmentGuide(String enrolmentGuide) {
if (log.isDebugEnabled()) {
log.debug("Sending enrollment invitation mail to existing user.");
}
DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
if (!config.getEnrollmentGuideConfiguration().isEnabled()) {
String msg = "Sending enrollment guide config is not enabled.";
log.error(msg);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
}
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
try {
dms.sendEnrolmentGuide(enrolmentGuide);
return Response.status(Response.Status.OK).entity("Invitation mails have been sent.").build();
} catch (DeviceManagementException e) {
String msg = "Error occurred sending mail to group in enrollment guide";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
}
@POST
@Path("/type/any/list")
@Override
@ -823,7 +711,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
DeviceManagementProviderService deviceManagementProviderService =
DeviceMgtAPIUtils.getDeviceManagementService();
if (deviceIds == null || deviceIds.isEmpty()) {
String msg = "Required values of device identifiers are not set..";
String msg = "Required values of device identifiers are not set.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).build();
}
@ -887,6 +775,107 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
return Response.status(Response.Status.OK).entity(deviceInfo).build();
}
@GET
@Path("/{type}/{id}/config")
@Override
public Response getDeviceConfiguration(
@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
DeviceConfig deviceConfig = new DeviceConfig();
deviceConfig.setDeviceId(id);
deviceConfig.setType(type);
// find token validity time
DeviceManagementProviderService deviceManagementProviderService =
DeviceMgtAPIUtils.getDeviceManagementService();
int validityTime = 3600;
// add scopes for event topics
List<String> mqttEventTopicStructure = new ArrayList<>();
try {
DeviceType deviceType = deviceManagementProviderService.getDeviceType(type);
if (deviceType != null) {
if (deviceType.getDeviceTypeMetaDefinition().isLongLivedToken()) {
validityTime = Integer.MAX_VALUE;
}
mqttEventTopicStructure = deviceType.getDeviceTypeMetaDefinition().getMqttEventTopicStructures();
} else {
String msg = "Device not found, device id : " + id + ", device type : " + type;
log.error(msg);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving device, device id : " + id + ", device type : " + type;
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String applicationName = type.replace(" ", "").replace("_", "")
+ "_" + tenantDomain;
KeyMgtService keyMgtService = new KeyMgtServiceImpl();
try {
DCRResponse dcrResponse = keyMgtService.dynamicClientRegistration(applicationName, username,
"client_credentials", null, new String[] {"device_management"}, false, validityTime);
deviceConfig.setClientId(dcrResponse.getClientId());
deviceConfig.setClientSecret(dcrResponse.getClientSecret());
StringBuilder scopes = new StringBuilder("device_" + type.replace(" ", "")
.replace("_", "") + "_" + id);
for (String topic : mqttEventTopicStructure) {
if (topic.contains("${deviceId}")) {
topic = topic.replace("${deviceId}", id);
}
topic = topic.replace("/",":");
// scopes.append(" perm:topic:sub:".concat(topic));
scopes.append(" perm:topic:pub:".concat(topic));
}
// add scopes for retrieve operation topic /tenantDomain/deviceType/deviceId/operation/#
scopes.append(" perm:topic:sub:" + tenantDomain + ":" + type + ":" + id + ":operation");
// add scopes for update operation /tenantDomain/deviceType/deviceId/update/operation
scopes.append(" perm:topic:pub:" + tenantDomain + ":" + type + ":" + id + ":update:operation");
TokenRequest tokenRequest = new TokenRequest(dcrResponse.getClientId(), dcrResponse.getClientSecret(),
null, scopes.toString(), "client_credentials", null,
null, null, null, validityTime);
TokenResponse tokenResponse = keyMgtService.generateAccessToken(tokenRequest);
deviceConfig.setAccessToken(tokenResponse.getAccessToken());
deviceConfig.setRefreshToken(tokenResponse.getRefreshToken());
try {
deviceConfig.setPlatformConfiguration(deviceManagementProviderService.getConfiguration(type));
} catch (DeviceManagementException e) {
String msg = "Error occurred while reading platform configurations token, device id : " + id + ", device type : " + type;
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
deviceConfig.setMqttGateway("tcp://" + System.getProperty("mqtt.broker.host") + ":" + System.getProperty("mqtt.broker.port"));
deviceConfig.setHttpGateway("http://" + System.getProperty("iot.gateway.host") + ":" + System.getProperty("iot.gateway.http.port"));
deviceConfig.setHttpsGateway("https://" + System.getProperty("iot.gateway.host") + ":" + System.getProperty("iot.gateway.https.port"));
} catch (KeyMgtException e) {
String msg = "Error occurred while creating oauth application, device id : " + id + ", device type : " + type;
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (org.wso2.carbon.apimgt.keymgt.extension.exception.BadRequestException e) {
String msg = "Error occurred while generating token, device id : " + id + ", device type : " + type;
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
return Response.status(Response.Status.OK).entity(deviceConfig).build();
}
@GET
@ -903,9 +892,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
try {
fm = dms.getFeatureManager(type);
} catch (DeviceTypeNotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder()
.setMessage("No device type found with name '" + type + "'").build()).build();
String msg = "No device type found with name : " + type ;
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
if (fm != null) {
features = fm.getFeatures();
@ -1126,8 +1114,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (InputValidationException e) {
String msg = "Error occurred while fetching the operations for the '" + type + "' device, which " +
"carries the id '" + id + "'";
String msg = "Error occurred while fetching the operations for the type : " + type + " device";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (DeviceManagementException e) {
@ -1136,7 +1123,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (DeviceTypeNotFoundException e) {
String msg = "No device type found with name '" + type + "'";
String msg = "No device type found with name : " + type ;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
@ -1246,11 +1233,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
boolean response = deviceManagementProviderService.changeDeviceStatus(deviceIdentifier, newsStatus);
return Response.status(Response.Status.OK).entity(response).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while changing device status of type : " + type + " and " +
"device id : " + id;
String msg = "Error occurred while changing device status of device type : " + type ;
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@ -1262,7 +1247,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
* @return {@link Response} object
*/
@GET
@Path("/{type}/{id}/getstatushistory")
@Path("/{type}/{id}/status-history")
public Response getDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id) {
//TODO check authorization for this
@ -1278,11 +1263,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
List<DeviceStatus> deviceStatusHistory = deviceManagementProviderService.getDeviceStatusHistory(persistedDevice);
return Response.status(Response.Status.OK).entity(deviceStatusHistory).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while retreiving device status history for device of type : " + type + " and " +
"device id : " + id;
String msg = "Error occurred while retrieving device status history for device of type : " + type ;
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@ -1294,7 +1277,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
* @return {@link Response} object
*/
@GET
@Path("/{type}/{id}/getenrolmentstatushistory")
@Path("/{type}/{id}/enrolment-status-history")
public Response getCurrentEnrolmentDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id) {
//TODO check authorization for this or current enrolment should be based on for the enrolment associated with the user
@ -1310,11 +1293,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
List<DeviceStatus> deviceStatusHistory = deviceManagementProviderService.getDeviceCurrentEnrolmentStatusHistory(persistedDevice);
return Response.status(Response.Status.OK).entity(deviceStatusHistory).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while retreiving device status history for device of type : " + type + " and " +
"device id : " + id;
String msg = "Error occurred while retrieving device status history for device of type : " + type;
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@ -1391,7 +1372,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build();
} catch (DeviceManagementException e) {
String errorMessage = "Issue in retrieving deivce management service instance";
String errorMessage = "Issue in retrieving device management service instance";
log.error(errorMessage, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build();
@ -1591,7 +1572,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
DeviceType deviceTypeObj = DeviceManagerUtil.getDeviceType(
deviceType, tenantId);
if (deviceTypeObj == null) {
String msg = "Error, device of type: " + deviceType + " does not exist";
String msg = "Device of type: " + deviceType + " does not exist";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}

@ -141,16 +141,15 @@ public class DeviceTypeManagementServiceImpl implements DeviceTypeManagementServ
DeviceManagementProviderService dms;
try {
if (StringUtils.isEmpty(type)) {
return Response.status(Response.Status.BAD_REQUEST).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Type cannot be empty.").build()).build();
String msg = "Type cannot be empty.";
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
dms = DeviceMgtAPIUtils.getDeviceManagementService();
FeatureManager fm = dms.getFeatureManager(type);
if (fm == null) {
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("No feature manager is " +
"registered with the given type '" + type + "'").build()).build();
String msg = "No feature manager is registered with the given type : " + type ;
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
if (StringUtils.isEmpty(hidden)) {
@ -165,11 +164,9 @@ public class DeviceTypeManagementServiceImpl implements DeviceTypeManagementServ
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (DeviceTypeNotFoundException e) {
String msg = "No device type found with name '" + type + "'";
String msg = "No device type found with name : " + type ;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder()
.setMessage(msg).build()).build();
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(features).build();
}

@ -63,6 +63,7 @@ import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.EventAction;
import org.wso2.carbon.device.mgt.jaxrs.beans.GeofenceWrapper;
import org.wso2.carbon.device.mgt.jaxrs.exception.BadRequestException;
import org.wso2.carbon.device.mgt.jaxrs.service.api.GeoLocationBasedService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
@ -107,8 +108,9 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@QueryParam("from") long from, @QueryParam("to") long to) {
try {
if (!DeviceManagerUtil.isPublishLocationResponseEnabled()) {
String msg = "Unable to retrieve Geo Device stats. Geo Data publishing does not enabled.";
return Response.status(Response.Status.BAD_REQUEST.getStatusCode())
.entity("Unable to retrive Geo Device stats. Geo Data publishing does not enabled.").build();
.entity(msg).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(e.getMessage()).build();
@ -277,7 +279,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
if (log.isDebugEnabled()) {
log.debug("Device not found: " + identifier.toString());
}
return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
String msg = "Device not found.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
@ -288,12 +291,11 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
} catch (AlertAlreadyExistException e) {
String error = "A geo alert with this name already exists.";
String error = "A geo alert with this name already exists. Try with another name.";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
} catch (DeviceManagementException e) {
String error = "Error occurred while retrieving the device enrollment info of " +
deviceType + " with id: " + deviceId;
String error = "Error occurred while retrieving the device enrollment info of requested "+ deviceType + " device.";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
@ -314,7 +316,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
} catch (AlertAlreadyExistException e) {
String error = "A geo alert with this name already exists.";
String error = "A geo alert with this name already exists. Try with another name.";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
@ -344,23 +346,23 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
if (log.isDebugEnabled()) {
log.debug("Device not found: " + identifier.toString());
}
return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
String msg = "Device not found.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
geoService.updateGeoAlert(alert, identifier, alertType, device.getEnrolmentInfo().getOwner());
return Response.ok().build();
} catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) {
String error = "Error occurred while creating the geo alert for " + deviceType + " with id: " + deviceId;
String error = "Error occurred while updating the geo alert for " + deviceType + " with id: " + deviceId;
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
} catch (AlertAlreadyExistException e) {
String error = "A geo alert with this name already exists.";
String error = "A geo alert with this name already exists. Try with another name.";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
} catch (DeviceManagementException e) {
String error = "Error occurred while retrieving the device enrollment info of " +
deviceType + " with id: " + deviceId;
String error = "Error occurred while retrieving the device enrollment info of requested " + deviceType + " device.";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
@ -380,7 +382,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
} catch (AlertAlreadyExistException e) {
String error = "A geo alert with this name already exists.";
String error = "A geo alert with this name already exists. Try with another name.";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
@ -410,7 +412,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
if (log.isDebugEnabled()) {
log.debug("Device not found: " + identifier.toString());
}
return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
String msg = "Device not found.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
@ -421,8 +424,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
} catch (DeviceManagementException e) {
String error = "Error occurred while retrieving the device enrollment info of " +
deviceType + " with id: " + deviceId;
String error = "Error occurred while retrieving the device enrollment info of requested " +deviceType + " device";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
@ -467,7 +469,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
if (log.isDebugEnabled()) {
log.debug("Device not found: " + identifier.toString());
}
return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
String msg = "Device not found.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
@ -497,8 +500,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
} catch (DeviceManagementException e) {
String error = "Error occurred while retrieving the device enrollment info of " +
deviceType + " with id: " + deviceId;
String error = "Error occurred while retrieving the device enrollment info of requested " + deviceType + " device";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
@ -687,9 +689,9 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@Consumes("application/json")
@Produces("application/json")
public Response createGeofence(GeofenceWrapper geofenceWrapper) {
RequestValidationUtil.validateGeofenceData(geofenceWrapper);
RequestValidationUtil.validateEventConfigurationData(geofenceWrapper.getEventConfig());
try {
RequestValidationUtil.validateGeofenceData(geofenceWrapper);
RequestValidationUtil.validateEventConfigurationData(geofenceWrapper.getEventConfig());
GeofenceData geofenceData = mapRequestGeofenceData(geofenceWrapper);
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
if (!geoService.createGeofence(geofenceData)) {
@ -699,6 +701,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
return Response.status(Response.Status.CREATED).entity("Geo Fence record created successfully").build();
} catch (BadRequestException e){
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (GeoLocationBasedServiceException e) {
String msg = "Failed to create geofence";
log.error(msg, e);
@ -895,9 +899,9 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
public Response updateGeofence(GeofenceWrapper geofenceWrapper,
@PathParam("fenceId") int fenceId,
@QueryParam("eventIds") int[] eventIds) {
RequestValidationUtil.validateGeofenceData(geofenceWrapper);
RequestValidationUtil.validateEventConfigurationData(geofenceWrapper.getEventConfig());
try {
RequestValidationUtil.validateGeofenceData(geofenceWrapper);
RequestValidationUtil.validateEventConfigurationData(geofenceWrapper.getEventConfig());
GeofenceData geofenceData = mapRequestGeofenceData(geofenceWrapper);
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
if (!geoService.updateGeofence(geofenceData, fenceId)) {
@ -912,6 +916,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
geoService.updateGeoEventConfigurations(geofenceData, eventsToRemove,
geofenceData.getGroupIds(), fenceId);
return Response.status(Response.Status.CREATED).entity("Geo Fence update successfully").build();
} catch (BadRequestException e){
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (GeoLocationBasedServiceException e) {
String msg = "Failed to update geofence";
log.error(msg, e);

@ -167,7 +167,7 @@ public class GroupManagementServiceImpl implements GroupManagementService {
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (GroupAlreadyExistException e) {
String msg = "Group already exists with name " + group.getName() + ".";
String msg = "Group already exists with name : " + group.getName() + ".";
log.warn(msg);
return Response.status(Response.Status.CONFLICT).entity(msg).build();
}
@ -181,7 +181,7 @@ public class GroupManagementServiceImpl implements GroupManagementService {
if (deviceGroup != null) {
return Response.status(Response.Status.OK).entity(deviceGroup).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
return Response.status(Response.Status.NOT_FOUND).entity("Group not found.").build();
}
} catch (GroupManagementException e) {
String error = "Error occurred while getting the group.";
@ -198,7 +198,7 @@ public class GroupManagementServiceImpl implements GroupManagementService {
if (deviceGroup != null) {
return Response.status(Response.Status.OK).entity(deviceGroup).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
return Response.status(Response.Status.NOT_FOUND).entity("Group not found.").build();
}
} catch (GroupManagementException e) {
String error = "Error occurred while getting the group.";
@ -220,11 +220,11 @@ public class GroupManagementServiceImpl implements GroupManagementService {
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (GroupNotExistException e) {
String msg = "Group doesn't exist with ID '" + deviceGroup.getGroupId() + "'.";
String msg = "Group does not exist.";
log.warn(msg);
return Response.status(Response.Status.CONFLICT).entity(msg).build();
} catch (GroupAlreadyExistException e) {
String msg = "Group already exists with name '" + deviceGroup.getName() + "'.";
String msg = "Group already exists with name : '" + deviceGroup.getName() + "'.";
log.warn(msg);
return Response.status(Response.Status.CONFLICT).entity(msg).build();
}

@ -18,20 +18,27 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataKeyNotFoundException;
import org.wso2.carbon.device.mgt.common.exceptions.NotFoundException;
import org.wso2.carbon.device.mgt.common.metadata.mgt.Metadata;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException;
import org.wso2.carbon.device.mgt.common.metadata.mgt.MetadataManagementService;
import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelTheme;
import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest;
import org.wso2.carbon.device.mgt.jaxrs.beans.MetadataList;
import org.wso2.carbon.device.mgt.jaxrs.service.api.MetadataService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.ws.rs.Consumes;
@ -147,4 +154,20 @@ public class MetadataServiceImpl implements MetadataService {
}
}
/**
* Useful to send files as application/octet-stream responses
*/
private Response sendFileStream(byte[] content) throws IOException {
try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(content)) {
Response.ResponseBuilder response = Response
.ok(binaryDuplicate, MediaType.APPLICATION_OCTET_STREAM);
response.status(Response.Status.OK);
response.header("Content-Length", content.length);
return response.build();
} catch (IOException e) {
String msg = "Error occurred while creating input stream from buffer array. ";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

@ -40,6 +40,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
@ -83,8 +84,9 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
.validatePolicyDetails(policyWrapper);
// validation failure results;
if (!features.isEmpty()) {
log.error("Policy feature/s validation failed.");
return Response.status(Response.Status.BAD_REQUEST).entity(features).build();
String msg = "Policy feature/s validation failed." ;
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg + " Features : " + features).build();
}
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
@ -212,9 +214,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
policy = policyAdministratorPoint.getPolicy(id);
if (policy == null) {
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(
"No policy found with the id '" + id + "'").build()).build();
String msg = "Policy not found.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
} catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving policy corresponding to the id '" + id + "'";
@ -233,8 +234,9 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
.validatePolicyDetails(policyWrapper);
// validation failure results;
if (!features.isEmpty()) {
log.error("Policy feature/s validation failed.");
return Response.status(Response.Status.BAD_REQUEST).entity(features).build();
String msg = "Policy feature/s validation failed." ;
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg + " Features : " + features).build();
}
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
try {
@ -296,10 +298,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
//TODO:Check of this logic is correct
String modifiedInvalidPolicyIds =
invalidPolicyIds.substring(0, invalidPolicyIds.length() - 1);
return Response.status(Response.Status.BAD_REQUEST).
entity(new ErrorResponse.ErrorResponseBuilder().
setMessage("Policies with the policy ID " + modifiedInvalidPolicyIds +
" doesn't exist").build()).build();
String msg = "Policies does not exist.";
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@ -329,9 +329,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
return Response.status(Response.Status.OK).entity("Selected policies have been successfully activated")
.build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Selected policies have " +
"not been activated").build()).build();
String msg = "Selected policies have not been activated.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
}
@ -361,9 +360,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
return Response.status(Response.Status.OK).entity("Selected policies have been successfully " +
"deactivated").build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Selected policies have " +
"not been deactivated").build()).build();
String msg = "Selected policies have not been activated.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
}
@ -412,9 +410,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
+ "updated.").build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Policy priorities did "
+ "not update. Bad Request.").build()).build();
String msg = "Policy priorities did not update. Bad Request.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
}
@ -440,9 +437,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
}
policy = policyManagementService.getAppliedPolicyToDevice(device);
if (policy == null) {
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(
"No policy found for device ID '" + deviceId + "'"+ deviceId).build()).build();
String msg = "Policy not found for the requested device.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
} catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving policy corresponding to the id '" + deviceType + "'"+ deviceId;
@ -491,8 +487,9 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
= RequestValidationUtil.validateProfileFeatures(profileFeaturesList);
// validation failure results;
if (!features.isEmpty()) {
log.error("Policy feature/s validation failed.");
return Response.status(Response.Status.BAD_REQUEST).entity(features).build();
String msg = "Policy feature/s validation failed." ;
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg + " Features : " +features).build();
}
return Response.status(Response.Status.OK).entity("Valid request").build();
@ -508,18 +505,13 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
RequestValidationUtil.validatePaginationParameters(offset, limit);
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
List<Policy> policies;
List<Policy> filteredPolicies;
PolicyList targetPolicies = new PolicyList();
PaginationRequest request = new PaginationRequest(offset, limit);
try {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
policies = policyAdministratorPoint.getPolicyList();
targetPolicies.setCount(policies.size());
if (offset == 0 && limit == 0) {
targetPolicies.setList(policies);
} else {
filteredPolicies = FilteringUtil.getFilteredList(policies, offset, limit);
targetPolicies.setList(filteredPolicies);
}
policies = policyAdministratorPoint.getPolicyList(request);
targetPolicies.setCount(policyAdministratorPoint.getPolicyCount());
targetPolicies.setList(policies);
} catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving all available policies";
log.error(msg, e);

@ -169,8 +169,9 @@ public class RoleManagementServiceImpl implements RoleManagementService {
try {
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
if (!userRealm.getUserStoreManager().isExistingRole(roleName)) {
return Response.status(404).entity(new ErrorResponse.ErrorResponseBuilder().setMessage(
"No role exists with the name '" + roleName + "'").build()).build();
String msg = "No role exists with the name : " + roleName ;
return Response.status(404).entity(msg).build();
}
final UIPermissionNode rolePermissions = this.getUIPermissionNode(roleName, userRealm);
@ -249,9 +250,8 @@ public class RoleManagementServiceImpl implements RoleManagementService {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
if (!userStoreManager.isExistingRole(roleName)) {
return Response.status(404).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" +
roleName + "'").build()).build();
String msg = "No role exists with the name : " + roleName ;
return Response.status(404).entity(msg).build();
}
roleInfo.setRoleName(roleName);
roleInfo.setUsers(userStoreManager.getUserListOfRole(roleName));
@ -325,7 +325,7 @@ public class RoleManagementServiceImpl implements RoleManagementService {
}
if (ErrorMessages.ERROR_CODE_ROLE_ALREADY_EXISTS.getCode().equals(errorCode)) {
String roleName = roleInfo.getRoleName().split("/")[1];
String msg = "Role already exists with name " + roleName + ".";
String msg = "Role already exists with name : " + roleName + ". Try with another role name.";
log.warn(msg);
return Response.status(Response.Status.CONFLICT).entity(msg).build();
} else {
@ -354,10 +354,8 @@ public class RoleManagementServiceImpl implements RoleManagementService {
roleName = userStoreName + "/" + roleName;
}
if (roles.size() < 2) {
return Response.status(400).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("Combining Roles requires at least two roles.")
.build()
).build();
String msg = "Combining Roles requires at least two roles.";
return Response.status(400).entity(msg).build();
}
for (String role : roles) {
RequestValidationUtil.validateRoleName(role);
@ -374,9 +372,7 @@ public class RoleManagementServiceImpl implements RoleManagementService {
mergePermissions(new UIPermissionNode[]{getRolePermissions(role)}, permsSet);
}
} catch (IllegalArgumentException e) {
return Response.status(404).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(e.getMessage()).build()
).build();
return Response.status(404).entity(e.getMessage()).build();
}
Permission[] permissions = permsSet.toArray(new Permission[permsSet.size()]);
@ -424,9 +420,8 @@ public class RoleManagementServiceImpl implements RoleManagementService {
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
final UserStoreManager userStoreManager = userRealm.getUserStoreManager();
if (!userStoreManager.isExistingRole(roleName)) {
return Response.status(404).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" +
roleName + "'").build()).build();
String msg = "No role exists with the name : " + roleName ;
return Response.status(404).entity(msg).build();
}
final AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();
@ -481,10 +476,23 @@ public class RoleManagementServiceImpl implements RoleManagementService {
return Response.status(Response.Status.OK).entity("Role '" + roleInfo.getRoleName() + "' has " +
"successfully been updated").build();
} catch (UserStoreException e) {
String msg = "Error occurred while updating role '" + roleName + "'";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
String errorCode = "";
String errorMessage = e.getMessage();
if (errorMessage != null && !errorMessage.isEmpty() &&
errorMessage.contains(ErrorMessages.ERROR_CODE_ROLE_ALREADY_EXISTS.getCode())) {
errorCode = e.getMessage().split("-")[0].trim();
}
if (ErrorMessages.ERROR_CODE_ROLE_ALREADY_EXISTS.getCode().equals(errorCode)) {
String role = roleInfo.getRoleName().split("/")[1];
String msg = "Role already exists with name : " + role + ". Try with another role name.";
log.warn(msg);
return Response.status(Response.Status.CONFLICT).entity(msg).build();
}else{
String msg = "Error occurred while updating role '" + roleName + "'";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
} catch (UserAdminException e) {
String msg = "Error occurred while updating permissions of the role '" + roleName + "'";
log.error(msg, e);
@ -559,9 +567,8 @@ public class RoleManagementServiceImpl implements RoleManagementService {
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
final UserStoreManager userStoreManager = userRealm.getUserStoreManager();
if (!userStoreManager.isExistingRole(roleName)) {
return Response.status(404).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" +
roleName + "'").build()).build();
String msg = "No role exists with the name : " + roleName ;
return Response.status(404).entity(msg).build();
}
final AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();

@ -157,10 +157,8 @@ public class UserManagementServiceImpl implements UserManagementService {
" already exists. Therefore, request made to add user was refused.");
}
// returning response with bad request state
return Response.status(Response.Status.CONFLICT).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " +
userInfo.getUsername() + " already exists. Therefore, request made to add user " +
"was refused.").build()).build();
String msg = "User by username: " + userInfo.getUsername() + " already exists. Try with another username." ;
return Response.status(Response.Status.CONFLICT).entity(msg).build();
}
String initialUserPassword;
@ -290,9 +288,8 @@ public class UserManagementServiceImpl implements UserManagementService {
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist.");
}
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(
"User doesn't exist.").build()).build();
String msg = "User by username: " + username + " does not exist.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
BasicUserInfo user = this.getBasicUserInfo(username);
@ -318,9 +315,8 @@ public class UserManagementServiceImpl implements UserManagementService {
log.debug("User by username: " + username +
" doesn't exists. Therefore, request made to update user was refused.");
}
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " +
username + " doesn't exist.").build()).build();
String msg = "User by username: " + username + " does not exist.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
Map<String, String> defaultUserClaims =
@ -396,9 +392,8 @@ public class UserManagementServiceImpl implements UserManagementService {
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist for removal.");
}
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("User '" +
username + "' does not exist for removal.").build()).build();
String msg = "User by username: " + username + " does not exist for removal.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
// Un-enroll all devices for the user
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
@ -430,9 +425,8 @@ public class UserManagementServiceImpl implements UserManagementService {
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist for role retrieval.");
}
return Response.status(Response.Status.NOT_FOUND).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + username +
" does not exist for role retrieval.").build()).build();
String msg = "User by username: " + username + " does not exist for role retrieval.";
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
RoleList result = new RoleList();
@ -867,8 +861,8 @@ public class UserManagementServiceImpl implements UserManagementService {
try {
ifSinceDate = format.parse(ifModifiedSince);
} catch (ParseException e) {
return Response.status(400).entity(new ErrorResponse.ErrorResponseBuilder()
.setMessage("Invalid date string is provided in 'If-Modified-Since' header").build()).build();
String msg = "Invalid date string is provided in [If-Modified-Since] header";
return Response.status(400).entity(msg).build();
}
ifModifiedSinceTimestamp = ifSinceDate.getTime();
isIfModifiedSinceSet = true;
@ -879,8 +873,8 @@ public class UserManagementServiceImpl implements UserManagementService {
try {
sinceDate = format.parse(since);
} catch (ParseException e) {
return Response.status(400).entity(new ErrorResponse.ErrorResponseBuilder()
.setMessage("Invalid date string is provided in 'since' filter").build()).build();
String msg = "Invalid date string is provided in [since] filter";
return Response.status(400).entity(msg).build();
}
sinceTimestamp = sinceDate.getTime();
timestamp = sinceTimestamp / 1000;
@ -1094,8 +1088,7 @@ public class UserManagementServiceImpl implements UserManagementService {
if (!userStoreManager.isExistingUser(username)) {
String message = "User by username: " + username + " does not exist for permission retrieval.";
log.error(message);
return Response.status(Response.Status.NOT_FOUND)
.entity(new ErrorResponse.ErrorResponseBuilder().setMessage(message).build()).build();
return Response.status(Response.Status.NOT_FOUND).entity(message).build();
}
// Get a list of roles which the user assigned to
List<String> roles = getFilteredRoles(userStoreManager, username);

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save