Merge branch 'master' into improvement/fix-task-deletion

improvement/fix-task-deletion
Charitha Goonetilleke 2 years ago
commit 6f54e5aadf

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

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

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

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

@ -3,7 +3,7 @@
<parent> <parent>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version> <version>5.0.22-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </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.22-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> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version> <version>5.0.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>

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

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

@ -256,10 +256,14 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
keyManagerId = keyManagerConfigurationDTO.getUuid(); keyManagerId = keyManagerConfigurationDTO.getUuid();
} }
} }
String applicationAccessTokenExpiryTime = "N/A";
if (!StringUtils.isEmpty(validityTime)) {
applicationAccessTokenExpiryTime = validityTime;
}
String jsonString = "{\"grant_types\":\"refresh_token,access_token," + String jsonString = "{\"grant_types\":\"refresh_token,access_token," +
"urn:ietf:params:oauth:grant-type:saml2-bearer," + "urn:ietf:params:oauth:grant-type:saml2-bearer," +
"password,client_credentials,iwa:ntlm,urn:ietf:params:oauth:grant-type:jwt-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\\\"," + "\\\"user_access_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"refresh_token_expiry_time\\\":\\\"N\\/A\\\"," + "\\\"refresh_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"id_token_expiry_time\\\":\\\"N\\/A\\\"}\"," + "\\\"id_token_expiry_time\\\":\\\"N\\/A\\\"}\"," +

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

@ -40,6 +40,9 @@ public class DCRRequest {
@XmlElement @XmlElement
private boolean isSaasApp; private boolean isSaasApp;
@XmlElement
private int validityPeriod;
public String getApplicationName() { public String getApplicationName() {
return applicationName; return applicationName;
} }
@ -87,4 +90,12 @@ public class DCRRequest {
public void setIsSaasApp(boolean saasApp) { public void setIsSaasApp(boolean saasApp) {
isSaasApp = 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("assertion") String assertion,
@FormParam("admin_access_token") String admin_access_token, @FormParam("admin_access_token") String admin_access_token,
@FormParam("username") String username, @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 { try {
KeyMgtService keyMgtService = new KeyMgtServiceImpl(); KeyMgtService keyMgtService = new KeyMgtServiceImpl();
DCRResponse resp = keyMgtService.dynamicClientRegistration(dcrRequest.getApplicationName(), dcrRequest.getUsername(), 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(); return Response.status(Response.Status.CREATED).entity(gson.toJson(resp)).build();
} catch (KeyMgtException e) { } catch (KeyMgtException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); 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("assertion") String assertion,
@FormParam("admin_access_token") String admin_access_token, @FormParam("admin_access_token") String admin_access_token,
@FormParam("username") String username, @FormParam("username") String username,
@FormParam("password") String password) { @FormParam("password") String password,
@FormParam("validityPeriod") int validityPeriod) {
try { try {
if (basicAuthHeader == null) { if (basicAuthHeader == null) {
String msg = "Invalid credentials. Make sure your API call is invoked with a Basic Authorization header."; 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( TokenResponse resp = keyMgtService.generateAccessToken(
new TokenRequest(encodedClientCredentials.split(":")[0], new TokenRequest(encodedClientCredentials.split(":")[0],
encodedClientCredentials.split(":")[1], refreshToken, scope, 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(); return Response.status(Response.Status.OK).entity(gson.toJson(resp)).build();
} catch (KeyMgtException e) { } catch (KeyMgtException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();

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

@ -29,8 +29,10 @@ public class TokenRequest {
private String username; private String username;
private String password; private String password;
private int validityPeriod;
public TokenRequest(String clientId, String clientSecret, String refreshToken, String scope, String grantType, 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.clientId = clientId;
this.clientSecret = clientSecret; this.clientSecret = clientSecret;
this.refreshToken = refreshToken; this.refreshToken = refreshToken;
@ -40,6 +42,7 @@ public class TokenRequest {
this.admin_access_token = admin_access_token; this.admin_access_token = admin_access_token;
this.username = username; this.username = username;
this.password = password; this.password = password;
this.validityPeriod = validityPeriod;
} }
public String getClientId() { public String getClientId() {
@ -113,4 +116,12 @@ public class TokenRequest {
public void setPassword(String password) { public void setPassword(String password) {
this.password = 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 * @throws KeyMgtException if any error occurs during DCR process
*/ */
DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl, 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 * This method will handle the access token requests

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

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

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

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

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

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

@ -17,7 +17,7 @@
package io.entgra.application.mgt.common.services; package io.entgra.application.mgt.common.services;
import io.entgra.application.mgt.common.ApplicationType; 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.dto.ApplicationDTO;
import io.entgra.application.mgt.common.exception.ResourceManagementException; import io.entgra.application.mgt.common.exception.ResourceManagementException;
import org.apache.cxf.jaxrs.ext.multipart.Attachment; 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.ApplicationStorageManagementException;
import io.entgra.application.mgt.common.exception.RequestValidatingException; import io.entgra.application.mgt.common.exception.RequestValidatingException;
import io.entgra.application.mgt.common.exception.ResourceManagementException; import io.entgra.application.mgt.common.exception.ResourceManagementException;
import org.wso2.carbon.device.mgt.core.common.exception.StorageManagementException;
import java.io.InputStream; import java.io.InputStream;
import java.util.List; import java.util.List;
@ -121,4 +122,14 @@ public interface ApplicationStorageManager {
* @throws ApplicationStorageManagementException throws if an error occurs when accessing the file. * @throws ApplicationStorageManagementException throws if an error occurs when accessing the file.
*/ */
InputStream getFileStream(String deviceType, String tenantDomain) throws ApplicationStorageManagementException; 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; 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.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;

@ -16,7 +16,7 @@
*/ */
package io.entgra.application.mgt.common.wrapper; 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.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;

@ -16,7 +16,7 @@
*/ */
package io.entgra.application.mgt.common.wrapper; 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.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;

@ -16,7 +16,7 @@
*/ */
package io.entgra.application.mgt.common.wrapper; 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.ApiModel;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;

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

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

@ -17,7 +17,7 @@
package io.entgra.application.mgt.core.impl; 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.dao.SPApplicationDAO;
import io.entgra.application.mgt.core.util.ApplicationManagementUtil; import io.entgra.application.mgt.core.util.ApplicationManagementUtil;
import org.apache.commons.codec.digest.DigestUtils; 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.lifecycle.LifecycleStateManager;
import io.entgra.application.mgt.core.util.ConnectionManagerUtil; import io.entgra.application.mgt.core.util.ConnectionManagerUtil;
import io.entgra.application.mgt.core.util.Constants; 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.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
@ -600,16 +600,17 @@ public class ApplicationManagerImpl implements ApplicationManager {
*/ */
private String generateMD5OfApp(ApplicationArtifact applicationArtifact, byte[] content) throws ApplicationManagementException { private String generateMD5OfApp(ApplicationArtifact applicationArtifact, byte[] content) throws ApplicationManagementException {
try { try {
String md5OfApp = StorageManagementUtil.getMD5(new ByteArrayInputStream(content)); ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
String md5OfApp = applicationStorageManager.getMD5(new ByteArrayInputStream(content));
if (md5OfApp == null) { if (md5OfApp == null) {
String msg = "Error occurred while generating md5sum value of " + applicationArtifact.getInstallerName(); String msg = "Error occurred while generating md5sum value of " + applicationArtifact.getInstallerName();
log.error(msg); log.error(msg);
throw new ApplicationManagementException(msg); throw new ApplicationManagementException(msg);
} }
return md5OfApp; return md5OfApp;
} catch( ApplicationStorageManagementException e) { } catch(StorageManagementException e) {
String msg = "Error occurred while generating md5sum value of " + applicationArtifact.getInstallerName(); String msg = "Error occurred while generating md5sum value of " + applicationArtifact.getInstallerName();
log.error(msg); log.error(msg, e);
throw new ApplicationManagementException(msg, e); throw new ApplicationManagementException(msg, e);
} }
} }
@ -689,7 +690,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg); log.error(msg);
throw new ApplicationManagementException(msg); throw new ApplicationManagementException(msg);
} }
String md5OfApp = StorageManagementUtil.getMD5(new ByteArrayInputStream(content)); String md5OfApp = applicationStorageManager.getMD5(new ByteArrayInputStream(content));
if (md5OfApp == null) { if (md5OfApp == null) {
String msg = "Error occurred while md5sum value retrieving process: application UUID " String msg = "Error occurred while md5sum value retrieving process: application UUID "
+ applicationReleaseDTO.getUuid(); + applicationReleaseDTO.getUuid();
@ -708,6 +709,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
applicationStorageManager applicationStorageManager
.uploadReleaseArtifact(applicationReleaseDTO, deviceType, binaryDuplicate, tenantId); .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) { } catch (DBConnectionException e) {
String msg = "Error occurred when getting database connection for verifying app release data."; String msg = "Error occurred when getting database connection for verifying app release data.";
log.error(msg, e); log.error(msg, e);
@ -752,7 +758,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream()); byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream());
try (ByteArrayInputStream binaryClone = new ByteArrayInputStream(content)) { try (ByteArrayInputStream binaryClone = new ByteArrayInputStream(content)) {
String md5OfApp = StorageManagementUtil.getMD5(binaryClone); String md5OfApp = applicationStorageManager.getMD5(binaryClone);
if (md5OfApp == null) { if (md5OfApp == null) {
String msg = "Error occurred while retrieving md5sum value from the binary file for application " 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) { } catch (IOException e) {
String msg = "Error occurred when getting byte array of binary file. Installer name: " + applicationArtifact String msg = "Error occurred when getting byte array of binary file. Installer name: " + applicationArtifact
.getInstallerName(); .getInstallerName();
@ -2162,9 +2173,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
ConnectionManagerUtil.closeDBConnection(); ConnectionManagerUtil.closeDBConnection();
} }
} }
public ApplicationRelease changeLifecycleState(ApplicationReleaseDTO applicationReleaseDTO, LifecycleChanger lifecycleChanger) throws ApplicationManagementException { public ApplicationRelease changeLifecycleState(ApplicationReleaseDTO applicationReleaseDTO, LifecycleChanger lifecycleChanger) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (lifecycleChanger == null || StringUtils.isEmpty(lifecycleChanger.getAction())) { if (lifecycleChanger == null || StringUtils.isEmpty(lifecycleChanger.getAction())) {
@ -2172,7 +2183,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg); log.error(msg);
throw new BadRequestException(msg); throw new BadRequestException(msg);
} }
try{ try{
if (lifecycleStateManager if (lifecycleStateManager
.isValidStateChange(applicationReleaseDTO.getCurrentState(), lifecycleChanger.getAction(), userName, .isValidStateChange(applicationReleaseDTO.getCurrentState(), lifecycleChanger.getAction(), userName,
@ -3254,7 +3265,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
try { try {
byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream()); byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream());
try (ByteArrayInputStream binaryClone = new ByteArrayInputStream(content)) { try (ByteArrayInputStream binaryClone = new ByteArrayInputStream(content)) {
String md5OfApp = StorageManagementUtil.getMD5(binaryClone); String md5OfApp = applicationStorageManager.getMD5(binaryClone);
if (md5OfApp == null) { if (md5OfApp == null) {
String msg = "Error occurred while retrieving md5sum value from the binary file for " String msg = "Error occurred while retrieving md5sum value from the binary file for "
+ "application release UUID " + applicationReleaseDTO.get().getUuid(); + "application release UUID " + applicationReleaseDTO.get().getUuid();
@ -3300,6 +3311,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) { } catch (IOException e) {
String msg = "Error occurred when getting byte array of binary file. Installer name: " String msg = "Error occurred when getting byte array of binary file. Installer name: "
+ applicationArtifact.getInstallerName(); + applicationArtifact.getInstallerName();

@ -19,6 +19,7 @@ package io.entgra.application.mgt.core.impl;
import com.dd.plist.NSDictionary; import com.dd.plist.NSDictionary;
import net.dongliu.apk.parser.bean.ApkMeta; import net.dongliu.apk.parser.bean.ApkMeta;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; 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.exception.ParsingException;
import io.entgra.application.mgt.core.util.ArtifactsParser; import io.entgra.application.mgt.core.util.ArtifactsParser;
import io.entgra.application.mgt.core.util.Constants; 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.io.*;
import java.util.List; 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. * This class contains the default concrete implementation of ApplicationStorage Management.
@ -112,6 +114,11 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
+ applicationReleaseDTO.getUuid(); + applicationReleaseDTO.getUuid();
log.error(msg, e); log.error(msg, e);
throw new ApplicationStorageManagementException(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(); + applicationReleaseDTO.getUuid();
log.error(msg, e); log.error(msg, e);
throw new ResourceManagementException( 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); 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);
}
}
} }

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

@ -18,13 +18,11 @@
package io.entgra.application.mgt.core.util; package io.entgra.application.mgt.core.util;
import io.entgra.application.mgt.common.ApplicationArtifact; 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.FileDataHolder;
import io.entgra.application.mgt.common.dto.ApplicationDTO; 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.ApplicationManagementException;
import io.entgra.application.mgt.common.exception.RequestValidatingException; 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.services.SPApplicationManager;
import io.entgra.application.mgt.common.wrapper.ApplicationWrapper; import io.entgra.application.mgt.common.wrapper.ApplicationWrapper;
import io.entgra.application.mgt.common.wrapper.CustomAppReleaseWrapper; 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.BeforeMethod;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import io.entgra.application.mgt.common.exception.ResourceManagementException; 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.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@ -47,14 +48,14 @@ public class StorageManagementUtilTest {
public void testCreateArtifactDirectory() { public void testCreateArtifactDirectory() {
try { try {
StorageManagementUtil.createArtifactDirectory(TEMP_FOLDER); StorageManagementUtil.createArtifactDirectory(TEMP_FOLDER);
} catch (ResourceManagementException e) { } catch (StorageManagementException e) {
e.printStackTrace(); e.printStackTrace();
Assert.fail("Directory creation failed."); Assert.fail("Directory creation failed.");
} }
} }
@Test @Test
public void testSaveFile() throws IOException, ResourceManagementException { public void testSaveFile() throws IOException, ResourceManagementException, StorageManagementException {
StorageManagementUtil.createArtifactDirectory(TEMP_FOLDER); StorageManagementUtil.createArtifactDirectory(TEMP_FOLDER);
InputStream apk = new FileInputStream(APK_FILE); InputStream apk = new FileInputStream(APK_FILE);
StorageManagementUtil.saveFile(apk, TEMP_FOLDER + APK_FILE_NAME); StorageManagementUtil.saveFile(apk, TEMP_FOLDER + APK_FILE_NAME);
@ -65,7 +66,7 @@ public class StorageManagementUtilTest {
} }
@AfterMethod @AfterMethod
public void deleteFileTest() throws IOException, ResourceManagementException { public void deleteFileTest() throws IOException, StorageManagementException {
File file = new File(TEMP_FOLDER); File file = new File(TEMP_FOLDER);
StorageManagementUtil.delete(file); StorageManagementUtil.delete(file);
if (file.exists()) { 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.internal.DataHolder;
import io.entgra.application.mgt.core.util.ConnectionManagerUtil; import io.entgra.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; 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.common.util.FileUtil;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; 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.dto.DeviceTypeVersion;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
public class ApplicationManagementTest extends BaseTestCase { public class ApplicationManagementTest extends BaseTestCase {

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

@ -17,7 +17,7 @@
*/ */
package io.entgra.application.mgt.publisher.api.services; 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.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam; 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.ApplicationArtifact;
import io.entgra.application.mgt.common.ApplicationList; 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.Filter;
import io.entgra.application.mgt.common.LifecycleChanger; import io.entgra.application.mgt.common.LifecycleChanger;
import io.entgra.application.mgt.common.exception.ResourceManagementException; import io.entgra.application.mgt.common.exception.ResourceManagementException;

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

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

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

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

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

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

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

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

@ -48,6 +48,22 @@ public interface EntgraLogger extends Log {
void warn(Object object, Throwable t, LogContext logContext); 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(); void clearLogContext();
} }

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

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

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

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

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

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

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

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

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

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>5.0.20-SNAPSHOT</version> <version>5.0.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -425,5 +425,35 @@
<artifactId>io.entgra.application.mgt.core</artifactId> <artifactId>io.entgra.application.mgt.core</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </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> </dependencies>
</project> </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 com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import java.util.List;
/** /**
* This hold stats data record * This hold stats data record
*/ */
public class DeviceTypeEvent { public class DeviceTypeEvent {
private String eventName;
private EventAttributeList eventAttributes; private EventAttributeList eventAttributes;
private TransportType transport; private TransportType transport;
private String eventTopicStructure;
@ApiModelProperty(value = "Attributes related to device type event") @ApiModelProperty(value = "Attributes related to device type event")
@JsonProperty("eventAttributes") @JsonProperty("eventAttributes")
public EventAttributeList getEventAttributeList() { public EventAttributeList getEventAttributeList() {
@ -48,5 +52,25 @@ public class DeviceTypeEvent {
public void setTransportType(TransportType transport) { public void setTransportType(TransportType transport) {
this.transport = 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.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.List;
@SwaggerDefinition( @SwaggerDefinition(
info = @Info( info = @Info(
@ -69,64 +70,64 @@ import javax.ws.rs.core.Response;
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public interface DeviceEventManagementService { public interface DeviceEventManagementService {
// @POST @POST
// @Path("/{type}") @Path("/{type}")
// @ApiOperation( @ApiOperation(
// produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
// httpMethod = "POST", httpMethod = "POST",
// value = "Adding the Event Type Definition", value = "Adding the Event Type Definition",
// notes = "Add the event definition for a device.", notes = "Add the event definition for a device.",
// tags = "Device Event Management", tags = "Device Event Management",
// extensions = { extensions = {
// @Extension(properties = { @Extension(properties = {
// @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events") @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events")
// }) })
// } }
// ) )
// @ApiResponses( @ApiResponses(
// value = { value = {
// @ApiResponse( @ApiResponse(
// code = 200, code = 200,
// message = "OK. \n Successfully added the event defintion.", message = "OK. \n Successfully added the event defintion.",
// responseHeaders = { responseHeaders = {
// @ResponseHeader( @ResponseHeader(
// name = "Content-Type", name = "Content-Type",
// description = "The content type of the body"), description = "The content type of the body"),
// @ResponseHeader( @ResponseHeader(
// name = "ETag", name = "ETag",
// description = "Entity Tag of the response resource.\n" + description = "Entity Tag of the response resource.\n" +
// "Used by caches, or in conditional requests."), "Used by caches, or in conditional requests."),
// @ResponseHeader( @ResponseHeader(
// name = "Last-Modified", name = "Last-Modified",
// description = description =
// "Date and time the resource was last modified.\n" + "Date and time the resource was last modified.\n" +
// "Used by caches, or in conditional requests."), "Used by caches, or in conditional requests."),
// } }
// ), ),
// @ApiResponse( @ApiResponse(
// code = 400, code = 400,
// message = message =
// "Bad Request. \n"), "Bad Request. \n"),
// @ApiResponse( @ApiResponse(
// code = 406, code = 406,
// message = "Not Acceptable.\n The requested media type is not supported"), message = "Not Acceptable.\n The requested media type is not supported"),
// @ApiResponse( @ApiResponse(
// code = 500, code = 500,
// message = "Internal Server Error. \n Server error occurred while fetching the " + message = "Internal Server Error. \n Server error occurred while fetching the " +
// "list of supported device types.", "list of supported device types.",
// response = ErrorResponse.class) response = ErrorResponse.class)
// } }
// ) )
// Response deployDeviceTypeEventDefinition( Response deployDeviceTypeEventDefinition(
// @ApiParam(name = "type", value = "The device type, such as android, ios, and windows.") @ApiParam(name = "type", value = "The device type, such as android, ios, and windows.")
// @PathParam("type")String deviceType, @PathParam("type")String deviceType,
// @ApiParam(name = "skipPersist", value = "Is it required to persist the data or not") @ApiParam(name = "skipPersist", value = "Is it required to persist the data or not")
// @QueryParam("skipPersist") boolean skipPersist, @QueryParam("skipPersist") boolean skipPersist,
// @ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants") @ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants")
// @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
// @ApiParam(name = "deviceTypeEvent", value = "Add the data to complete the DeviceTypeEvent object.", @ApiParam(name = "deviceTypeEvents", value = "Add the data to complete the DeviceTypeEvent object.",
// required = true) required = true)
// @Valid DeviceTypeEvent deviceTypeEvent); @Valid List<DeviceTypeEvent> deviceTypeEvent);
@DELETE @DELETE
@Path("/{type}") @Path("/{type}")

@ -188,6 +188,13 @@ import java.util.List;
roles = {"Internal/devicemgt-user"}, roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/devices/owning-device/add"} 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") @Path("/devices")
@ -553,12 +560,12 @@ public interface DeviceManagementService {
required = false, required = false,
defaultValue = "0") defaultValue = "0")
@QueryParam("offset") int offset, @QueryParam("offset") int offset,
@ApiParam( @ApiParam(
name = "limit", name = "limit",
value = "Provide how many device details you require from the starting pagination index/offset.", value = "Provide how many device details you require from the starting pagination index/offset.",
required = false, required = false,
defaultValue = "100") defaultValue = "100")
@QueryParam("limit") int limit @QueryParam("limit") int limit
); );
@GET @GET
@ -802,6 +809,59 @@ public interface DeviceManagementService {
@QueryParam("requireDeviceInfo") @QueryParam("requireDeviceInfo")
boolean 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 @POST
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("/type/any/list") @Path("/type/any/list")
@ -1059,6 +1119,82 @@ public interface DeviceManagementService {
@HeaderParam("If-Modified-Since") @HeaderParam("If-Modified-Since")
String ifModifiedSince); 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 //device rename request would looks like follows
//POST devices/type/virtual_firealarm/id/us06ww93auzp/rename //POST devices/type/virtual_firealarm/id/us06ww93auzp/rename
@POST @POST
@ -1399,15 +1535,15 @@ public interface DeviceManagementService {
@ResponseHeader( @ResponseHeader(
name = "ETag", name = "ETag",
description = "Entity Tag of the response resource.\n" + description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."), "Used by caches, or in conditional requests."),
@ResponseHeader( @ResponseHeader(
name = "Last-Modified", name = "Last-Modified",
description = "Date and time the resource was last modified. \n" + 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( @ApiResponse(
code = 304, code = 304,
message = "Not Modified. \n " + 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( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n Invalid request or validation error.", message = "Bad Request. \n Invalid request or validation error.",
@ -1425,7 +1561,7 @@ public interface DeviceManagementService {
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n " + 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 = ErrorResponse.class)
}) })
Response queryDevicesByProperties( Response queryDevicesByProperties(
@ -1447,7 +1583,7 @@ public interface DeviceManagementService {
name = "device property map", name = "device property map",
value = "properties by which devices need filtered", value = "properties by which devices need filtered",
required = true) required = true)
PropertyMap map); PropertyMap map);
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@ -1873,140 +2009,141 @@ public interface DeviceManagementService {
@Size(max = 45) @Size(max = 45)
String id); String id);
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@Path("/{type}/{id}/getstatushistory") @Path("/{type}/{id}/status-history")
@ApiOperation( @ApiOperation(
produces = MediaType.APPLICATION_JSON, produces = MediaType.APPLICATION_JSON,
httpMethod = "GET", httpMethod = "GET",
value = "Get Device status history", value = "Get Device status history",
notes = "Get a list of status history associated with the device type and id", notes = "Get a list of status history associated with the device type and id",
tags = "Device Management", tags = "Device Management",
extensions = { extensions = {
@Extension(properties = { @Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
}) })
} }
) )
@ApiResponses( @ApiResponses(
value = { value = {
@ApiResponse( @ApiResponse(
code = 200, code = 200,
message = "OK. \n Successfully fetched the status history of matching devices.", message = "OK. \n Successfully fetched the status history of matching devices.",
response = List.class, response = List.class,
responseHeaders = { responseHeaders = {
@ResponseHeader( @ResponseHeader(
name = "Content-Type", name = "Content-Type",
description = "The content type of the body"), description = "The content type of the body"),
@ResponseHeader( @ResponseHeader(
name = "ETag", name = "ETag",
description = "Entity Tag of the response resource.\n" + description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."), "Used by caches, or in conditional requests."),
@ResponseHeader( @ResponseHeader(
name = "Last-Modified", name = "Last-Modified",
description = "Date and time the resource was last modified.\n" + 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( @ApiResponse(
code = 304, code = 304,
message = "Not Modified. Empty body because the client already has the latest version" + message = "Not Modified. Empty body because the client already has the latest version" +
" of the requested resource.\n"), " of the requested resource.\n"),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n Invalid request or validation error.", message = "Bad Request. \n Invalid request or validation error.",
response = ErrorResponse.class), response = ErrorResponse.class),
@ApiResponse( @ApiResponse(
code = 404, code = 404,
message = "Not Found. \n A device with the specified device type and id was not found.", message = "Not Found. \n A device with the specified device type and id was not found.",
response = ErrorResponse.class), response = ErrorResponse.class),
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n " + 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 = ErrorResponse.class)
}) })
Response getDeviceStatusHistory( Response getDeviceStatusHistory(
@ApiParam( @ApiParam(
name = "type", name = "type",
value = "The device type, such as ios, android, or windows.", value = "The device type, such as ios, android, or windows.",
required = true) required = true)
@PathParam("type") @PathParam("type")
@Size(max = 45) @Size(max = 45)
String type, String type,
@ApiParam( @ApiParam(
name = "id", name = "id",
value = "Device ID.", value = "Device ID.",
required = true) required = true)
@PathParam("id") @PathParam("id")
@Size(max = 45) @Size(max = 45)
String id); String id);
@GET
@Produces(MediaType.APPLICATION_JSON) @GET
@Path("/{type}/{id}/getenrolmentstatushistory") @Produces(MediaType.APPLICATION_JSON)
@ApiOperation( @Path("/{type}/{id}/enrolment-status-history")
produces = MediaType.APPLICATION_JSON, @ApiOperation(
httpMethod = "GET", produces = MediaType.APPLICATION_JSON,
value = "Get Device Current Enrolment status history", httpMethod = "GET",
notes = "Get a list of status history associated with the device type and id for the current enrolment", value = "Get Device Current Enrolment status history",
tags = "Device Management", notes = "Get a list of status history associated with the device type and id for the current enrolment",
extensions = { tags = "Device Management",
@Extension(properties = { extensions = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view") @Extension(properties = {
}) @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
} })
) }
@ApiResponses( )
value = { @ApiResponses(
@ApiResponse( value = {
code = 200, @ApiResponse(
message = "OK. \n Successfully fetched the status history of matching devices.", code = 200,
response = List.class, message = "OK. \n Successfully fetched the status history of matching devices.",
responseHeaders = { response = List.class,
@ResponseHeader( responseHeaders = {
name = "Content-Type", @ResponseHeader(
description = "The content type of the body"), name = "Content-Type",
@ResponseHeader( description = "The content type of the body"),
name = "ETag", @ResponseHeader(
description = "Entity Tag of the response resource.\n" + name = "ETag",
"Used by caches, or in conditional requests."), description = "Entity Tag of the response resource.\n" +
@ResponseHeader( "Used by caches, or in conditional requests."),
name = "Last-Modified", @ResponseHeader(
description = "Date and time the resource was last modified.\n" + name = "Last-Modified",
"Used by caches, or in conditional requests."), description = "Date and time the resource was last modified.\n" +
}), "Used by caches, or in conditional requests."),
@ApiResponse( }),
code = 304, @ApiResponse(
message = "Not Modified. Empty body because the client already has the latest version" + code = 304,
" of the requested resource.\n"), message = "Not Modified. Empty body because the client already has the latest version" +
@ApiResponse( " of the requested resource.\n"),
code = 400, @ApiResponse(
message = "Bad Request. \n Invalid request or validation error.", code = 400,
response = ErrorResponse.class), message = "Bad Request. \n Invalid request or validation error.",
@ApiResponse( response = ErrorResponse.class),
code = 404, @ApiResponse(
message = "Not Found. \n A device with the specified device type and id was not found.", code = 404,
response = ErrorResponse.class), message = "Not Found. \n A device with the specified device type and id was not found.",
@ApiResponse( response = ErrorResponse.class),
code = 500, @ApiResponse(
message = "Internal Server Error. \n " + code = 500,
"Server error occurred while retrieving the device details.", message = "Internal Server Error. \n " +
response = ErrorResponse.class) "Server error occurred while retrieving the device details.",
}) response = ErrorResponse.class)
})
Response getCurrentEnrolmentDeviceStatusHistory( Response getCurrentEnrolmentDeviceStatusHistory(
@ApiParam( @ApiParam(
name = "type", name = "type",
value = "The device type, such as ios, android, or windows.", value = "The device type, such as ios, android, or windows.",
required = true) required = true)
@PathParam("type") @PathParam("type")
@Size(max = 45) @Size(max = 45)
String type, String type,
@ApiParam( @ApiParam(
name = "id", name = "id",
value = "Device ID.", value = "Device ID.",
required = true) required = true)
@PathParam("id") @PathParam("id")
@Size(max = 45) @Size(max = 45)
String id); String id);
@PUT @PUT
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
@ -2171,16 +2308,16 @@ public interface DeviceManagementService {
@ResponseHeader( @ResponseHeader(
name = "ETag", name = "ETag",
description = "Entity Tag of the response resource.\n" + description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."), "Used by caches, or in conditional requests."),
@ResponseHeader( @ResponseHeader(
name = "Last-Modified", name = "Last-Modified",
description = "Date and time the resource was last modified.\n" + 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( @ApiResponse(
code = 304, code = 304,
message = "Not Modified. Empty body because the client already has the latest version" + message = "Not Modified. Empty body because the client already has the latest version" +
" of the requested resource.\n"), " of the requested resource.\n"),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n Invalid request or validation error.", message = "Bad Request. \n Invalid request or validation error.",
@ -2192,7 +2329,7 @@ public interface DeviceManagementService {
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n " + 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 = ErrorResponse.class)
}) })
Response getDeviceCountByStatus( Response getDeviceCountByStatus(
@ -2240,16 +2377,16 @@ public interface DeviceManagementService {
@ResponseHeader( @ResponseHeader(
name = "ETag", name = "ETag",
description = "Entity Tag of the response resource.\n" + description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."), "Used by caches, or in conditional requests."),
@ResponseHeader( @ResponseHeader(
name = "Last-Modified", name = "Last-Modified",
description = "Date and time the resource was last modified.\n" + 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( @ApiResponse(
code = 304, code = 304,
message = "Not Modified. Empty body because the client already has the latest version" + message = "Not Modified. Empty body because the client already has the latest version" +
" of the requested resource.\n"), " of the requested resource.\n"),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n Invalid request or validation error.", message = "Bad Request. \n Invalid request or validation error.",
@ -2261,7 +2398,7 @@ public interface DeviceManagementService {
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n " + 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 = ErrorResponse.class)
}) })
Response getDeviceIdentifiersByStatus( Response getDeviceIdentifiersByStatus(
@ -2310,16 +2447,16 @@ public interface DeviceManagementService {
@ResponseHeader( @ResponseHeader(
name = "ETag", name = "ETag",
description = "Entity Tag of the response resource.\n" + description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."), "Used by caches, or in conditional requests."),
@ResponseHeader( @ResponseHeader(
name = "Last-Modified", name = "Last-Modified",
description = "Date and time the resource has been modified the last time.\n" + 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( @ApiResponse(
code = 304, code = 304,
message = "Not Modified. Empty body because the client already has the latest " + message = "Not Modified. Empty body because the client already has the latest " +
"version of the requested resource."), "version of the requested resource."),
@ApiResponse( @ApiResponse(
code = 400, code = 400,
message = "Bad Request. \n Invalid request or validation error.", message = "Bad Request. \n Invalid request or validation error.",
@ -2331,7 +2468,7 @@ public interface DeviceManagementService {
@ApiResponse( @ApiResponse(
code = 500, code = 500,
message = "Internal Server Error. \n " + 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 = ErrorResponse.class)
}) })
Response bulkUpdateDeviceStatus( Response bulkUpdateDeviceStatus(
@ -2642,11 +2779,11 @@ public interface DeviceManagementService {
@ResponseHeader( @ResponseHeader(
name = "ETag", name = "ETag",
description = "Entity Tag of the response resource.\n" + description = "Entity Tag of the response resource.\n" +
"Used by caches, or in conditional requests."), "Used by caches, or in conditional requests."),
@ResponseHeader( @ResponseHeader(
name = "Last-Modified", name = "Last-Modified",
description = "Date and time the resource was last modified.\n" + 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( @ApiResponse(
code = 500, 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.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes; 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.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.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.MetadataList; import org.wso2.carbon.device.mgt.jaxrs.beans.MetadataList;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants; 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();
}

@ -1,11 +1,19 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl; 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.AxisFault;
import org.apache.axis2.client.Stub; import org.apache.axis2.client.Stub;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext; 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.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.Attribute; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.Attribute;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.AttributeType; 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.service.api.DeviceEventManagementService;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; 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.EventPublisherAdminServiceCallbackHandler;
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub; 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.EventReceiverAdminServiceCallbackHandler;
import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub; 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.BasicInputAdapterPropertyDto;
import org.wso2.carbon.event.receiver.stub.types.EventReceiverConfigurationDto; 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.EventStreamAdminServiceStub;
import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto; import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto;
import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto; import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.DELETE; import javax.validation.Valid;
import javax.ws.rs.GET; import javax.ws.rs.*;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; 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. * Deploy Event Stream, Receiver, Publisher and Store Configuration.
*/ */
// @POST @POST
// @Path("/{type}") @Path("/{type}")
// @Override @Override
// public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType, public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType,
// @QueryParam("skipPersist") boolean skipPersist, @QueryParam("skipPersist") boolean skipPersist,
// @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
// @Valid DeviceTypeEvent deviceTypeEvent) { @Valid List<DeviceTypeEvent> deviceTypeEvents) {
// TransportType transportType = deviceTypeEvent.getTransportType();
// EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList();
// String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
// try { int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
// if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 || try {
// deviceType == null || transportType == null || for (DeviceTypeEvent deviceTypeEvent : deviceTypeEvents) {
// !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { TransportType transportType = deviceTypeEvent.getTransportType();
// String errorMessage = "Invalid Payload"; EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList();
// log.error(errorMessage); String eventName = deviceTypeEvent.getEventName();
// return Response.status(Response.Status.BAD_REQUEST).build();
// }
// String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain); if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 ||
// String streamNameWithVersion = streamName + ":" + Constants.DEFAULT_STREAM_VERSION; deviceType == null || transportType == null ||
// publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes); !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
// publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType); String errorMessage = "Invalid Payload";
// if (!skipPersist) { log.error(errorMessage);
// publishEventStore(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes); return Response.status(Response.Status.BAD_REQUEST).build();
// } }
// publishWebsocketPublisherDefinition(streamNameWithVersion, deviceType); // event stream
// try { String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain, eventName);
// PrivilegedCarbonContext.startTenantFlow(); AnalyticsArtifactsDeployer artifactsDeployer = new AnalyticsArtifactsDeployer();
// PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( List<Property> props = new ArrayList<>();
// MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); for (Attribute attribute : eventAttributes.getList()) {
// if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { props.add(new Property(attribute.getName(), attribute.getType().name()));
// publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes); }
// publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType); EventStreamData eventStreamData = new EventStreamData();
// } eventStreamData.setName(streamName);
// } finally { eventStreamData.setVersion(Constants.DEFAULT_STREAM_VERSION);
// PrivilegedCarbonContext.endTenantFlow(); eventStreamData.setMetaData(new MetaData(DEFAULT_DEVICE_ID_ATTRIBUTE, "STRING"));
// } eventStreamData.setPayloadData(props);
// return Response.ok().build(); artifactsDeployer.deployEventStream(eventStreamData, tenantId);
// } catch (AxisFault e) {
// log.error("Failed to create event definitions for tenantDomain:" + tenantDomain, e); // event receiver
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); String receiverName = getReceiverName(deviceType, tenantDomain, transportType, eventName);
// } catch (RemoteException e) { EventReceiverData receiverData = new EventReceiverData();
// log.error("Failed to connect with the remote services:" + tenantDomain, e); receiverData.setName(receiverName);
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); receiverData.setStreamName(streamName);
// } catch (JWTClientException e) { receiverData.setStreamVersion(Constants.DEFAULT_STREAM_VERSION);
// log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e); List<Property> propertyList = new ArrayList<>();
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); if (transportType == TransportType.MQTT) {
// } catch (UserStoreException e) { receiverData.setEventAdapterType(OAUTH_MQTT_ADAPTER_TYPE);
// log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e); propertyList.add(new Property(MQTT_CONTENT_TRANSFORMER_TYPE, MQTT_CONTENT_TRANSFORMER));
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); propertyList.add(new Property(MQTT_CONTENT_VALIDATOR_TYPE, MQTT_CONTENT_VALIDATOR));
// } catch (DeviceManagementException e) { String topic;
// log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e); if (!StringUtils.isEmpty(deviceTypeEvent.getEventTopicStructure())) {
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); if (isSharedWithAllTenants) {
// } catch (EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException e) { topic = deviceTypeEvent.getEventTopicStructure().replace("${deviceId}", "+")
// log.error("Failed to create event store for, tenantDomain: " + tenantDomain + " deviceType" + deviceType, .replace("${deviceType}", deviceType)
// e); .replace("${tenantDomain}", "+");
// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } 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. * Delete device type specific artifacts from DAS.
@ -498,160 +584,174 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
// return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); // return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
// } // }
// } // }
private void publishEventReceivers(String streamName, String version, TransportType transportType
, String requestedTenantDomain, boolean isSharedWithAllTenants, String deviceType,
private void publishEventReceivers(String streamNameWithVersion, TransportType transportType String eventTopicStructure, String receiverName) throws EventReceiverConfigurationException {
, String requestedTenantDomain, boolean isSharedWithAllTenants, String deviceType) EventReceiverService eventReceiverService = DeviceMgtAPIUtils.getEventReceiverService();
throws RemoteException, UserStoreException, JWTClientException {
EventReceiverAdminServiceStub receiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub();
try { try {
TransportType transportTypeToBeRemoved = TransportType.HTTP; // TransportType transportTypeToBeRemoved = TransportType.HTTP;
if (transportType == TransportType.HTTP) { // if (transportType == TransportType.HTTP) {
transportTypeToBeRemoved = TransportType.MQTT; // transportTypeToBeRemoved = TransportType.MQTT;
} // }
String eventRecieverNameTobeRemoved = getReceiverName(deviceType, requestedTenantDomain, transportTypeToBeRemoved); // String eventRecieverNameTobeRemoved = getReceiverName(deviceType, requestedTenantDomain, transportTypeToBeRemoved);
EventReceiverConfigurationDto eventReceiverConfigurationDto = receiverAdminServiceStub EventReceiverConfiguration eventReceiverConfiguration =
.getActiveEventReceiverConfiguration(eventRecieverNameTobeRemoved); eventReceiverService.getActiveEventReceiverConfiguration(receiverName);
if (eventReceiverConfigurationDto != null) { if (eventReceiverConfiguration != null) {
EventReceiverAdminServiceCallbackHandler eventReceiverAdminServiceCallbackHandler = eventReceiverService.undeployActiveEventReceiverConfiguration(receiverName);
new EventReceiverAdminServiceCallbackHandler() {
};
receiverAdminServiceStub.startundeployActiveEventReceiverConfiguration(eventRecieverNameTobeRemoved
, eventReceiverAdminServiceCallbackHandler);
} }
String adapterType = OAUTH_MQTT_ADAPTER_TYPE; InputEventAdapterConfiguration inputEventAdapterConfiguration = new InputEventAdapterConfiguration();
BasicInputAdapterPropertyDto basicInputAdapterPropertyDtos[]; Map<String, String> propertyMap = new HashMap<>();
if (transportType == TransportType.MQTT) { if (transportType == TransportType.MQTT) {
basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[3]; inputEventAdapterConfiguration.setType(OAUTH_MQTT_ADAPTER_TYPE);
String topic; String topic;
if (isSharedWithAllTenants) { if (!StringUtils.isEmpty(eventTopicStructure)) {
topic = "+/" + deviceType + "/+/events"; if (isSharedWithAllTenants) {
topic = eventTopicStructure.replace("${deviceId}", "+")
.replace("${deviceType}", deviceType)
.replace("${tenantDomain}", "+");
} else {
topic = eventTopicStructure.replace("${deviceId}", "+")
.replace("${deviceType}", deviceType)
.replace("${tenantDomain}", requestedTenantDomain);
}
} else { } else {
topic = requestedTenantDomain + "/" + deviceType + "/+/events"; if (isSharedWithAllTenants) {
topic = "+/" + deviceType + "/+/events";
} else {
topic = requestedTenantDomain + "/" + deviceType + "/+/events";
}
} }
basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("topic", topic); propertyMap.put("topic", topic);
basicInputAdapterPropertyDtos[1] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_TRANSFORMER_TYPE propertyMap.put(MQTT_CONTENT_TRANSFORMER_TYPE, MQTT_CONTENT_TRANSFORMER);
, MQTT_CONTENT_TRANSFORMER); propertyMap.put(MQTT_CONTENT_VALIDATOR_TYPE, MQTT_CONTENT_VALIDATOR);
basicInputAdapterPropertyDtos[2] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_VALIDATOR_TYPE
, MQTT_CONTENT_VALIDATOR);
} else { } else {
adapterType = THRIFT_ADAPTER_TYPE; inputEventAdapterConfiguration.setType(THRIFT_ADAPTER_TYPE);
basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[1]; propertyMap.put("events.duplicated.in.cluster", "false");
basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("events.duplicated.in.cluster", "false");
} }
String eventRecieverName = getReceiverName(deviceType, requestedTenantDomain, transportType); inputEventAdapterConfiguration.setProperties(propertyMap);
if (receiverAdminServiceStub.getActiveEventReceiverConfiguration(eventRecieverName) == null) {
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) { if (transportType == TransportType.MQTT) {
receiverAdminServiceStub.deployJsonEventReceiverConfiguration(eventRecieverName, streamNameWithVersion JSONInputMapping jsonInputMapping = new JSONInputMapping();
, adapterType, null, basicInputAdapterPropertyDtos, false); jsonInputMapping.setCustomMappingEnabled(false);
configuration.setInputMapping(jsonInputMapping);
eventReceiverService.deployEventReceiverConfiguration(configuration);
} else { } else {
receiverAdminServiceStub.deployWso2EventReceiverConfiguration(eventRecieverName, streamNameWithVersion WSO2EventInputMapping wso2EventInputMapping = new WSO2EventInputMapping();
, adapterType, null, null, null, basicInputAdapterPropertyDtos, false, null); wso2EventInputMapping.setCustomMappingEnabled(false);
configuration.setInputMapping(wso2EventInputMapping);
eventReceiverService.deployEventReceiverConfiguration(configuration);
} }
} }
} finally { } catch (EventReceiverConfigurationException e) {
cleanup(receiverAdminServiceStub); log.error("Error while publishing event receiver" , e);
throw new EventReceiverConfigurationException(e);
} }
} }
private void publishStreamDefinitons(String streamName, String version, String deviceType private void publishStreamDefinitons(String streamName, String version, EventAttributeList eventAttributes)
, EventAttributeList eventAttributes) throws MalformedStreamDefinitionException, EventStreamConfigurationException {
throws RemoteException, UserStoreException, JWTClientException { EventStreamService eventStreamService = DeviceMgtAPIUtils.getEventStreamService();
EventStreamAdminServiceStub eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub();
try { try {
EventStreamDefinitionDto eventStreamDefinitionDto = new EventStreamDefinitionDto(); StreamDefinition streamDefinition = new StreamDefinition(streamName, version);
eventStreamDefinitionDto.setName(streamName);
eventStreamDefinitionDto.setVersion(version); List<org.wso2.carbon.databridge.commons.Attribute> payloadDataAttributes = new ArrayList<>();
EventStreamAttributeDto eventStreamAttributeDtos[] =
new EventStreamAttributeDto[eventAttributes.getList().size()];
EventStreamAttributeDto metaStreamAttributeDtos[] =
new EventStreamAttributeDto[1];
int i = 0;
for (Attribute attribute : eventAttributes.getList()) { for (Attribute attribute : eventAttributes.getList()) {
EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto(); payloadDataAttributes.add(new org.wso2.carbon.databridge.commons.Attribute(attribute.getName(),
eventStreamAttributeDto.setAttributeName(attribute.getName()); org.wso2.carbon.databridge.commons.AttributeType.valueOf(attribute.getType().name())));
eventStreamAttributeDto.setAttributeType(attribute.getType().toString());
eventStreamAttributeDtos[i] = eventStreamAttributeDto;
i++;
} }
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(); if (eventStreamService.getStreamDefinition(streamDefinition.getStreamId()) != null) {
eventStreamAttributeDto.setAttributeName(DEFAULT_DEVICE_ID_ATTRIBUTE); eventStreamService.removeEventStreamDefinition(streamName, version);
eventStreamAttributeDto.setAttributeType(AttributeType.STRING.toString()); eventStreamService.addEventStreamDefinition(streamDefinition);
metaStreamAttributeDtos[0] = eventStreamAttributeDto;
eventStreamDefinitionDto.setPayloadData(eventStreamAttributeDtos);
eventStreamDefinitionDto.setMetaData(metaStreamAttributeDtos);
String streamId = streamName + ":" + version;
if (eventStreamAdminServiceStub.getStreamDefinitionDto(streamId) != null) {
eventStreamAdminServiceStub.editEventStreamDefinitionAsDto(eventStreamDefinitionDto, streamId);
} else { } 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 { private void publishEventStore(String streamName, String version, String publisherName)
// EventStreamPersistenceAdminServiceStub eventStreamPersistenceAdminServiceStub = throws EventPublisherConfigurationException {
// DeviceMgtAPIUtils.getEventStreamPersistenceAdminServiceStub();
// try { EventPublisherService eventPublisherService = DeviceMgtAPIUtils.getEventPublisherService();
// 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 publishWebsocketPublisherDefinition(String streamNameWithVersion, String deviceType)
throws RemoteException, UserStoreException, JWTClientException {
EventPublisherAdminServiceStub eventPublisherAdminServiceStub = DeviceMgtAPIUtils
.getEventPublisherAdminServiceStub();
try { try {
String eventPublisherName = deviceType.trim().replace(" ", "_") + "_websocket_publisher"; if (eventPublisherService.getActiveEventPublisherConfiguration(publisherName) == null) {
if (eventPublisherAdminServiceStub.getActiveEventPublisherConfiguration(eventPublisherName) == null) { EventPublisherConfiguration configuration = new EventPublisherConfiguration();
eventPublisherAdminServiceStub.deployJsonEventPublisherConfiguration(eventPublisherName configuration.setEventPublisherName(publisherName);
, streamNameWithVersion, DEFAULT_WEBSOCKET_PUBLISHER_ADAPTER_TYPE, null, null configuration.setFromStreamName(streamName);
, null, false); 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) { private BasicInputAdapterPropertyDto getBasicInputAdapterPropertyDto(String key, String value) {
BasicInputAdapterPropertyDto basicInputAdapterPropertyDto = new BasicInputAdapterPropertyDto(); BasicInputAdapterPropertyDto basicInputAdapterPropertyDto = new BasicInputAdapterPropertyDto();
basicInputAdapterPropertyDto.setKey(key); basicInputAdapterPropertyDto.setKey(key);
@ -667,6 +767,13 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
return deviceType.replace(" ", "_").trim() + "-" + tenantDomain + "-" + transportType.toString() + "-receiver"; 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) { private void cleanup(Stub stub) {
if (stub != null) { if (stub != null) {

@ -37,33 +37,26 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl; package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import com.google.gson.Gson; 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.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.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject; 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.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import io.entgra.application.mgt.common.ApplicationInstallResponse; import org.wso2.carbon.device.mgt.common.*;
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.app.mgt.Application; import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; 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.DeviceInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation; 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.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.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.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; 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.search.SearchContext;
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceStatus; 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.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.dao.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; 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.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; 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.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.traccar.common.TraccarHandlerConstants;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; 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.*;
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.service.api.DeviceManagementService; 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.InputValidationException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; 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.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.validation.Valid; import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import javax.ws.rs.DELETE; import javax.ws.rs.*;
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.core.Response; import javax.ws.rs.core.Response;
import java.sql.Timestamp;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.ArrayList;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
@ -816,6 +786,32 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.OK).entity(device).build(); 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 @POST
@Path("/type/any/list") @Path("/type/any/list")
@Override @Override
@ -887,6 +883,107 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
} }
return Response.status(Response.Status.OK).entity(deviceInfo).build(); 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 @GET
@ -1262,7 +1359,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
* @return {@link Response} object * @return {@link Response} object
*/ */
@GET @GET
@Path("/{type}/{id}/getstatushistory") @Path("/{type}/{id}/status-history")
public Response getDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type, public Response getDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id) { @PathParam("id") @Size(max = 45) String id) {
//TODO check authorization for this //TODO check authorization for this
@ -1294,7 +1391,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
* @return {@link Response} object * @return {@link Response} object
*/ */
@GET @GET
@Path("/{type}/{id}/getenrolmentstatushistory") @Path("/{type}/{id}/enrolment-status-history")
public Response getCurrentEnrolmentDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type, public Response getCurrentEnrolmentDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id) { @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 //TODO check authorization for this or current enrolment should be based on for the enrolment associated with the user

@ -18,20 +18,27 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl; 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.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; 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.MetadataKeyAlreadyExistsException;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataKeyNotFoundException; 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.metadata.mgt.Metadata;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException; 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.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.beans.MetadataList;
import org.wso2.carbon.device.mgt.jaxrs.service.api.MetadataService; 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.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; 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 java.util.List;
import javax.ws.rs.Consumes; 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();
}
}
} }

@ -0,0 +1,175 @@
/*
* 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.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.FileResponse;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.NotFoundException;
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.service.api.WhiteLabelService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
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;
import java.io.ByteArrayInputStream;
import java.io.IOException;
/**
* This is the service class for metadata management.
*/
@Path("/whitelabel")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class WhiteLabelServiceImpl implements WhiteLabelService {
private static final Log log = LogFactory.getLog(WhiteLabelServiceImpl.class);
@GET
@Override
@Path("/{tenantDomain}/favicon")
public Response getWhiteLabelFavicon(@PathParam("tenantDomain") String tenantDomain) {
try {
FileResponse fileResponse = DeviceMgtAPIUtils.getWhiteLabelManagementService().getWhiteLabelFavicon(tenantDomain);
return sendFileStream(fileResponse);
} catch (NotFoundException e) {
String msg = "Favicon white label image cannot be found in the system. Uploading the favicon white label image again might help solve the issue.";
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (MetadataManagementException e) {
String msg = "Error occurred while getting favicon";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Override
@Path("/{tenantDomain}/logo")
public Response getWhiteLabelLogo(@PathParam("tenantDomain") String tenantDomain) {
try {
FileResponse fileResponse = DeviceMgtAPIUtils.getWhiteLabelManagementService().getWhiteLabelLogo(tenantDomain);
return sendFileStream(fileResponse);
} catch (NotFoundException e) {
String msg = "Logo white label image cannot be found in the system. Uploading the logo white label image again might help solve the issue.";
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (MetadataManagementException e) {
String msg = "Error occurred while getting logo";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Override
@Path("/{tenantDomain}/icon")
public Response getWhiteLabelLogoIcon(@PathParam("tenantDomain") String tenantDomain) {
try {
FileResponse fileResponse = DeviceMgtAPIUtils.getWhiteLabelManagementService().getWhiteLabelLogoIcon(tenantDomain);
return sendFileStream(fileResponse);
} catch (NotFoundException e) {
String msg = "Icon white label image cannot be found in the system. Uploading the icon white label image again might help solve the issue.";
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (MetadataManagementException e) {
String msg = "Error occurred while getting logo";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@PUT
@Override
public Response updateWhiteLabelTheme(WhiteLabelThemeCreateRequest whiteLabelThemeCreateRequest) {
RequestValidationUtil.validateWhiteLabelTheme(whiteLabelThemeCreateRequest);
try {
WhiteLabelTheme createdWhiteLabelTheme = DeviceMgtAPIUtils.getWhiteLabelManagementService().updateWhiteLabelTheme(whiteLabelThemeCreateRequest);
return Response.status(Response.Status.CREATED).entity(createdWhiteLabelTheme).build();
} catch (MetadataManagementException e) {
String msg = "Error occurred while creating whitelabel for tenant";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@GET
@Override
public Response getWhiteLabelTheme() {
try {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
WhiteLabelTheme whiteLabelTheme = DeviceMgtAPIUtils.getWhiteLabelManagementService().getWhiteLabelTheme(tenantDomain);
return Response.status(Response.Status.CREATED).entity(whiteLabelTheme).build();
} catch (MetadataManagementException e) {
String msg = "Error occurred while deleting whitelabel for tenant";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (NotFoundException e) {
String msg = "Not white label theme configured for this tenant";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving tenant details of whitelabel";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@PUT
@Override
@Path("/reset")
public Response resetWhiteLabel() {
try {
DeviceMgtAPIUtils.getWhiteLabelManagementService().resetToDefaultWhiteLabelTheme();
return Response.status(Response.Status.CREATED).entity("White label theme deleted successfully.").build();
} catch (MetadataManagementException e) {
String msg = "Error occurred while resetting whitelabel for tenant";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* Useful to send file responses
*/
private Response sendFileStream(FileResponse fileResponse) {
try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(fileResponse.getFileContent())) {
Response.ResponseBuilder response = Response
.ok(binaryDuplicate, fileResponse.getMimeType());
response.status(Response.Status.OK);
response.header("Content-Length", fileResponse.getFileContent().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();
}
}
}

@ -18,10 +18,13 @@
*/ */
package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; package org.wso2.carbon.device.mgt.jaxrs.service.impl.util;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.wso2.carbon.device.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager; import org.wso2.carbon.device.mgt.common.FeatureManager;
@ -31,8 +34,11 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; 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.DeviceTypeNotFoundException;
import org.wso2.carbon.device.mgt.common.metadata.mgt.Metadata; import org.wso2.carbon.device.mgt.common.metadata.mgt.Metadata;
import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelImageRequestPayload;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.core.common.util.HttpUtil;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
@ -670,6 +676,122 @@ public class RequestValidationUtil {
} }
} }
/**
* Check if whitelabel theme create request contains valid payload and all required payload
*
* @param whiteLabelThemeCreateRequest {@link WhiteLabelThemeCreateRequest}
*/
public static void validateWhiteLabelTheme(WhiteLabelThemeCreateRequest whiteLabelThemeCreateRequest) {
if (whiteLabelThemeCreateRequest.getFavicon() == null) {
String msg = "Favicon is required to whitelabel";
log.error(msg);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
if (whiteLabelThemeCreateRequest.getLogo() == null) {
String msg = "Logo is required to whitelabel";
log.error(msg);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
if (whiteLabelThemeCreateRequest.getLogoIcon() == null) {
String msg = "Logo Icon is required to whitelabel";
log.error(msg);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
if (whiteLabelThemeCreateRequest.getFooterText() == null) {
String msg = "Footer text is required to whitelabel";
log.error(msg);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
if (whiteLabelThemeCreateRequest.getAppTitle() == null) {
String msg = "App title is required to whitelabel";
log.error(msg);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
try {
validateWhiteLabelImage(whiteLabelThemeCreateRequest.getFavicon());
validateWhiteLabelImage(whiteLabelThemeCreateRequest.getLogo());
validateWhiteLabelImage(whiteLabelThemeCreateRequest.getLogoIcon());
} catch (InputValidationException e) {
String msg = "Payload contains invalid base64 files";
log.error(msg, e);
throw e;
}
}
/**
* Validate if {@link WhiteLabelImageRequestPayload} contains mandatory fields.
*/
private static void validateWhiteLabelImage(WhiteLabelImageRequestPayload whiteLabelImage) {
if (whiteLabelImage.getImageType() == null) {
String msg = "Invalid payload found with the request. White label imageType cannot be null.";
log.error(msg);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
if (whiteLabelImage.getImageType() == WhiteLabelImageRequestPayload.ImageType.BASE64) {
try {
Base64File image = new Gson().fromJson(whiteLabelImage.getImage(), Base64File.class);
validateBase64File(image);
} catch (JsonSyntaxException e) {
String msg = "Invalid image payload found with the request. Image object does not represent a Base64 File. " +
"Hence verify the request payload object.";
log.error(msg, e);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
}
else if (whiteLabelImage.getImageType() == WhiteLabelImageRequestPayload.ImageType.URL) {
try {
String imageUrl = new Gson().fromJson(whiteLabelImage.getImage(), String.class);
if (!HttpUtil.isHttpUrlValid(imageUrl)) {
String msg = "Invalid image url provided for white label image.";
log.error(msg);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
} catch (JsonSyntaxException e) {
String msg = "Invalid payload found with the request. Hence verify the request payload object.";
log.error(msg, e);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
} else {
String msg = "Invalid payload found with the request. Unknown white label imageType " + whiteLabelImage.getImageType();
log.error(msg);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
}
/**
* Validate if {@link Base64File} contains mandatory fields.
*/
private static void validateBase64File(Base64File base64File) {
if (base64File.getBase64String() == null || base64File.getName() == null) {
String msg = "Base64File doesn't contain required properties. name and base64String properties " +
"are required fields for base64file type";
log.error(msg);
throw new InputValidationException(
new ErrorResponse.ErrorResponseBuilder()
.setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
}
}
/** /**
* Validate if the metaData and metaKey values are non empty & in proper format. * Validate if the metaData and metaKey values are non empty & in proper format.
* *

@ -50,15 +50,12 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI; import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub; import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils; import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
@ -74,6 +71,7 @@ import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.metadata.mgt.MetadataManagementService; import org.wso2.carbon.device.mgt.common.metadata.mgt.MetadataManagementService;
import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelManagementService;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.report.mgt.ReportManagementService; import org.wso2.carbon.device.mgt.common.report.mgt.ReportManagementService;
@ -95,8 +93,11 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventAttributeList;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub; import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub;
import org.wso2.carbon.event.publisher.core.EventPublisherService;
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub; import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub;
import org.wso2.carbon.event.receiver.core.EventReceiverService;
import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub; import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub;
import org.wso2.carbon.event.stream.core.EventStreamService;
import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub; import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub;
import org.wso2.carbon.identity.claim.metadata.mgt.dto.ClaimPropertyDTO; import org.wso2.carbon.identity.claim.metadata.mgt.dto.ClaimPropertyDTO;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient; import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
@ -111,11 +112,7 @@ import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService; import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService; import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.api.AuthorizationManager; import org.wso2.carbon.user.api.*;
import org.wso2.carbon.user.api.RealmConfiguration;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager; import org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.mgt.common.UIPermissionNode; import org.wso2.carbon.user.mgt.common.UIPermissionNode;
@ -128,11 +125,7 @@ import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.security.KeyManagementException; import java.security.*;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedList; import java.util.LinkedList;
@ -172,8 +165,9 @@ public class DeviceMgtAPIUtils {
private static KeyStore trustStore; private static KeyStore trustStore;
private static char[] keyStorePassword; private static char[] keyStorePassword;
// private static IntegrationClientService integrationClientService; // private static IntegrationClientService integrationClientService;
private static MetadataManagementService metadataManagementService; private static MetadataManagementService metadataManagementService;
private static WhiteLabelManagementService whiteLabelManagementService;
private static OTPManagementService otpManagementService; private static OTPManagementService otpManagementService;
private static volatile SubscriptionManager subscriptionManager; private static volatile SubscriptionManager subscriptionManager;
@ -511,6 +505,28 @@ public class DeviceMgtAPIUtils {
return notificationManagementService; return notificationManagementService;
} }
/**
* Initializing and accessing method for WhiteLabelManagementService.
*
* @return WhiteLabelManagementService instance
* @throws IllegalStateException if whiteLabelManagementService cannot be initialized
*/
public static WhiteLabelManagementService getWhiteLabelManagementService() {
if (whiteLabelManagementService == null) {
synchronized (DeviceMgtAPIUtils.class) {
if (whiteLabelManagementService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
whiteLabelManagementService = (WhiteLabelManagementService) ctx.getOSGiService(
WhiteLabelManagementService.class, null);
if (whiteLabelManagementService == null) {
throw new IllegalStateException("Whitelabel Management service not initialized.");
}
}
}
}
return whiteLabelManagementService;
}
/** /**
* Initializing and accessing method for MetadataManagementService. * Initializing and accessing method for MetadataManagementService.
* *
@ -581,6 +597,36 @@ public class DeviceMgtAPIUtils {
return geoService; return geoService;
} }
public static EventStreamService getEventStreamService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
EventStreamService
eventStreamService = (EventStreamService) ctx.getOSGiService(EventStreamService.class, null);
if (eventStreamService == null) {
throw new IllegalStateException("Event Stream Service has not been initialized.");
}
return eventStreamService;
}
public static EventReceiverService getEventReceiverService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
EventReceiverService
eventReceiverService = (EventReceiverService) ctx.getOSGiService(EventReceiverService.class, null);
if (eventReceiverService == null) {
throw new IllegalStateException("Event Receiver Service has not been initialized.");
}
return eventReceiverService;
}
public static EventPublisherService getEventPublisherService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
EventPublisherService
eventPublisherService = (EventPublisherService) ctx.getOSGiService(EventPublisherService.class, null);
if (eventPublisherService == null) {
throw new IllegalStateException("Event Receiver Service has not been initialized.");
}
return eventPublisherService;
}
public static AnalyticsDataAPI getAnalyticsDataAPI() { public static AnalyticsDataAPI getAnalyticsDataAPI() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AnalyticsDataAPI analyticsDataAPI = AnalyticsDataAPI analyticsDataAPI =
@ -642,10 +688,13 @@ public class DeviceMgtAPIUtils {
// return eventsPublisherService; // return eventsPublisherService;
// } // }
public static String getStreamDefinition(String deviceType, String tenantDomain, String eventName) {
return getStreamDefinition(deviceType, tenantDomain) + "." + eventName;
}
public static String getStreamDefinition(String deviceType, String tenantDomain) { public static String getStreamDefinition(String deviceType, String tenantDomain) {
return STREAM_DEFINITION_PREFIX + tenantDomain + "." + deviceType.replace(" ", "."); return STREAM_DEFINITION_PREFIX + tenantDomain + "." + deviceType.replace(" ", ".");
} }
public static EventStreamAdminServiceStub getEventStreamAdminServiceStub() public static EventStreamAdminServiceStub getEventStreamAdminServiceStub()
throws AxisFault, UserStoreException, JWTClientException { throws AxisFault, UserStoreException, JWTClientException {
EventStreamAdminServiceStub eventStreamAdminServiceStub = new EventStreamAdminServiceStub( EventStreamAdminServiceStub eventStreamAdminServiceStub = new EventStreamAdminServiceStub(

@ -49,6 +49,7 @@
<ref bean="swaggerResource"/> <ref bean="swaggerResource"/>
<ref bean="analyticsArtifactsManagementService"/> <ref bean="analyticsArtifactsManagementService"/>
<ref bean="metadataService"/> <ref bean="metadataService"/>
<ref bean="whitelabelService"/>
</jaxrs:serviceBeans> </jaxrs:serviceBeans>
<jaxrs:providers> <jaxrs:providers>
<ref bean="jsonProvider"/> <ref bean="jsonProvider"/>
@ -99,6 +100,7 @@
<bean id="jsonProvider" class="org.wso2.carbon.device.mgt.jaxrs.common.GsonMessageBodyHandler"/> <bean id="jsonProvider" class="org.wso2.carbon.device.mgt.jaxrs.common.GsonMessageBodyHandler"/>
<bean id="analyticsArtifactsManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.AnalyticsArtifactsManagementServiceImpl"/> <bean id="analyticsArtifactsManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.AnalyticsArtifactsManagementServiceImpl"/>
<bean id="metadataService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.MetadataServiceImpl"/> <bean id="metadataService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.MetadataServiceImpl"/>
<bean id="whitelabelService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.WhiteLabelServiceImpl"/>
<!--<bean id="errorHandler" class="org.wso2.carbon.device.mgt.jaxrs.common.ErrorHandler"/>--> <!--<bean id="errorHandler" class="org.wso2.carbon.device.mgt.jaxrs.common.ErrorHandler"/>-->
<cxf:bus> <cxf:bus>

@ -48,7 +48,10 @@
<context-param> <context-param>
<param-name>nonSecuredEndPoints</param-name> <param-name>nonSecuredEndPoints</param-name>
<param-value> <param-value>
/api/device-mgt/v1.0/users/validate /api/device-mgt/v1.0/users/validate,
/api/device-mgt/v1.0/whitelabel/.*/favicon,
/api/device-mgt/v1.0/whitelabel/.*/logo,
/api/device-mgt/v1.0/whitelabel/.*/icon,
</param-value> </param-value>
</context-param> </context-param>

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

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2023, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except * Version 2.0 (the "License"); you may not use this file except
@ -16,7 +16,7 @@
* under the License. * under the License.
*/ */
package io.entgra.application.mgt.common; package org.wso2.carbon.device.mgt.common;
public class Base64File { public class Base64File {

@ -0,0 +1,74 @@
/*
* 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.common;
public class FileResponse {
private static final String DEFAULT_MIME_TYPE = "application/octet-stream";
private byte[] fileContent;
private String mimeType;
private String name;
public byte[] getFileContent() {
return fileContent;
}
public void setFileContent(byte[] fileContent) {
this.fileContent = fileContent;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public enum ImageExtension {
SVG() {
@Override
public String mimeType() {
return "image/svg+xml";
}
},
PNG,
JPG,
JPEG,
GIF;
public String mimeType() {
return DEFAULT_MIME_TYPE;
}
public static String mimeTypeOf(String extension) {
if (extension.isEmpty()) {
return DEFAULT_MIME_TYPE;
}
ImageExtension imageExtension = ImageExtension.valueOf(extension.toUpperCase());
return imageExtension.mimeType();
}
@Override
public String toString() {
return this.name().toLowerCase();
}
}
}

@ -0,0 +1,34 @@
/*
* Copyright (c) 2023, Entgra (pvt) Ltd. (http://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.common.exceptions;
/**
* This exception will be thrown when the requested application or platform not found.
*/
public class NotFoundException extends Exception {
public NotFoundException(String message, Throwable throwable) {
super(message, throwable);
}
public NotFoundException(String message) {
super(message);
}
}

@ -23,7 +23,6 @@ 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.MetadataKeyAlreadyExistsException;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataKeyNotFoundException; import org.wso2.carbon.device.mgt.common.exceptions.MetadataKeyNotFoundException;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException; import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException;
import java.util.List; import java.util.List;
/** /**

@ -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 org.wso2.carbon.device.mgt.common.metadata.mgt;
public class WhiteLabelArtifactPath {
private String faviconPath;
private String logoPath;
private String logoIconPath;
public WhiteLabelArtifactPath() {
}
public WhiteLabelArtifactPath(String faviconPath, String logoPath, String logoIconPath) {
this.faviconPath = faviconPath;
this.logoPath = logoPath;
this.logoIconPath = logoIconPath;
}
public String getFaviconPath() {
return faviconPath;
}
public void setFaviconPath(String faviconPath) {
this.faviconPath = faviconPath;
}
public String getLogoPath() {
return logoPath;
}
public void setLogoPath(String logoPath) {
this.logoPath = logoPath;
}
public String getLogoIconPath() {
return logoIconPath;
}
public void setLogoIconPath(String logoIconPath) {
this.logoIconPath = logoIconPath;
}
}

@ -0,0 +1,57 @@
/*
* Copyright (c) 2023, Entgra (pvt) Ltd. (http://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.common.metadata.mgt;
public class WhiteLabelImage {
private ImageLocationType imageLocationType;
private String imageLocation;
public ImageLocationType getImageLocationType() {
return imageLocationType;
}
public void setImageLocationType(ImageLocationType imageLocationType) {
this.imageLocationType = imageLocationType;
}
public String getImageLocation() {
return imageLocation;
}
public void setImageLocation(String imageLocation) {
this.imageLocation = imageLocation;
}
public enum ImageName {
FAVICON,
LOGO,
LOGO_ICON;
@Override
public String toString() {
return name().toLowerCase();
}
}
public enum ImageLocationType {
URL,
CUSTOM_FILE,
DEFAULT_FILE
}
}

@ -0,0 +1,71 @@
/*
* Copyright (c) 2023, Entgra (pvt) Ltd. (http://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.common.metadata.mgt;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import org.wso2.carbon.device.mgt.common.Base64File;
public class WhiteLabelImageRequestPayload {
private ImageType imageType;
private JsonElement image;
public ImageType getImageType() {
return imageType;
}
public void setImageType(ImageType imageType) {
this.imageType = imageType;
}
public JsonElement getImage() {
return image;
}
public Base64File getImageAsBase64File() {
if (imageType != ImageType.BASE64) {
throw new IllegalStateException("Cannot convert image with Image type of " + imageType + " to base64.");
}
return new Gson().fromJson(image, Base64File.class);
}
public String getImageAsUrl() {
if (imageType != ImageType.URL) {
throw new IllegalStateException("Cannot convert image with Image type of " + imageType + " to image url string.");
}
return new Gson().fromJson(image, String.class);
}
public void setImage(JsonElement image) {
this.image = image;
}
public enum ImageType {
URL,
BASE64;
public WhiteLabelImage.ImageLocationType getDTOImageLocationType() {
if (this == URL) {
return WhiteLabelImage.ImageLocationType.URL;
}
return WhiteLabelImage.ImageLocationType.CUSTOM_FILE;
}
}
}

@ -0,0 +1,83 @@
/*
* 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.common.metadata.mgt;
import org.wso2.carbon.device.mgt.common.FileResponse;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.NotFoundException;
/**
* Defines the contract of WhiteLabelManagementService.
*/
public interface WhiteLabelManagementService {
/**
* Use to get byte content of favicon whitelabel image
* @return byte content of favicon
* @throws MetadataManagementException if error occurred while retrieving favicon
* @throws NotFoundException if favicon is not found
*/
FileResponse getWhiteLabelFavicon(String tenantDomain) throws
MetadataManagementException, NotFoundException;
/**
* Use to get byte content of logo whitelabel image
* @return byte content of logo
* @throws MetadataManagementException if error occurred while retrieving logo
* @throws NotFoundException if logo is not found
*/
FileResponse getWhiteLabelLogo(String tenantDomain) throws
MetadataManagementException, NotFoundException;
/**
* Use to get byte content of logo icon whitelabel image
* @return byte content of logo icon
* @throws MetadataManagementException if error occurred while retrieving logo icon
* @throws NotFoundException if logo icon is not found
*/
FileResponse getWhiteLabelLogoIcon(String tenantDomain) throws
MetadataManagementException, NotFoundException;
/**
* This method is useful to create & persist default white label theme for provided tenant if
* it doesn't exist already
* @throws MetadataManagementException if error while adding default white label theme
*/
void addDefaultWhiteLabelThemeIfNotExist(int tenantId) throws MetadataManagementException;
/**
* This method is useful to reset existing white label to default whitelabel
* @throws MetadataManagementException if error while resetting default white label theme
*/
void resetToDefaultWhiteLabelTheme() throws MetadataManagementException;
/**
* This method is useful to update existing white label theme
* @throws MetadataManagementException if error while updating existing white label theme
*/
WhiteLabelTheme updateWhiteLabelTheme(WhiteLabelThemeCreateRequest createWhiteLabelTheme)
throws MetadataManagementException;
/**
* This method is useful to get existing white label theme
* @throws MetadataManagementException if error while getting existing white label theme
*/
WhiteLabelTheme getWhiteLabelTheme(String tenantDomain) throws MetadataManagementException, NotFoundException, DeviceManagementException;
}

@ -0,0 +1,67 @@
/*
* 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.common.metadata.mgt;
public class WhiteLabelTheme {
private WhiteLabelImage faviconImage;
private WhiteLabelImage logoImage;
private WhiteLabelImage logoIconImage;
private String footerText;
private String appTitle;
public String getFooterText() {
return footerText;
}
public void setFooterText(String footerText) {
this.footerText = footerText;
}
public WhiteLabelImage getFaviconImage() {
return faviconImage;
}
public void setFaviconImage(WhiteLabelImage faviconImage) {
this.faviconImage = faviconImage;
}
public WhiteLabelImage getLogoImage() {
return logoImage;
}
public void setLogoImage(WhiteLabelImage logoImage) {
this.logoImage = logoImage;
}
public String getAppTitle() {
return appTitle;
}
public void setAppTitle(String appTitle) {
this.appTitle = appTitle;
}
public WhiteLabelImage getLogoIconImage() {
return logoIconImage;
}
public void setLogoIconImage(WhiteLabelImage logoIconImage) {
this.logoIconImage = logoIconImage;
}
}

@ -0,0 +1,67 @@
/*
* 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.common.metadata.mgt;
public class WhiteLabelThemeCreateRequest {
private WhiteLabelImageRequestPayload favicon;
private WhiteLabelImageRequestPayload logo;
private WhiteLabelImageRequestPayload logoIcon;
private String footerText;
private String appTitle;
public WhiteLabelImageRequestPayload getFavicon() {
return favicon;
}
public void setFavicon(WhiteLabelImageRequestPayload favicon) {
this.favicon = favicon;
}
public WhiteLabelImageRequestPayload getLogo() {
return logo;
}
public void setLogo(WhiteLabelImageRequestPayload logo) {
this.logo = logo;
}
public String getFooterText() {
return footerText;
}
public void setFooterText(String footerText) {
this.footerText = footerText;
}
public String getAppTitle() {
return appTitle;
}
public void setAppTitle(String appTitle) {
this.appTitle = appTitle;
}
public WhiteLabelImageRequestPayload getLogoIcon() {
return logoIcon;
}
public void setLogoIcon(WhiteLabelImageRequestPayload logoIcon) {
this.logoIcon = logoIcon;
}
}

@ -5,6 +5,7 @@ import org.wso2.carbon.device.mgt.common.InitialOperationConfig;
import org.wso2.carbon.device.mgt.common.license.mgt.License; import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import java.util.ArrayList;
import java.util.List; import java.util.List;
public class DeviceTypeMetaDefinition { public class DeviceTypeMetaDefinition {
@ -19,6 +20,10 @@ public class DeviceTypeMetaDefinition {
private String description; private String description;
private boolean isSharedWithAllTenants; private boolean isSharedWithAllTenants;
private List<String> mqttEventTopicStructures;
private boolean longLivedToken = false;
public String getDescription() { public String getDescription() {
return description; return description;
} }
@ -83,4 +88,20 @@ public class DeviceTypeMetaDefinition {
public void setSharedWithAllTenants(boolean sharedWithAllTenants) { public void setSharedWithAllTenants(boolean sharedWithAllTenants) {
isSharedWithAllTenants = sharedWithAllTenants; isSharedWithAllTenants = sharedWithAllTenants;
} }
public List<String> getMqttEventTopicStructures() {
return mqttEventTopicStructures;
}
public void setMqttEventTopicStructures(List<String> mqttEventTopicStructures) {
this.mqttEventTopicStructures = mqttEventTopicStructures;
}
public boolean isLongLivedToken() {
return longLivedToken;
}
public void setLongLivedToken(boolean longLivedToken) {
this.longLivedToken = longLivedToken;
}
} }

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<version>5.0.20-SNAPSHOT</version> <version>5.0.22-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -113,7 +113,9 @@
org.wso2.carbon.event.processor.stub, org.wso2.carbon.event.processor.stub,
org.wso2.carbon.identity.jwt.client.extension.service, org.wso2.carbon.identity.jwt.client.extension.service,
org.apache.commons.codec.binary, org.apache.commons.codec.binary,
io.entgra.server.bootup.heartbeat.beacon io.entgra.server.bootup.heartbeat.beacon,
io.entgra.device.mgt.extensions.logger.*,
io.entgra.notification.logger.*
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
!org.wso2.carbon.device.mgt.core.internal, !org.wso2.carbon.device.mgt.core.internal,
@ -352,6 +354,10 @@
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.task.mgt.common</artifactId> <artifactId>io.entgra.task.mgt.common</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>io.entgra.notification.logger</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

@ -136,6 +136,7 @@ public final class DeviceManagementConstants {
public static final String POLICY_VIOLATE_TEMPLATE = "policy-violating-notifier"; public static final String POLICY_VIOLATE_TEMPLATE = "policy-violating-notifier";
public static final String USER_WELCOME_TEMPLATE = "user-welcome"; public static final String USER_WELCOME_TEMPLATE = "user-welcome";
public static final String DEFAULT_ENROLLMENT_TEMPLATE = "default-enrollment-invitation"; public static final String DEFAULT_ENROLLMENT_TEMPLATE = "default-enrollment-invitation";
public static final String ENROLLMENT_GUIDE_TEMPLATE = "enrollment-guide";
} }
public static final class OperationAttributes { public static final class OperationAttributes {

@ -0,0 +1,32 @@
/* 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.core.common.exception;
/**
* Represents the exception thrown during storing and retrieving the artifacts.
*/
public class StorageManagementException extends Exception {
public StorageManagementException(String message, Throwable ex) {
super(message, ex);
}
public StorageManagementException(String message) {
super(message);
}
}

@ -19,6 +19,8 @@
package org.wso2.carbon.device.mgt.core.common.util; package org.wso2.carbon.device.mgt.core.common.util;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.wso2.carbon.device.mgt.common.Base64File;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -54,7 +56,7 @@ public class FileUtil {
} }
/** /**
* Useful to convert input stream to base64 string * Useful to convert file to base64 string
* *
* @param file stream to be converted * @param file stream to be converted
* @return base64 string of the provided input stream * @return base64 string of the provided input stream
@ -64,6 +66,17 @@ public class FileUtil {
return Base64.getEncoder().encodeToString(fileContent); return Base64.getEncoder().encodeToString(fileContent);
} }
/**
* Useful to convert {@link File} to {@link Base64File}
*
* @param file to be converted
* @return {@link Base64File} of the provided input stream
*/
public static Base64File fileToBase64File(File file) throws IOException {
String base64String = fileToBase64String(file);
return new Base64File(file.getName(), base64String);
}
/** /**
* This generates file name with a suffix depending on the duplicate name count, useful when saving * This generates file name with a suffix depending on the duplicate name count, useful when saving
* files with the same name * files with the same name
@ -75,7 +88,7 @@ public class FileUtil {
String suffix = generateDuplicateFileNameSuffix(fileNameCount); String suffix = generateDuplicateFileNameSuffix(fileNameCount);
String fileNameWithoutExtension = extractFileNameWithoutExtension(fileName); String fileNameWithoutExtension = extractFileNameWithoutExtension(fileName);
String fileNameWithSuffix = fileNameWithoutExtension + suffix; String fileNameWithSuffix = fileNameWithoutExtension + suffix;
fileNameWithSuffix = fileNameWithSuffix + '.' + extractFileExtension(fileName); fileNameWithSuffix = fileNameWithSuffix + '.' + extractFileExtensionFileName(fileName);
return fileNameWithSuffix; return fileNameWithSuffix;
} }
@ -98,13 +111,27 @@ public class FileUtil {
return suffix; return suffix;
} }
/**
* Use to extract file extension from file path
*
* @param filePath path of the file
* @return extension of the file
*/
public static String extractFileExtensionFromFilePath(String filePath) {
File file = new File(filePath);
return extractFileExtensionFileName(file.getName());
}
/** /**
* Use to extract file extension from file name * Use to extract file extension from file name
* *
* @param fileName name of the file * @param fileName name of the file
* @return extension of the file * @return extension of the file
*/ */
private static String extractFileExtension(String fileName) { public static String extractFileExtensionFileName(String fileName) {
if (!fileName.contains(".")) {
return "";
}
return fileName.substring(fileName.lastIndexOf('.') + 1); return fileName.substring(fileName.lastIndexOf('.') + 1);
} }

@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.core.common.util;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.routines.UrlValidator;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.entity.ContentType; import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
@ -234,4 +235,16 @@ public class HttpUtil {
ContentType contentType = ContentType.getOrDefault(response.getEntity()); ContentType contentType = ContentType.getOrDefault(response.getEntity());
return contentType.getMimeType(); return contentType.getMimeType();
} }
/**
* Validate http url (For example make sure it uses http/https protocol)
*
* @param url url to be checked if valid
* @return if provided http url is valid
*/
public static boolean isHttpUrlValid(String url) {
String[] schemes = {"http","https"};
UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);
return urlValidator.isValid(url);
}
} }

@ -16,16 +16,12 @@
* under the License. * under the License.
*/ */
package io.entgra.application.mgt.core.util; package org.wso2.carbon.device.mgt.core.common.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import io.entgra.application.mgt.common.ImageArtifact; import org.wso2.carbon.device.mgt.common.Base64File;
import io.entgra.application.mgt.common.exception.ApplicationStorageManagementException; import org.wso2.carbon.device.mgt.core.common.exception.StorageManagementException;
import io.entgra.application.mgt.common.exception.ResourceManagementException;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@ -47,14 +43,13 @@ public class StorageManagementUtil {
* This method is responsible for creating artifact parent directories in the given path. * This method is responsible for creating artifact parent directories in the given path.
* *
* @param artifactDirectoryPath Path for the artifact directory. * @param artifactDirectoryPath Path for the artifact directory.
* @throws ResourceManagementException Resource Management Exception.
*/ */
public static void createArtifactDirectory(String artifactDirectoryPath) throws ResourceManagementException { public static void createArtifactDirectory(String artifactDirectoryPath) throws StorageManagementException {
File artifactDirectory = new File(artifactDirectoryPath); File artifactDirectory = new File(artifactDirectoryPath);
if (!artifactDirectory.exists() && !artifactDirectory.mkdirs()) { if (!artifactDirectory.exists() && !artifactDirectory.mkdirs()) {
throw new ResourceManagementException( throw new StorageManagementException(
"Cannot create directories in the path to save the application related artifacts"); "Cannot create directories in the path: " + artifactDirectoryPath);
} }
} }
@ -103,20 +98,13 @@ public class StorageManagementUtil {
} }
/** /**
* To create {@link ImageArtifact}. * To save a bas64 string of a file in a given location.
* *
* @param imageFile Image File. * @param base64File {@link Base64File} of the file.
* @param imageArtifactPath Path of the image artifact file.
* @return Image Artifact.
* @throws IOException IO Exception.
*/ */
public static ImageArtifact createImageArtifact(File imageFile, String imageArtifactPath) throws IOException { public static void saveFile(Base64File base64File, String path) throws IOException {
ImageArtifact imageArtifact = new ImageArtifact(); InputStream inputStream = FileUtil.base64ToInputStream(base64File.getBase64String());
imageArtifact.setName(imageFile.getName()); saveFile(inputStream, path);
imageArtifact.setType(Files.probeContentType(imageFile.toPath()));
byte[] imageBytes = IOUtils.toByteArray(new FileInputStream(imageArtifactPath));
imageArtifact.setEncodedImage(Base64.encodeBase64URLSafeString(imageBytes));
return imageArtifact;
} }
/*** /***
@ -138,16 +126,4 @@ public class StorageManagementUtil {
throw new IOException(msg, e); throw new IOException(msg, e);
} }
} }
public static String getMD5(InputStream binaryFile) throws ApplicationStorageManagementException {
String md5;
try {
md5 = DigestUtils.md5Hex(binaryFile);
} catch (IOException e) {
String msg = "IO Exception occurred while trying to get the md5sum value of application";
log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e);
}
return md5;
}
} }

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

Loading…
Cancel
Save