merging upstream cloud-3.1.0

revert-dabc3590
kamidu 8 years ago
commit ee24a8baea

@ -118,7 +118,8 @@ public class SenseClientAsyncExecutor extends AsyncTask<String, Void, Map<String
new BasicAuthRequestInterceptor(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret())) new BasicAuthRequestInterceptor(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret()))
.contract(new JAXRSContract()).encoder(new JacksonEncoder()).decoder(new JacksonDecoder()) .contract(new JAXRSContract()).encoder(new JacksonEncoder()).decoder(new JacksonDecoder())
.target(TokenIssuerService.class, endpoint); .target(TokenIssuerService.class, endpoint);
accessTokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password, "device_" + deviceId, SCOPE); accessTokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password, "device_"
+ deviceId + " " + SCOPE);
//DeviceRegister //DeviceRegister
AndroidSenseManagerService androidSenseManagerService = Feign.builder().client(disableHostnameVerification) AndroidSenseManagerService androidSenseManagerService = Feign.builder().client(disableHostnameVerification)

@ -29,7 +29,7 @@ public interface TokenIssuerService {
@POST @POST
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
AccessTokenInfo getToken(@QueryParam("grant_type") String grant, @QueryParam("username") String username, AccessTokenInfo getToken(@QueryParam("grant_type") String grant, @QueryParam("username") String username,
@QueryParam("password") String password, @QueryParam("deviceId") String deviceId, @QueryParam("scope") String scope); @QueryParam("password") String password, @QueryParam("scope") String scope);
@POST @POST
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)

@ -182,12 +182,11 @@ public class ArduinoServiceImpl implements ArduinoService {
String username = APIUtil.getAuthenticatedUser() + "@" + PrivilegedCarbonContext String username = APIUtil.getAuthenticatedUser() + "@" + PrivilegedCarbonContext
.getThreadLocalCarbonContext().getTenantDomain(); .getThreadLocalCarbonContext().getTenantDomain();
ZipArchive zipFile = createDownloadFile(username, deviceName); ZipArchive zipFile = createDownloadFile(username, deviceName);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); Response.ResponseBuilder response = Response.ok(zipFile.getZipFileContent());
response.status(Response.Status.OK); response.status(Response.Status.OK);
response.type("application/zip"); response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
Response resp = response.build(); Response resp = response.build();
zipFile.getZipFile().delete();
return resp; return resp;
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request return Response.status(400).entity(ex.getMessage()).build();//bad request
@ -200,9 +199,6 @@ public class ArduinoServiceImpl implements ArduinoService {
} catch (APIManagerException ex) { } catch (APIManagerException ex) {
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build(); return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) { } catch (UserStoreException ex) {
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build(); return Response.status(500).entity(ex.getMessage()).build();

@ -25,16 +25,16 @@ import java.io.File;
*/ */
public class ZipArchive { public class ZipArchive {
private File zipFile = null; private byte[] zipFileContent = null;
private String fileName = null; private String fileName = null;
public ZipArchive(String fileName, File zipFile) { public ZipArchive(String fileName, byte[] zipFile) {
this.fileName = fileName; this.fileName = fileName;
this.zipFile = zipFile; this.zipFileContent = zipFile;
} }
public File getZipFile() { public byte[] getZipFileContent() {
return zipFile; return zipFileContent;
} }
public String getFileName() { public String getFileName() {

@ -34,6 +34,7 @@ import org.wso2.carbon.utils.NetworkUtils;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -57,7 +58,6 @@ import java.util.zip.ZipOutputStream;
*/ */
public class ZipUtil { public class ZipUtil {
private static final String HTTP_PORT_PROPERTY = "httpPort";
private static final String CONFIG_TYPE = "general"; private static final String CONFIG_TYPE = "general";
private static final Log log = LogFactory.getLog(ZipUtil.class); private static final Log log = LogFactory.getLog(ZipUtil.class);
private static final String LOCALHOST = "localhost"; private static final String LOCALHOST = "localhost";
@ -69,8 +69,6 @@ public class ZipUtil {
String refreshToken) throws DeviceManagementException { String refreshToken) throws DeviceManagementException {
String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches"; String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches";
String archivesPath = CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" +
File.separator + deviceId;
String templateSketchPath = sketchFolder + File.separator + deviceType; String templateSketchPath = sketchFolder + File.separator + deviceType;
String iotServerIP; String iotServerIP;
@ -113,7 +111,7 @@ public class ZipUtil {
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken); contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
ZipArchive zipFile; ZipArchive zipFile;
zipFile = getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName); zipFile = getSketchArchive(templateSketchPath, contextParams, deviceName);
return zipFile; return zipFile;
} catch (IOException e) { } catch (IOException e) {
throw new DeviceManagementException("Zip File Creation Failed", e); throw new DeviceManagementException("Zip File Creation Failed", e);
@ -122,7 +120,7 @@ public class ZipUtil {
} }
} }
public static String getServerUrl() { private static String getServerUrl() {
try { try {
return org.apache.axis2.util.Utils.getIpAddress(); return org.apache.axis2.util.Utils.getIpAddress();
} catch (SocketException e) { } catch (SocketException e) {
@ -131,32 +129,26 @@ public class ZipUtil {
} }
} }
private static ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams private ZipArchive getSketchArchive(String templateSketchPath, Map contextParams
, String zipFileName) , String zipFileName)
throws DeviceManagementException, IOException { throws DeviceManagementException, IOException {
String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath; String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath;
FileUtils.deleteDirectory(new File(archivesPath));//clear directory
FileUtils.deleteDirectory(new File(archivesPath + ".zip"));//clear zip
if (!new File(archivesPath).mkdirs()) { //new dir
String message = "Could not create directory at path: " + archivesPath;
log.error(message);
throw new DeviceManagementException(message);
}
zipFileName = zipFileName + ".zip"; zipFileName = zipFileName + ".zip";
try { try {
Map<String, List<String>> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties"); Map<String, List<String>> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties");
List<String> templateFiles = properties.get("templates"); List<String> templateFiles = properties.get("templates");
List<TemplateFile> processTemplateFiles = new ArrayList<>();
for (String templateFile : templateFiles) { for (String templateFile : templateFiles) {
parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath + File.separator + templateFile, TemplateFile tFile = new TemplateFile();
contextParams); tFile.setContent(parseTemplate(templateSketchPath + File.separator + templateFile, contextParams));
tFile.setFileName(templateFile);
processTemplateFiles.add(tFile);
} }
templateFiles.add("sketch.properties"); // ommit copying the props file templateFiles.add("sketch.properties"); // ommit copying the props file
copyFolder(new File(sketchPath), new File(archivesPath), templateFiles);
createZipArchive(archivesPath); byte[] zip = createZipArchive(templateSketchPath, processTemplateFiles);
FileUtils.deleteDirectory(new File(archivesPath));
File zip = new File(archivesPath + ".zip");
return new ZipArchive(zipFileName, zip); return new ZipArchive(zipFileName, zip);
} catch (IOException ex) { } catch (IOException ex) {
throw new DeviceManagementException( throw new DeviceManagementException(
@ -196,148 +188,124 @@ public class ZipUtil {
} }
} }
private static void parseTemplate(String srcFile, String dstFile, Map contextParams) throws IOException { private static String parseTemplate(String srcFile, Map contextParams) throws IOException {
//read from file //read from file
FileInputStream inputStream = null; FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try { try {
inputStream = new FileInputStream(srcFile); inputStream = new FileInputStream(srcFile);
outputStream = new FileOutputStream(dstFile);
String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString()); String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString());
Iterator iterator = contextParams.entrySet().iterator(); Iterator iterator = contextParams.entrySet().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next(); Map.Entry mapEntry = (Map.Entry) iterator.next();
content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString()); content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString());
} }
IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString()); return content;
} finally { } finally {
if (inputStream != null) { if (inputStream != null) {
inputStream.close(); inputStream.close();
} }
if (outputStream != null) {
outputStream.close();
}
}
}
private static void copyFolder(File src, File dest, List<String> excludeFileNames) throws IOException {
if (src.isDirectory()) {
//if directory not exists, create it
if (!dest.exists() && !dest.mkdirs()) {
String message = "Could not create directory at path: " + dest;
log.error(message);
throw new IOException(message);
}
//list all the directory contents
String files[] = src.list();
if (files == null) {
log.warn("There are no files insides the directory " + src.getAbsolutePath());
return;
}
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile, destFile, excludeFileNames);
}
} else {
for (String fileName : excludeFileNames) {
if (src.getName().equals(fileName)) {
return;
}
}
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
} }
} }
private static boolean createZipArchive(String srcFolder) throws IOException { private static byte[] createZipArchive(String srcFolder, List<TemplateFile> processTemplateFiles) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = null; ZipOutputStream out = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try { try {
final int BUFFER = 2048; out = new ZipOutputStream(new BufferedOutputStream(baos));
FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip"));
out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
File subDir = new File(srcFolder); File subDir = new File(srcFolder);
String subdirList[] = subDir.list(); String subdirList[] = subDir.list();
if (subdirList == null) { if (subdirList == null) {
log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty"); log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty");
return false; return null;
} }
for (String sd : subdirList) { for (String sd : subdirList) {
// get a list of files from current directory // get a list of files from current directory
File f = new File(srcFolder + "/" + sd); File f = new File(srcFolder + File.separator + sd);
if (f.isDirectory()) { if (f.isDirectory()) {
String files[] = f.list(); String files[] = f.list();
if (files == null) { if (files == null) {
log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files"); log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files");
return false; return null;
} }
for (int i = 0; i < files.length; i++) { for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]); boolean fileAdded = false;
origin = new BufferedInputStream(fi, BUFFER); for (TemplateFile templateFile : processTemplateFiles) {
ZipEntry entry = new ZipEntry(sd + "/" + files[i]); if (files[i].equals(templateFile.getFileName())) {
ZipEntry entry = new ZipEntry(templateFile.getFileName());
out.putNextEntry(entry); out.putNextEntry(entry);
int count; out.write(templateFile.getContent().getBytes());
while ((count = origin.read(data, 0, BUFFER)) != -1) { out.closeEntry();
out.write(data, 0, count); fileAdded = true;
out.flush(); break;
} else if (f.getName().equals("sketch.properties")) {
fileAdded = true;
break;
}
}
if (fileAdded) {
continue;
} }
ZipEntry entry = new ZipEntry(sd + File.separator + files[i]);
out.putNextEntry(entry);
out.write(IOUtils.toByteArray(new FileInputStream(srcFolder + File.separator + sd
+ File.separator + files[i])));
out.closeEntry();
} }
} else //it is just a file } else //it is just a file
{ {
FileInputStream fi = new FileInputStream(f); boolean fileAdded = false;
origin = new BufferedInputStream(fi, BUFFER); for (TemplateFile templateFile : processTemplateFiles) {
ZipEntry entry = new ZipEntry(sd); if (f.getName().equals(templateFile.getFileName())) {
ZipEntry entry = new ZipEntry(templateFile.getFileName());
out.putNextEntry(entry); out.putNextEntry(entry);
int count; out.write(templateFile.getContent().getBytes());
while ((count = origin.read(data, 0, BUFFER)) != -1) { out.closeEntry();
out.write(data, 0, count); fileAdded = true;
out.flush(); break;
} else if (f.getName().equals("sketch.properties")) {
fileAdded = true;
break;
} }
} }
if (fileAdded) {
continue;
}
ZipEntry entry = new ZipEntry(sd);
out.putNextEntry(entry);
out.write(IOUtils.toByteArray(new FileInputStream(f)));
out.closeEntry();
} }
out.flush();
} finally {
if (origin != null) {
origin.close();
} }
out.finish();
} finally {
if (out != null) { if (out != null) {
out.close(); out.close();
} }
} }
return true; return baos.toByteArray();
}
public class TemplateFile {
private String content;
private String fileName;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
} }
} }

@ -144,12 +144,11 @@ public class RaspberryPiServiceImpl implements RaspberryPiService {
String username = APIUtil.getAuthenticatedUser() + "@" + PrivilegedCarbonContext String username = APIUtil.getAuthenticatedUser() + "@" + PrivilegedCarbonContext
.getThreadLocalCarbonContext().getTenantDomain(); .getThreadLocalCarbonContext().getTenantDomain();
ZipArchive zipFile = createDownloadFile(username, deviceName, sketchType); ZipArchive zipFile = createDownloadFile(username, deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); Response.ResponseBuilder response = Response.ok(zipFile.getZipFileContent());
response.status(Response.Status.OK); response.status(Response.Status.OK);
response.type("application/zip"); response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
Response resp = response.build(); Response resp = response.build();
zipFile.getZipFile().delete();
return resp; return resp;
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request return Response.status(400).entity(ex.getMessage()).build();//bad request
@ -162,9 +161,6 @@ public class RaspberryPiServiceImpl implements RaspberryPiService {
} catch (APIManagerException ex) { } catch (APIManagerException ex) {
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build(); return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) { } catch (UserStoreException ex) {
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build(); return Response.status(500).entity(ex.getMessage()).build();

@ -18,23 +18,21 @@
package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util; package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util;
import java.io.File;
/** /**
* This is an utility class to hold zip files. * This is an utility class to hold zip files.
*/ */
public class ZipArchive { public class ZipArchive {
private File zipFile = null; private byte[] zipFileContent = null;
private String fileName = null; private String fileName = null;
public ZipArchive(String fileName, File zipFile) { public ZipArchive(String fileName, byte[] zipFile) {
this.fileName = fileName; this.fileName = fileName;
this.zipFile = zipFile; this.zipFileContent = zipFile;
} }
public File getZipFile() { public byte[] getZipFileContent() {
return zipFile; return zipFileContent;
} }
public String getFileName() { public String getFileName() {

@ -18,27 +18,22 @@
package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util; package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util;
import org.apache.commons.io.FileUtils;
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;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.core.util.Utils; import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.NetworkUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException; import java.net.SocketException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
@ -69,8 +64,6 @@ public class ZipUtil {
String refreshToken) throws DeviceManagementException { String refreshToken) throws DeviceManagementException {
String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches"; String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches";
String archivesPath = CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" +
File.separator + deviceId;
String templateSketchPath = sketchFolder + File.separator + deviceType; String templateSketchPath = sketchFolder + File.separator + deviceType;
String iotServerIP; String iotServerIP;
@ -117,7 +110,7 @@ public class ZipUtil {
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken); contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
ZipArchive zipFile; ZipArchive zipFile;
zipFile = getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName); zipFile = getSketchArchive(templateSketchPath, contextParams, deviceName);
return zipFile; return zipFile;
} catch (IOException e) { } catch (IOException e) {
throw new DeviceManagementException("Zip File Creation Failed", e); throw new DeviceManagementException("Zip File Creation Failed", e);
@ -126,7 +119,7 @@ public class ZipUtil {
} }
} }
public static String getServerUrl() { private static String getServerUrl() {
try { try {
return org.apache.axis2.util.Utils.getIpAddress(); return org.apache.axis2.util.Utils.getIpAddress();
} catch (SocketException e) { } catch (SocketException e) {
@ -135,32 +128,26 @@ public class ZipUtil {
} }
} }
private static ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams private ZipArchive getSketchArchive(String templateSketchPath, Map contextParams
, String zipFileName) , String zipFileName)
throws DeviceManagementException, IOException { throws DeviceManagementException, IOException {
String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath; String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath;
FileUtils.deleteDirectory(new File(archivesPath));//clear directory
FileUtils.deleteDirectory(new File(archivesPath + ".zip"));//clear zip
if (!new File(archivesPath).mkdirs()) { //new dir
String message = "Could not create directory at path: " + archivesPath;
log.error(message);
throw new DeviceManagementException(message);
}
zipFileName = zipFileName + ".zip"; zipFileName = zipFileName + ".zip";
try { try {
Map<String, List<String>> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties"); Map<String, List<String>> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties");
List<String> templateFiles = properties.get("templates"); List<String> templateFiles = properties.get("templates");
List<TemplateFile> processTemplateFiles = new ArrayList<>();
for (String templateFile : templateFiles) { for (String templateFile : templateFiles) {
parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath + File.separator + templateFile, TemplateFile tFile = new TemplateFile();
contextParams); tFile.setContent(parseTemplate(templateSketchPath + File.separator + templateFile, contextParams));
tFile.setFileName(templateFile);
processTemplateFiles.add(tFile);
} }
templateFiles.add("sketch.properties"); // ommit copying the props file templateFiles.add("sketch.properties"); // ommit copying the props file
copyFolder(new File(sketchPath), new File(archivesPath), templateFiles);
createZipArchive(archivesPath); byte[] zip = createZipArchive(templateSketchPath, processTemplateFiles);
FileUtils.deleteDirectory(new File(archivesPath));
File zip = new File(archivesPath + ".zip");
return new ZipArchive(zipFileName, zip); return new ZipArchive(zipFileName, zip);
} catch (IOException ex) { } catch (IOException ex) {
throw new DeviceManagementException( throw new DeviceManagementException(
@ -200,148 +187,124 @@ public class ZipUtil {
} }
} }
private static void parseTemplate(String srcFile, String dstFile, Map contextParams) throws IOException { private static String parseTemplate(String srcFile, Map contextParams) throws IOException {
//read from file //read from file
FileInputStream inputStream = null; FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try { try {
inputStream = new FileInputStream(srcFile); inputStream = new FileInputStream(srcFile);
outputStream = new FileOutputStream(dstFile);
String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString()); String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString());
Iterator iterator = contextParams.entrySet().iterator(); Iterator iterator = contextParams.entrySet().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next(); Map.Entry mapEntry = (Map.Entry) iterator.next();
content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString()); content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString());
} }
IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString()); return content;
} finally { } finally {
if (inputStream != null) { if (inputStream != null) {
inputStream.close(); inputStream.close();
} }
if (outputStream != null) {
outputStream.close();
}
}
}
private static void copyFolder(File src, File dest, List<String> excludeFileNames) throws IOException {
if (src.isDirectory()) {
//if directory not exists, create it
if (!dest.exists() && !dest.mkdirs()) {
String message = "Could not create directory at path: " + dest;
log.error(message);
throw new IOException(message);
}
//list all the directory contents
String files[] = src.list();
if (files == null) {
log.warn("There are no files insides the directory " + src.getAbsolutePath());
return;
}
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile, destFile, excludeFileNames);
}
} else {
for (String fileName : excludeFileNames) {
if (src.getName().equals(fileName)) {
return;
}
}
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
} }
} }
private static boolean createZipArchive(String srcFolder) throws IOException { private static byte[] createZipArchive(String srcFolder, List<TemplateFile> processTemplateFiles) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = null; ZipOutputStream out = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try { try {
final int BUFFER = 2048; out = new ZipOutputStream(new BufferedOutputStream(baos));
FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip"));
out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
File subDir = new File(srcFolder); File subDir = new File(srcFolder);
String subdirList[] = subDir.list(); String subdirList[] = subDir.list();
if (subdirList == null) { if (subdirList == null) {
log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty"); log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty");
return false; return null;
} }
for (String sd : subdirList) { for (String sd : subdirList) {
// get a list of files from current directory // get a list of files from current directory
File f = new File(srcFolder + "/" + sd); File f = new File(srcFolder + File.separator + sd);
if (f.isDirectory()) { if (f.isDirectory()) {
String files[] = f.list(); String files[] = f.list();
if (files == null) { if (files == null) {
log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files"); log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files");
return false; return null;
} }
for (int i = 0; i < files.length; i++) { for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]); boolean fileAdded = false;
origin = new BufferedInputStream(fi, BUFFER); for (TemplateFile templateFile : processTemplateFiles) {
ZipEntry entry = new ZipEntry(sd + "/" + files[i]); if (files[i].equals(templateFile.getFileName())) {
ZipEntry entry = new ZipEntry(templateFile.getFileName());
out.putNextEntry(entry); out.putNextEntry(entry);
int count; out.write(templateFile.getContent().getBytes());
while ((count = origin.read(data, 0, BUFFER)) != -1) { out.closeEntry();
out.write(data, 0, count); fileAdded = true;
out.flush(); break;
} else if (f.getName().equals("sketch.properties")) {
fileAdded = true;
break;
} }
}
if (fileAdded) {
continue;
}
ZipEntry entry = new ZipEntry(sd + File.separator + files[i]);
out.putNextEntry(entry);
out.write(IOUtils.toByteArray(new FileInputStream(srcFolder + File.separator + sd
+ File.separator + files[i])));
out.closeEntry();
} }
} else //it is just a file } else //it is just a file
{ {
FileInputStream fi = new FileInputStream(f); boolean fileAdded = false;
origin = new BufferedInputStream(fi, BUFFER); for (TemplateFile templateFile : processTemplateFiles) {
ZipEntry entry = new ZipEntry(sd); if (f.getName().equals(templateFile.getFileName())) {
ZipEntry entry = new ZipEntry(templateFile.getFileName());
out.putNextEntry(entry); out.putNextEntry(entry);
int count; out.write(templateFile.getContent().getBytes());
while ((count = origin.read(data, 0, BUFFER)) != -1) { out.closeEntry();
out.write(data, 0, count); fileAdded = true;
out.flush(); break;
} else if (f.getName().equals("sketch.properties")) {
fileAdded = true;
break;
} }
} }
if (fileAdded) {
continue;
} }
out.flush(); ZipEntry entry = new ZipEntry(sd);
} finally { out.putNextEntry(entry);
if (origin != null) { out.write(IOUtils.toByteArray(new FileInputStream(f)));
origin.close(); out.closeEntry();
} }
}
out.finish();
} finally {
if (out != null) { if (out != null) {
out.close(); out.close();
} }
} }
return true; return baos.toByteArray();
}
public class TemplateFile {
private String content;
private String fileName;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
} }
} }

@ -51,18 +51,6 @@
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId> <artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>

@ -58,15 +58,11 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Properties; import java.util.Properties;
import java.util.UUID; import java.util.UUID;
@ -175,12 +171,11 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
String user = APIUtil.getAuthenticatedUser() + "@" + PrivilegedCarbonContext.getThreadLocalCarbonContext() String user = APIUtil.getAuthenticatedUser() + "@" + PrivilegedCarbonContext.getThreadLocalCarbonContext()
.getTenantDomain(); .getTenantDomain();
ZipArchive zipFile = createDownloadFile(user, deviceName, sketchType); ZipArchive zipFile = createDownloadFile(user, deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); Response.ResponseBuilder response = Response.ok(zipFile.getZipFileContent());
response.status(Response.Status.OK); response.status(Response.Status.OK);
response.type("application/zip"); response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
Response resp = response.build(); Response resp = response.build();
zipFile.getZipFile().delete();
return resp; return resp;
} catch (IllegalArgumentException ex) { } catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request return Response.status(400).entity(ex.getMessage()).build();//bad request
@ -193,9 +188,6 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
} catch (APIManagerException ex) { } catch (APIManagerException ex) {
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build(); return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) { } catch (UserStoreException ex) {
log.error(ex.getMessage(), ex); log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build(); return Response.status(500).entity(ex.getMessage()).build();

@ -18,23 +18,23 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util;
import java.io.File; import java.util.zip.ZipOutputStream;
/** /**
* This is an utility class to hold zip files. * This is an utility class to hold zip files.
*/ */
public class ZipArchive { public class ZipArchive {
private File zipFile = null; private byte[] zipFileContent = null;
private String fileName = null; private String fileName = null;
public ZipArchive(String fileName, File zipFile) { public ZipArchive(String fileName, byte[] zipFile) {
this.fileName = fileName; this.fileName = fileName;
this.zipFile = zipFile; this.zipFileContent = zipFile;
} }
public File getZipFile() { public byte[] getZipFileContent() {
return zipFile; return zipFileContent;
} }
public String getFileName() { public String getFileName() {

@ -19,7 +19,6 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
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;
@ -33,14 +32,12 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.xmpp.XmppConfig;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException; import java.net.SocketException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
@ -59,24 +56,18 @@ import java.util.zip.ZipOutputStream;
public class ZipUtil { public class ZipUtil {
private static final Log log = LogFactory.getLog(ZipUtil.class); private static final Log log = LogFactory.getLog(ZipUtil.class);
private static final String HTTPS_PORT_PROPERTY = "httpsPort";
private static final String HTTP_PORT_PROPERTY = "httpPort";
private static final String LOCALHOST = "localhost"; private static final String LOCALHOST = "localhost";
private static final String HTTPS_PROTOCOL_URL = "https://${iot.gateway.host}:${iot.gateway.https.port}"; private static final String HTTPS_PROTOCOL_URL = "https://${iot.gateway.host}:${iot.gateway.https.port}";
private static final String HTTP_PROTOCOL_URL = "http://${iot.gateway.host}:${iot.gateway.http.port}"; private static final String HTTP_PROTOCOL_URL = "http://${iot.gateway.host}:${iot.gateway.http.port}";
private static final String CONFIG_TYPE = "general"; private static final String CONFIG_TYPE = "general";
private static final String DEFAULT_MQTT_ENDPOINT = "tcp://${mqtt.broker.host}:${mqtt.broker.port}"; private static final String DEFAULT_MQTT_ENDPOINT = "tcp://${mqtt.broker.host}:${mqtt.broker.port}";
public static final String HOST_NAME = "HostName";
public ZipArchive createZipFile(String owner, String deviceType, String deviceId, String deviceName, public ZipArchive createZipFile(String owner, String deviceType, String deviceId, String deviceName,
String apiApplicationKey, String token, String refreshToken) String apiApplicationKey, String token, String refreshToken)
throws DeviceManagementException { throws DeviceManagementException {
String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches"; String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches";
String archivesPath =
CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" +
File.separator + deviceId;
String templateSketchPath = sketchFolder + File.separator + deviceType; String templateSketchPath = sketchFolder + File.separator + deviceType;
String iotServerIP; String iotServerIP;
@ -141,7 +132,7 @@ public class ZipUtil {
? "" : XmppConfig.getInstance().getJid()); ? "" : XmppConfig.getInstance().getJid());
ZipArchive zipFile; ZipArchive zipFile;
zipFile = getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName); zipFile = getSketchArchive(templateSketchPath, contextParams, deviceName);
return zipFile; return zipFile;
} catch (IOException e) { } catch (IOException e) {
throw new DeviceManagementException("Zip File Creation Failed", e); throw new DeviceManagementException("Zip File Creation Failed", e);
@ -159,7 +150,7 @@ public class ZipUtil {
return Base64.encodeBase64String(stringToEncode.getBytes()); return Base64.encodeBase64String(stringToEncode.getBytes());
} }
public static String getServerUrl() { private static String getServerUrl() {
try { try {
return org.apache.axis2.util.Utils.getIpAddress(); return org.apache.axis2.util.Utils.getIpAddress();
} catch (SocketException e) { } catch (SocketException e) {
@ -168,33 +159,27 @@ public class ZipUtil {
} }
} }
public static ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams private ZipArchive getSketchArchive(String templateSketchPath, Map contextParams
, String zipFileName) , String zipFileName)
throws DeviceManagementException, IOException { throws DeviceManagementException, IOException {
String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath; String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath;
FileUtils.deleteDirectory(new File(archivesPath));//clear directory
FileUtils.deleteDirectory(new File(archivesPath + ".zip"));//clear zip
if (!new File(archivesPath).mkdirs()) { //new dir
String message = "Could not create directory at path: " + archivesPath;
log.error(message);
throw new DeviceManagementException(message);
}
zipFileName = zipFileName + ".zip"; zipFileName = zipFileName + ".zip";
try { try {
Map<String, List<String>> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties"); Map<String, List<String>> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties");
List<String> templateFiles = properties.get("templates"); List<String> templateFiles = properties.get("templates");
List<TemplateFile> processTemplateFiles = new ArrayList<>();
for (String templateFile : templateFiles) { for (String templateFile : templateFiles) {
parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath + File.separator + templateFile, TemplateFile tFile = new TemplateFile();
contextParams); tFile.setContent(parseTemplate(templateSketchPath + File.separator + templateFile, contextParams));
tFile.setFileName(templateFile);
processTemplateFiles.add(tFile);
} }
templateFiles.add("sketch.properties"); // ommit copying the props file templateFiles.add("sketch.properties"); // ommit copying the props file
copyFolder(new File(sketchPath), new File(archivesPath), templateFiles);
createZipArchive(archivesPath); byte[] zip = createZipArchive(templateSketchPath, processTemplateFiles);
FileUtils.deleteDirectory(new File(archivesPath)); return new ZipArchive(zipFileName, zip);
File zip = new File(archivesPath + ".zip");
return new org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipArchive(zipFileName, zip);
} catch (IOException ex) { } catch (IOException ex) {
throw new DeviceManagementException( throw new DeviceManagementException(
"Error occurred when trying to read property " + "file sketch.properties", ex); "Error occurred when trying to read property " + "file sketch.properties", ex);
@ -206,9 +191,7 @@ public class ZipUtil {
InputStream input = null; InputStream input = null;
try { try {
input = new FileInputStream(propertyFilePath); input = new FileInputStream(propertyFilePath);
// load a properties file // load a properties file
prop.load(input); prop.load(input);
Map<String, List<String>> properties = new HashMap<String, List<String>>(); Map<String, List<String>> properties = new HashMap<String, List<String>>();
@ -235,148 +218,124 @@ public class ZipUtil {
} }
} }
private static void parseTemplate(String srcFile, String dstFile, Map contextParams) throws IOException { private static String parseTemplate(String srcFile, Map contextParams) throws IOException {
//read from file //read from file
FileInputStream inputStream = null; FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try { try {
inputStream = new FileInputStream(srcFile); inputStream = new FileInputStream(srcFile);
outputStream = new FileOutputStream(dstFile);
String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString()); String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString());
Iterator iterator = contextParams.entrySet().iterator(); Iterator iterator = contextParams.entrySet().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next(); Map.Entry mapEntry = (Map.Entry) iterator.next();
content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString()); content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString());
} }
IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString()); return content;
} finally { } finally {
if (inputStream != null) { if (inputStream != null) {
inputStream.close(); inputStream.close();
} }
if (outputStream != null) {
outputStream.close();
}
}
}
private static void copyFolder(File src, File dest, List<String> excludeFileNames) throws IOException {
if (src.isDirectory()) {
//if directory not exists, create it
if (!dest.exists() && !dest.mkdirs()) {
String message = "Could not create directory at path: " + dest;
log.error(message);
throw new IOException(message);
} }
//list all the directory contents
String files[] = src.list();
if (files == null) {
log.warn("There are no files insides the directory " + src.getAbsolutePath());
return;
} }
for (String file : files) { private static byte[] createZipArchive(String srcFolder, List<TemplateFile> processTemplateFiles) throws IOException {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile, destFile, excludeFileNames);
}
} else {
for (String fileName : excludeFileNames) {
if (src.getName().equals(fileName)) {
return;
}
}
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
private static boolean createZipArchive(String srcFolder) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = null; ZipOutputStream out = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try { try {
final int BUFFER = 2048; out = new ZipOutputStream(new BufferedOutputStream(baos));
FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip"));
out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
File subDir = new File(srcFolder); File subDir = new File(srcFolder);
String subdirList[] = subDir.list(); String subdirList[] = subDir.list();
if (subdirList == null) { if (subdirList == null) {
log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty"); log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty");
return false; return null;
} }
for (String sd : subdirList) { for (String sd : subdirList) {
// get a list of files from current directory // get a list of files from current directory
File f = new File(srcFolder + "/" + sd); File f = new File(srcFolder + File.separator + sd);
if (f.isDirectory()) { if (f.isDirectory()) {
String files[] = f.list(); String files[] = f.list();
if (files == null) { if (files == null) {
log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files"); log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files");
return false; return null;
} }
for (int i = 0; i < files.length; i++) { for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]); boolean fileAdded = false;
origin = new BufferedInputStream(fi, BUFFER); for (TemplateFile templateFile : processTemplateFiles) {
ZipEntry entry = new ZipEntry(sd + "/" + files[i]); if (files[i].equals(templateFile.getFileName())) {
ZipEntry entry = new ZipEntry(templateFile.getFileName());
out.putNextEntry(entry); out.putNextEntry(entry);
int count; out.write(templateFile.getContent().getBytes());
while ((count = origin.read(data, 0, BUFFER)) != -1) { out.closeEntry();
out.write(data, 0, count); fileAdded = true;
out.flush(); break;
} else if (f.getName().equals("sketch.properties")) {
fileAdded = true;
break;
}
}
if (fileAdded) {
continue;
} }
ZipEntry entry = new ZipEntry(sd + File.separator + files[i]);
out.putNextEntry(entry);
out.write(IOUtils.toByteArray(new FileInputStream(srcFolder + File.separator + sd
+ File.separator + files[i])));
out.closeEntry();
} }
} else //it is just a file } else //it is just a file
{ {
FileInputStream fi = new FileInputStream(f); boolean fileAdded = false;
origin = new BufferedInputStream(fi, BUFFER); for (TemplateFile templateFile : processTemplateFiles) {
ZipEntry entry = new ZipEntry(sd); if (f.getName().equals(templateFile.getFileName())) {
ZipEntry entry = new ZipEntry(templateFile.getFileName());
out.putNextEntry(entry); out.putNextEntry(entry);
int count; out.write(templateFile.getContent().getBytes());
while ((count = origin.read(data, 0, BUFFER)) != -1) { out.closeEntry();
out.write(data, 0, count); fileAdded = true;
out.flush(); break;
} else if (f.getName().equals("sketch.properties")) {
fileAdded = true;
break;
} }
} }
if (fileAdded) {
continue;
}
ZipEntry entry = new ZipEntry(sd);
out.putNextEntry(entry);
out.write(IOUtils.toByteArray(new FileInputStream(f)));
out.closeEntry();
} }
out.flush();
} finally {
if (origin != null) {
origin.close();
} }
out.finish();
} finally {
if (out != null) { if (out != null) {
out.close(); out.close();
} }
} }
return true; return baos.toByteArray();
}
public class TemplateFile {
private String content;
private String fileName;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
} }
} }

@ -1,61 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipArchive;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.NetworkUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Provides utility methods required by the device type plugins.
*/
public class Utils {
public static final String HOST_NAME = "HostName";
private static final Log log = LogFactory.getLog(Utils.class);
}

@ -68,7 +68,8 @@
org.json.simple.*, org.json.simple.*,
org.wso2.carbon.appmgt.mobile.beans, org.wso2.carbon.appmgt.mobile.beans,
org.wso2.carbon.context, org.wso2.carbon.context,
javax.net.ssl javax.net.ssl,
feign.slf4j
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
!org.wso2.carbon.appmgt.mdm.restconnector.internal, !org.wso2.carbon.appmgt.mdm.restconnector.internal,
@ -121,6 +122,10 @@
<groupId>org.wso2.carbon.appmgt</groupId> <groupId>org.wso2.carbon.appmgt</groupId>
<artifactId>org.wso2.carbon.appmgt.mobile</artifactId> <artifactId>org.wso2.carbon.appmgt.mobile</artifactId>
</dependency> </dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

@ -19,9 +19,13 @@ package org.wso2.carbon.appmgt.mdm.restconnector;
import feign.Client; import feign.Client;
import feign.Feign; import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.Response;
import feign.gson.GsonDecoder; import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder; import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract; import feign.jaxrs.JAXRSContract;
import feign.slf4j.Slf4jLogger;
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.simple.JSONObject; import org.json.simple.JSONObject;
@ -51,6 +55,7 @@ import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.ArrayList;
@ -71,13 +76,13 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
public ApplicationOperationsImpl() { public ApplicationOperationsImpl() {
String authorizationConfigManagerServerURL = AuthorizationConfigurationManager.getInstance().getServerURL(); String authorizationConfigManagerServerURL = AuthorizationConfigurationManager.getInstance().getServerURL();
OAuthRequestInterceptor oAuthRequestInterceptor = new OAuthRequestInterceptor(); OAuthRequestInterceptor oAuthRequestInterceptor = new OAuthRequestInterceptor();
deviceManagementAdminService = Feign.builder().client(getSSLClient()) deviceManagementAdminService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()).logLevel(
.requestInterceptor(oAuthRequestInterceptor) Logger.Level.FULL).requestInterceptor(oAuthRequestInterceptor)
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(DeviceManagementAdminService.class, .target(DeviceManagementAdminService.class,
authorizationConfigManagerServerURL + CDMF_SERVER_BASE_CONTEXT); authorizationConfigManagerServerURL + CDMF_SERVER_BASE_CONTEXT);
applicationManagementAdminService = Feign.builder().client(getSSLClient()) applicationManagementAdminService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()).logLevel(
.requestInterceptor(oAuthRequestInterceptor) Logger.Level.FULL).requestInterceptor(oAuthRequestInterceptor)
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(ApplicationManagementAdminService.class, .target(ApplicationManagementAdminService.class,
authorizationConfigManagerServerURL + CDMF_SERVER_BASE_CONTEXT); authorizationConfigManagerServerURL + CDMF_SERVER_BASE_CONTEXT);
@ -311,6 +316,6 @@ public class ApplicationOperationsImpl implements ApplicationOperations {
} catch (KeyManagementException | NoSuchAlgorithmException e) { } catch (KeyManagementException | NoSuchAlgorithmException e) {
return null; return null;
} }
} }
} }

@ -19,12 +19,18 @@ package org.wso2.carbon.appmgt.mdm.restconnector.authorization.client;
import feign.Client; import feign.Client;
import feign.Feign; import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.RequestTemplate; import feign.RequestTemplate;
import feign.Response;
import feign.auth.BasicAuthRequestInterceptor; import feign.auth.BasicAuthRequestInterceptor;
import feign.gson.GsonDecoder; import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder; import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract; import feign.jaxrs.JAXRSContract;
import feign.slf4j.Slf4jLogger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.appmgt.mdm.restconnector.Constants; import org.wso2.carbon.appmgt.mdm.restconnector.Constants;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.AccessTokenInfo; import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.AccessTokenInfo;
import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.ApiApplicationKey; import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.ApiApplicationKey;
@ -40,6 +46,7 @@ import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -56,6 +63,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private static final String REFRESH_GRANT_TYPE = "refresh_token"; private static final String REFRESH_GRANT_TYPE = "refresh_token";
private ApiApplicationRegistrationService apiApplicationRegistrationService; private ApiApplicationRegistrationService apiApplicationRegistrationService;
private TokenIssuerService tokenIssuerService; private TokenIssuerService tokenIssuerService;
private static Log log = LogFactory.getLog(OAuthRequestInterceptor.class);
/** /**
* Creates an interceptor that authenticates all requests. * Creates an interceptor that authenticates all requests.
@ -64,8 +73,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
refreshTimeOffset = AuthorizationConfigurationManager.getInstance().getTokenRefreshTimeOffset(); refreshTimeOffset = AuthorizationConfigurationManager.getInstance().getTokenRefreshTimeOffset();
String username = AuthorizationConfigurationManager.getInstance().getUserName(); String username = AuthorizationConfigurationManager.getInstance().getUserName();
String password = AuthorizationConfigurationManager.getInstance().getPassword(); String password = AuthorizationConfigurationManager.getInstance().getPassword();
apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).requestInterceptor( apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()).logLevel(
new BasicAuthRequestInterceptor(username, password)) Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(ApiApplicationRegistrationService.class, .target(ApiApplicationRegistrationService.class,
AuthorizationConfigurationManager.getInstance().getServerURL() + AuthorizationConfigurationManager.getInstance().getServerURL() +
@ -92,8 +101,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
String consumerSecret = apiApplicationKey.getConsumerSecret(); String consumerSecret = apiApplicationKey.getConsumerSecret();
String username = AuthorizationConfigurationManager.getInstance().getUserName(); String username = AuthorizationConfigurationManager.getInstance().getUserName();
String password = AuthorizationConfigurationManager.getInstance().getPassword(); String password = AuthorizationConfigurationManager.getInstance().getPassword();
tokenIssuerService = Feign.builder().client(getSSLClient()).requestInterceptor( tokenIssuerService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()).logLevel(Logger.Level.FULL)
new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) .requestInterceptor(new BasicAuthRequestInterceptor(consumerKey, consumerSecret))
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(TokenIssuerService.class, AuthorizationConfigurationManager.getInstance().getTokenApiURL()); .target(TokenIssuerService.class, AuthorizationConfigurationManager.getInstance().getTokenApiURL());
tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password); tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password);
@ -139,6 +148,6 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
} catch (KeyManagementException | NoSuchAlgorithmException e) { } catch (KeyManagementException | NoSuchAlgorithmException e) {
return null; return null;
} }
} }
} }

@ -92,6 +92,10 @@
<groupId>javax.ws.rs</groupId> <groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId> <artifactId>jsr311-api</artifactId>
</dependency> </dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -161,7 +165,8 @@
org.wso2.carbon.identity.oauth2.*, org.wso2.carbon.identity.oauth2.*,
org.wso2.carbon.utils, org.wso2.carbon.utils,
org.wso2.carbon.utils.multitenancy, org.wso2.carbon.utils.multitenancy,
javax.net.ssl javax.net.ssl,
feign.slf4j
</Import-Package> </Import-Package>
<Embed-Dependency> <Embed-Dependency>
jsr311-api, jsr311-api,

@ -20,9 +20,13 @@ package org.wso2.carbon.device.mgt.input.adapter.http.authorization;
import feign.Client; import feign.Client;
import feign.Feign; import feign.Feign;
import feign.FeignException; import feign.FeignException;
import feign.Logger;
import feign.Request;
import feign.Response;
import feign.gson.GsonDecoder; import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder; import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract; import feign.jaxrs.JAXRSContract;
import feign.slf4j.Slf4jLogger;
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.input.adapter.http.authorization.client.OAuthRequestInterceptor; import org.wso2.carbon.device.mgt.input.adapter.http.authorization.client.OAuthRequestInterceptor;
@ -40,10 +44,10 @@ import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -55,17 +59,17 @@ public class DeviceAuthorizer {
private static DeviceAccessAuthorizationAdminService deviceAccessAuthorizationAdminService; private static DeviceAccessAuthorizationAdminService deviceAccessAuthorizationAdminService;
private static final String CDMF_SERVER_BASE_CONTEXT = "/api/device-mgt/v1.0"; private static final String CDMF_SERVER_BASE_CONTEXT = "/api/device-mgt/v1.0";
private static final String DEVICE_MGT_SERVER_URL = "deviceMgtServerUrl"; private static final String DEVICE_MGT_SERVER_URL = "deviceMgtServerUrl";
private static Log logger = LogFactory.getLog(DeviceAuthorizer.class); private static Log log = LogFactory.getLog(DeviceAuthorizer.class);
public DeviceAuthorizer(Map<String, String> globalProperties) { public DeviceAuthorizer(Map<String, String> globalProperties) {
try { try {
deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()) deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger())
.requestInterceptor(new OAuthRequestInterceptor(globalProperties)) .logLevel(Logger.Level.FULL).requestInterceptor(new OAuthRequestInterceptor(globalProperties))
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(DeviceAccessAuthorizationAdminService.class, getDeviceMgtServerUrl(globalProperties) .target(DeviceAccessAuthorizationAdminService.class, getDeviceMgtServerUrl(globalProperties)
+ CDMF_SERVER_BASE_CONTEXT); + CDMF_SERVER_BASE_CONTEXT);
} catch (InputEventAdapterException e) { } catch (InputEventAdapterException e) {
logger.error("Invalid value for deviceMgtServerUrl in globalProperties."); log.error("Invalid value for deviceMgtServerUrl in globalProperties.");
} }
} }
@ -94,7 +98,7 @@ public class DeviceAuthorizer {
} }
} }
} catch (FeignException e) { } catch (FeignException e) {
logger.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
} }
return false; return false;
@ -103,7 +107,7 @@ public class DeviceAuthorizer {
private String getDeviceMgtServerUrl(Map<String, String> properties) throws InputEventAdapterException { private String getDeviceMgtServerUrl(Map<String, String> properties) throws InputEventAdapterException {
String deviceMgtServerUrl = PropertyUtils.replaceProperty(properties.get(DEVICE_MGT_SERVER_URL)); String deviceMgtServerUrl = PropertyUtils.replaceProperty(properties.get(DEVICE_MGT_SERVER_URL));
if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) { if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) {
logger.error("deviceMgtServerUrl can't be empty "); log.error("deviceMgtServerUrl can't be empty ");
} }
return deviceMgtServerUrl; return deviceMgtServerUrl;
} }
@ -138,6 +142,6 @@ public class DeviceAuthorizer {
} catch (KeyManagementException | NoSuchAlgorithmException e) { } catch (KeyManagementException | NoSuchAlgorithmException e) {
return null; return null;
} }
} }
} }

@ -16,12 +16,16 @@ package org.wso2.carbon.device.mgt.input.adapter.http.authorization.client;
import feign.Client; import feign.Client;
import feign.Feign; import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.RequestTemplate; import feign.RequestTemplate;
import feign.Response;
import feign.auth.BasicAuthRequestInterceptor; import feign.auth.BasicAuthRequestInterceptor;
import feign.gson.GsonDecoder; import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder; import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract; import feign.jaxrs.JAXRSContract;
import feign.slf4j.Slf4jLogger;
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.input.adapter.http.authorization.client.dto.AccessTokenInfo; import org.wso2.carbon.device.mgt.input.adapter.http.authorization.client.dto.AccessTokenInfo;
@ -38,6 +42,7 @@ import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.Map; import java.util.Map;
@ -58,7 +63,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private ApiApplicationRegistrationService apiApplicationRegistrationService; private ApiApplicationRegistrationService apiApplicationRegistrationService;
private TokenIssuerService tokenIssuerService; private TokenIssuerService tokenIssuerService;
private static Log logger = LogFactory.getLog(OAuthRequestInterceptor.class); private static Log log = LogFactory.getLog(OAuthRequestInterceptor.class);
private static final String CONNECTION_USERNAME = "username"; private static final String CONNECTION_USERNAME = "username";
private static final String CONNECTION_PASSWORD = "password"; private static final String CONNECTION_PASSWORD = "password";
@ -85,13 +90,13 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
username = getUsername(globalProperties); username = getUsername(globalProperties);
password = getPassword(globalProperties); password = getPassword(globalProperties);
tokenEndpoint = getTokenEndpoint(globalProperties); tokenEndpoint = getTokenEndpoint(globalProperties);
apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).requestInterceptor( apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()).logLevel(
new BasicAuthRequestInterceptor(username, password)) Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(ApiApplicationRegistrationService.class, .target(ApiApplicationRegistrationService.class,
deviceMgtServerUrl + API_APPLICATION_REGISTRATION_CONTEXT); deviceMgtServerUrl + API_APPLICATION_REGISTRATION_CONTEXT);
} catch (InputEventAdapterException e) { } catch (InputEventAdapterException e) {
logger.error("Invalid url: deviceMgtServerUrl" + deviceMgtServerUrl + " or tokenEndpoint:" + tokenEndpoint, log.error("Invalid url: deviceMgtServerUrl" + deviceMgtServerUrl + " or tokenEndpoint:" + tokenEndpoint,
e); e);
} }
} }
@ -108,8 +113,9 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
ApiApplicationKey apiApplicationKey = apiApplicationRegistrationService.register(apiRegistrationProfile); ApiApplicationKey apiApplicationKey = apiApplicationRegistrationService.register(apiRegistrationProfile);
String consumerKey = apiApplicationKey.getConsumerKey(); String consumerKey = apiApplicationKey.getConsumerKey();
String consumerSecret = apiApplicationKey.getConsumerSecret(); String consumerSecret = apiApplicationKey.getConsumerSecret();
tokenIssuerService = Feign.builder().client(getSSLClient()).requestInterceptor( tokenIssuerService = Feign.builder().client(getSSLClient())
new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) .logger(new Slf4jLogger()).logLevel(Logger.Level.FULL)
.requestInterceptor(new BasicAuthRequestInterceptor(consumerKey, consumerSecret))
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(TokenIssuerService.class, tokenEndpoint); .target(TokenIssuerService.class, tokenEndpoint);
tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password, REQUIRED_SCOPE); tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password, REQUIRED_SCOPE);
@ -128,7 +134,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private String getUsername(Map<String, String> globalProperties) { private String getUsername(Map<String, String> globalProperties) {
String username = globalProperties.get(CONNECTION_USERNAME); String username = globalProperties.get(CONNECTION_USERNAME);
if (username == null || username.isEmpty()) { if (username == null || username.isEmpty()) {
logger.error("username can't be empty "); log.error("username can't be empty ");
} }
return username; return username;
} }
@ -136,7 +142,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private String getPassword(Map<String, String> globalProperties) { private String getPassword(Map<String, String> globalProperties) {
String password = globalProperties.get(CONNECTION_PASSWORD);; String password = globalProperties.get(CONNECTION_PASSWORD);;
if (password == null || password.isEmpty()) { if (password == null || password.isEmpty()) {
logger.error("password can't be empty "); log.error("password can't be empty ");
} }
return password; return password;
} }
@ -144,7 +150,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private String getDeviceMgtServerUrl(Map<String, String> globalProperties) throws InputEventAdapterException { private String getDeviceMgtServerUrl(Map<String, String> globalProperties) throws InputEventAdapterException {
String deviceMgtServerUrl = globalProperties.get(DEVICE_MGT_SERVER_URL); String deviceMgtServerUrl = globalProperties.get(DEVICE_MGT_SERVER_URL);
if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) { if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) {
logger.error("deviceMgtServerUrl can't be empty "); log.error("deviceMgtServerUrl can't be empty ");
} }
return PropertyUtils.replaceProperty(deviceMgtServerUrl); return PropertyUtils.replaceProperty(deviceMgtServerUrl);
} }
@ -152,7 +158,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private String getTokenEndpoint(Map<String, String> globalProperties) throws InputEventAdapterException { private String getTokenEndpoint(Map<String, String> globalProperties) throws InputEventAdapterException {
String tokenEndpoint = globalProperties.get(TOKEN_ENDPOINT_CONTEXT); String tokenEndpoint = globalProperties.get(TOKEN_ENDPOINT_CONTEXT);
if ( tokenEndpoint.isEmpty()) { if ( tokenEndpoint.isEmpty()) {
logger.error("tokenEndpoint can't be empty "); log.error("tokenEndpoint can't be empty ");
} }
return PropertyUtils.replaceProperty(tokenEndpoint); return PropertyUtils.replaceProperty(tokenEndpoint);
} }
@ -162,7 +168,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
try { try {
refreshTimeOffset = Long.parseLong(globalProperties.get(TOKEN_REFRESH_TIME_OFFSET)); refreshTimeOffset = Long.parseLong(globalProperties.get(TOKEN_REFRESH_TIME_OFFSET));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
logger.error("refreshTimeOffset should be a number", e); log.error("refreshTimeOffset should be a number", e);
} }
return refreshTimeOffset; return refreshTimeOffset;
} }
@ -197,7 +203,5 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
} catch (KeyManagementException | NoSuchAlgorithmException e) { } catch (KeyManagementException | NoSuchAlgorithmException e) {
return null; return null;
} }
} }
} }

@ -95,6 +95,10 @@
<groupId>javax.ws.rs</groupId> <groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId> <artifactId>jsr311-api</artifactId>
</dependency> </dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -170,7 +174,8 @@
feign.codec, feign.codec,
feign.gson, feign.gson,
javax.cache, javax.cache,
javax.net.ssl javax.net.ssl,
feign.slf4j
</Import-Package> </Import-Package>
<DynamicImport-Package>*</DynamicImport-Package> <DynamicImport-Package>*</DynamicImport-Package>
<Embed-Dependency> <Embed-Dependency>

@ -20,9 +20,13 @@ package org.wso2.carbon.device.mgt.output.adapter.websocket.authorization;
import feign.Client; import feign.Client;
import feign.Feign; import feign.Feign;
import feign.FeignException; import feign.FeignException;
import feign.Logger;
import feign.Request;
import feign.Response;
import feign.gson.GsonDecoder; import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder; import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract; import feign.jaxrs.JAXRSContract;
import feign.slf4j.Slf4jLogger;
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.output.adapter.websocket.authentication.AuthenticationInfo; import org.wso2.carbon.device.mgt.output.adapter.websocket.authentication.AuthenticationInfo;
@ -43,6 +47,7 @@ import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import javax.websocket.Session; import javax.websocket.Session;
import java.io.IOException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.ArrayList;
@ -61,7 +66,7 @@ public class DeviceAuthorizer implements Authorizer {
private static final String STAT_PERMISSION = "statsPermission"; private static final String STAT_PERMISSION = "statsPermission";
private static final String DEVICE_ID = "deviceId"; private static final String DEVICE_ID = "deviceId";
private static final String DEVICE_TYPE = "deviceType"; private static final String DEVICE_TYPE = "deviceType";
private static Log logger = LogFactory.getLog(DeviceAuthorizer.class); private static Log log = LogFactory.getLog(DeviceAuthorizer.class);
private static List<String> statPermissions; private static List<String> statPermissions;
public DeviceAuthorizer() { public DeviceAuthorizer() {
@ -76,13 +81,13 @@ public class DeviceAuthorizer implements Authorizer {
} }
} }
try { try {
deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()) deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger())
.requestInterceptor(new OAuthRequestInterceptor(globalProperties)) .logLevel(Logger.Level.FULL).requestInterceptor(new OAuthRequestInterceptor(globalProperties))
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(DeviceAccessAuthorizationAdminService.class, getDeviceMgtServerUrl(globalProperties) .target(DeviceAccessAuthorizationAdminService.class, getDeviceMgtServerUrl(globalProperties)
+ CDMF_SERVER_BASE_CONTEXT); + CDMF_SERVER_BASE_CONTEXT);
} catch (OutputEventAdapterException e) { } catch (OutputEventAdapterException e) {
logger.error("Invalid value for deviceMgtServerUrl in globalProperties."); log.error("Invalid value for deviceMgtServerUrl in globalProperties.");
} }
} }
@ -118,7 +123,7 @@ public class DeviceAuthorizer implements Authorizer {
} }
} }
} catch (FeignException e) { } catch (FeignException e) {
logger.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
} }
return false; return false;
@ -127,7 +132,7 @@ public class DeviceAuthorizer implements Authorizer {
private String getDeviceMgtServerUrl(Map<String, String> properties) throws OutputEventAdapterException { private String getDeviceMgtServerUrl(Map<String, String> properties) throws OutputEventAdapterException {
String deviceMgtServerUrl = PropertyUtils.replaceProperty(properties.get(DEVICE_MGT_SERVER_URL)); String deviceMgtServerUrl = PropertyUtils.replaceProperty(properties.get(DEVICE_MGT_SERVER_URL));
if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) { if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) {
logger.error("deviceMgtServerUrl can't be empty "); log.error("deviceMgtServerUrl can't be empty ");
} }
return deviceMgtServerUrl; return deviceMgtServerUrl;
} }
@ -170,6 +175,5 @@ public class DeviceAuthorizer implements Authorizer {
} catch (KeyManagementException | NoSuchAlgorithmException e) { } catch (KeyManagementException | NoSuchAlgorithmException e) {
return null; return null;
} }
} }
} }

@ -16,12 +16,16 @@ package org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client
import feign.Client; import feign.Client;
import feign.Feign; import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.RequestTemplate; import feign.RequestTemplate;
import feign.Response;
import feign.auth.BasicAuthRequestInterceptor; import feign.auth.BasicAuthRequestInterceptor;
import feign.gson.GsonDecoder; import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder; import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract; import feign.jaxrs.JAXRSContract;
import feign.slf4j.Slf4jLogger;
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.output.adapter.websocket.authorization.client.dto.AccessTokenInfo; import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client.dto.AccessTokenInfo;
@ -38,6 +42,7 @@ import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.Map; import java.util.Map;
@ -58,7 +63,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private ApiApplicationRegistrationService apiApplicationRegistrationService; private ApiApplicationRegistrationService apiApplicationRegistrationService;
private TokenIssuerService tokenIssuerService; private TokenIssuerService tokenIssuerService;
private static Log logger = LogFactory.getLog(OAuthRequestInterceptor.class); private static Log log = LogFactory.getLog(OAuthRequestInterceptor.class);
private static final String CONNECTION_USERNAME = "username"; private static final String CONNECTION_USERNAME = "username";
private static final String CONNECTION_PASSWORD = "password"; private static final String CONNECTION_PASSWORD = "password";
@ -86,13 +91,13 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
username = getUsername(globalProperties); username = getUsername(globalProperties);
password = getPassword(globalProperties); password = getPassword(globalProperties);
tokenEndpoint = getTokenEndpoint(globalProperties); tokenEndpoint = getTokenEndpoint(globalProperties);
apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).requestInterceptor( apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger())
new BasicAuthRequestInterceptor(username, password)) .logLevel(Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(ApiApplicationRegistrationService.class, .target(ApiApplicationRegistrationService.class,
deviceMgtServerUrl + API_APPLICATION_REGISTRATION_CONTEXT); deviceMgtServerUrl + API_APPLICATION_REGISTRATION_CONTEXT);
} catch (OutputEventAdapterException e) { } catch (OutputEventAdapterException e) {
logger.error("Invalid url: deviceMgtServerUrl" + deviceMgtServerUrl + " or tokenEndpoint:" + tokenEndpoint, log.error("Invalid url: deviceMgtServerUrl" + deviceMgtServerUrl + " or tokenEndpoint:" + tokenEndpoint,
e); e);
} }
} }
@ -109,8 +114,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
ApiApplicationKey apiApplicationKey = apiApplicationRegistrationService.register(apiRegistrationProfile); ApiApplicationKey apiApplicationKey = apiApplicationRegistrationService.register(apiRegistrationProfile);
String consumerKey = apiApplicationKey.getConsumerKey(); String consumerKey = apiApplicationKey.getConsumerKey();
String consumerSecret = apiApplicationKey.getConsumerSecret(); String consumerSecret = apiApplicationKey.getConsumerSecret();
tokenIssuerService = Feign.builder().client(getSSLClient()).requestInterceptor( tokenIssuerService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()).logLevel(Logger.Level.FULL)
new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) .requestInterceptor(new BasicAuthRequestInterceptor(consumerKey, consumerSecret))
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(TokenIssuerService.class, tokenEndpoint); .target(TokenIssuerService.class, tokenEndpoint);
tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password, REQUIRED_SCOPE); tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password, REQUIRED_SCOPE);
@ -129,7 +134,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private String getUsername(Map<String, String> globalProperties) { private String getUsername(Map<String, String> globalProperties) {
String username = globalProperties.get(CONNECTION_USERNAME); String username = globalProperties.get(CONNECTION_USERNAME);
if (username == null || username.isEmpty()) { if (username == null || username.isEmpty()) {
logger.error("username can't be empty "); log.error("username can't be empty ");
} }
return username; return username;
} }
@ -137,7 +142,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private String getPassword(Map<String, String> globalProperties) { private String getPassword(Map<String, String> globalProperties) {
String password = globalProperties.get(CONNECTION_PASSWORD);; String password = globalProperties.get(CONNECTION_PASSWORD);;
if (password == null || password.isEmpty()) { if (password == null || password.isEmpty()) {
logger.error("password can't be empty "); log.error("password can't be empty ");
} }
return password; return password;
} }
@ -145,7 +150,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private String getDeviceMgtServerUrl(Map<String, String> globalProperties) throws OutputEventAdapterException { private String getDeviceMgtServerUrl(Map<String, String> globalProperties) throws OutputEventAdapterException {
String deviceMgtServerUrl = globalProperties.get(DEVICE_MGT_SERVER_URL); String deviceMgtServerUrl = globalProperties.get(DEVICE_MGT_SERVER_URL);
if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) { if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) {
logger.error("deviceMgtServerUrl can't be empty "); log.error("deviceMgtServerUrl can't be empty ");
} }
return PropertyUtils.replaceProperty(deviceMgtServerUrl); return PropertyUtils.replaceProperty(deviceMgtServerUrl);
} }
@ -153,7 +158,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private String getTokenEndpoint(Map<String, String> globalProperties) throws OutputEventAdapterException { private String getTokenEndpoint(Map<String, String> globalProperties) throws OutputEventAdapterException {
String tokenEndpoint = globalProperties.get(TOKEN_ENDPOINT_CONTEXT); String tokenEndpoint = globalProperties.get(TOKEN_ENDPOINT_CONTEXT);
if ( tokenEndpoint.isEmpty()) { if ( tokenEndpoint.isEmpty()) {
logger.error("tokenEndpoint can't be empty "); log.error("tokenEndpoint can't be empty ");
} }
return PropertyUtils.replaceProperty(tokenEndpoint); return PropertyUtils.replaceProperty(tokenEndpoint);
} }
@ -163,7 +168,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
try { try {
refreshTimeOffset = Long.parseLong(globalProperties.get(TOKEN_REFRESH_TIME_OFFSET)); refreshTimeOffset = Long.parseLong(globalProperties.get(TOKEN_REFRESH_TIME_OFFSET));
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
logger.error("refreshTimeOffset should be a number", e); log.error("refreshTimeOffset should be a number", e);
} }
return refreshTimeOffset; return refreshTimeOffset;
} }
@ -198,7 +203,6 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
} catch (KeyManagementException | NoSuchAlgorithmException e) { } catch (KeyManagementException | NoSuchAlgorithmException e) {
return null; return null;
} }
} }
} }

@ -78,6 +78,10 @@
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>javax.cache.wso2</artifactId> <artifactId>javax.cache.wso2</artifactId>
</dependency> </dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -124,7 +128,8 @@
javax.xml.stream, javax.xml.stream,
org.wso2.carbon.base, org.wso2.carbon.base,
org.wso2.carbon.utils, org.wso2.carbon.utils,
javax.net.ssl javax.net.ssl,
feign.slf4j
</Import-Package> </Import-Package>
<Embed-Dependency> <Embed-Dependency>
jsr311-api, jsr311-api,

@ -21,9 +21,13 @@ package org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization;
import feign.Client; import feign.Client;
import feign.Feign; import feign.Feign;
import feign.FeignException; import feign.FeignException;
import feign.Logger;
import feign.Request;
import feign.Response;
import feign.gson.GsonDecoder; import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder; import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract; import feign.jaxrs.JAXRSContract;
import feign.slf4j.Slf4jLogger;
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.dna.mqtt.moquette.server.IAuthorizer; import org.dna.mqtt.moquette.server.IAuthorizer;
@ -44,7 +48,6 @@ import org.wso2.carbon.user.api.UserStoreException;
import javax.cache.Cache; import javax.cache.Cache;
import javax.cache.CacheConfiguration; import javax.cache.CacheConfiguration;
import javax.cache.CacheManager;
import javax.cache.Caching; import javax.cache.Caching;
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
@ -52,6 +55,7 @@ import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.ArrayList;
@ -67,7 +71,7 @@ import java.util.concurrent.TimeUnit;
public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer { public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer {
private static final String UI_EXECUTE = "ui.execute"; private static final String UI_EXECUTE = "ui.execute";
private static Log logger = LogFactory.getLog(DeviceAccessBasedMQTTAuthorizer.class); private static Log log = LogFactory.getLog(DeviceAccessBasedMQTTAuthorizer.class);
AuthorizationConfigurationManager MQTTAuthorizationConfiguration; AuthorizationConfigurationManager MQTTAuthorizationConfiguration;
private static final String CDMF_SERVER_BASE_CONTEXT = "/api/device-mgt/v1.0"; private static final String CDMF_SERVER_BASE_CONTEXT = "/api/device-mgt/v1.0";
private static final String CACHE_MANAGER_NAME = "mqttAuthorizationCacheManager"; private static final String CACHE_MANAGER_NAME = "mqttAuthorizationCacheManager";
@ -77,8 +81,8 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer {
public DeviceAccessBasedMQTTAuthorizer() { public DeviceAccessBasedMQTTAuthorizer() {
this.MQTTAuthorizationConfiguration = AuthorizationConfigurationManager.getInstance(); this.MQTTAuthorizationConfiguration = AuthorizationConfigurationManager.getInstance();
deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()) deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger())
.requestInterceptor(new OAuthRequestInterceptor()) .logLevel(Logger.Level.FULL).requestInterceptor(new OAuthRequestInterceptor())
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(DeviceAccessAuthorizationAdminService.class, .target(DeviceAccessAuthorizationAdminService.class,
MQTTAuthorizationConfiguration.getDeviceMgtServerUrl() + CDMF_SERVER_BASE_CONTEXT); MQTTAuthorizationConfiguration.getDeviceMgtServerUrl() + CDMF_SERVER_BASE_CONTEXT);
@ -117,7 +121,7 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer {
} }
return false; return false;
} catch (FeignException e) { } catch (FeignException e) {
logger.error(e.getMessage(), e); log.error(e.getMessage(), e);
return false; return false;
} }
} }
@ -160,7 +164,7 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer {
} }
} }
} catch (FeignException e) { } catch (FeignException e) {
logger.error(e.getMessage(), e); log.error(e.getMessage(), e);
} }
} finally { } finally {
PrivilegedCarbonContext.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
@ -204,7 +208,7 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer {
userRealm.getAuthorizationManager().isUserAuthorized(username, permission, action); userRealm.getAuthorizationManager().isUserAuthorized(username, permission, action);
} catch (UserStoreException e) { } catch (UserStoreException e) {
String errorMsg = String.format("Unable to authorize the user : %s", username); String errorMsg = String.format("Unable to authorize the user : %s", username);
logger.error(errorMsg, e); log.error(errorMsg, e);
return false; return false;
} finally { } finally {
PrivilegedCarbonContext.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
@ -263,7 +267,6 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer {
} catch (KeyManagementException | NoSuchAlgorithmException e) { } catch (KeyManagementException | NoSuchAlgorithmException e) {
return null; return null;
} }
} }
} }

@ -16,14 +16,20 @@ package org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client;
import feign.Client; import feign.Client;
import feign.Feign; import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.RequestInterceptor; import feign.RequestInterceptor;
import feign.RequestTemplate; import feign.RequestTemplate;
import feign.Response;
import feign.auth.BasicAuthRequestInterceptor; import feign.auth.BasicAuthRequestInterceptor;
import feign.codec.EncodeException; import feign.codec.EncodeException;
import feign.codec.Encoder; import feign.codec.Encoder;
import feign.gson.GsonDecoder; import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder; import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract; import feign.jaxrs.JAXRSContract;
import feign.slf4j.Slf4jLogger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client.dto.AccessTokenInfo; import org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client.dto.AccessTokenInfo;
import org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client.dto.ApiApplicationKey; import org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client.dto.ApiApplicationKey;
import org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client.dto.ApiApplicationRegistrationService; import org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client.dto.ApiApplicationRegistrationService;
@ -37,6 +43,7 @@ import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@ -55,6 +62,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private static final String REQUIRED_SCOPE = "perm:authorization:verify"; private static final String REQUIRED_SCOPE = "perm:authorization:verify";
private ApiApplicationRegistrationService apiApplicationRegistrationService; private ApiApplicationRegistrationService apiApplicationRegistrationService;
private TokenIssuerService tokenIssuerService; private TokenIssuerService tokenIssuerService;
private static Log log = LogFactory.getLog(OAuthRequestInterceptor.class);
/** /**
* Creates an interceptor that authenticates all requests. * Creates an interceptor that authenticates all requests.
@ -63,8 +71,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
refreshTimeOffset = AuthorizationConfigurationManager.getInstance().getTokenRefreshTimeOffset() * 1000; refreshTimeOffset = AuthorizationConfigurationManager.getInstance().getTokenRefreshTimeOffset() * 1000;
String username = AuthorizationConfigurationManager.getInstance().getUsername(); String username = AuthorizationConfigurationManager.getInstance().getUsername();
String password = AuthorizationConfigurationManager.getInstance().getPassword(); String password = AuthorizationConfigurationManager.getInstance().getPassword();
apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).requestInterceptor( apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()).logLevel(
new BasicAuthRequestInterceptor(username, password)) Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password))
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(ApiApplicationRegistrationService.class, .target(ApiApplicationRegistrationService.class,
AuthorizationConfigurationManager.getInstance().getDeviceMgtServerUrl() + AuthorizationConfigurationManager.getInstance().getDeviceMgtServerUrl() +
@ -85,8 +93,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
String consumerSecret = apiApplicationKey.getConsumerSecret(); String consumerSecret = apiApplicationKey.getConsumerSecret();
String username = AuthorizationConfigurationManager.getInstance().getUsername(); String username = AuthorizationConfigurationManager.getInstance().getUsername();
String password = AuthorizationConfigurationManager.getInstance().getPassword(); String password = AuthorizationConfigurationManager.getInstance().getPassword();
tokenIssuerService = Feign.builder().client(getSSLClient()).requestInterceptor( tokenIssuerService = Feign.builder().client(getSSLClient()).logger(new Slf4jLogger()).logLevel(Logger.Level.FULL)
new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) .requestInterceptor(new BasicAuthRequestInterceptor(consumerKey, consumerSecret))
.contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder())
.target(TokenIssuerService.class, .target(TokenIssuerService.class,
AuthorizationConfigurationManager.getInstance().getTokenEndpoint()); AuthorizationConfigurationManager.getInstance().getTokenEndpoint());
@ -133,7 +141,6 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
} catch (KeyManagementException | NoSuchAlgorithmException e) { } catch (KeyManagementException | NoSuchAlgorithmException e) {
return null; return null;
} }
} }
} }

@ -20,15 +20,14 @@ package org.wso2.carbon.mdm.services.android.services.impl;
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.Device; import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
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.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
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.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.mdm.services.android.bean.ErrorResponse; import org.wso2.carbon.mdm.services.android.bean.ErrorResponse;
import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidApplication; import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidApplication;
import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidDevice; import org.wso2.carbon.mdm.services.android.bean.wrapper.AndroidDevice;
@ -219,7 +218,25 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
device.setProperties(androidDevice.getProperties()); device.setProperties(androidDevice.getProperties());
boolean status = AndroidAPIUtils.getDeviceManagementService().enrollDevice(device); boolean status = AndroidAPIUtils.getDeviceManagementService().enrollDevice(device);
if (status) {
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(new DeviceIdentifier(androidDevice.getDeviceIdentifier(), device.getType()));
List<String> taskOperaions = new ArrayList<>();
taskOperaions.add(AndroidConstants.OperationCodes.APPLICATION_LIST);
taskOperaions.add(AndroidConstants.OperationCodes.DEVICE_INFO);
taskOperaions.add(AndroidConstants.OperationCodes.DEVICE_LOCATION);
for (String str : taskOperaions) {
CommandOperation operation = new CommandOperation();
operation.setEnabled(true);
operation.setType(Operation.Type.COMMAND);
operation.setCode(str);
AndroidAPIUtils.getDeviceManagementService().
addOperation(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID,
operation, deviceIdentifiers);
}
}
PolicyManagerService policyManagerService = AndroidAPIUtils.getPolicyManagerService(); PolicyManagerService policyManagerService = AndroidAPIUtils.getPolicyManagerService();
policyManagerService.getEffectivePolicy(new DeviceIdentifier(androidDevice.getDeviceIdentifier(), device.getType())); policyManagerService.getEffectivePolicy(new DeviceIdentifier(androidDevice.getDeviceIdentifier(), device.getType()));
if (status) { if (status) {
@ -249,6 +266,20 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
log.error(msg, e); log.error(msg, e);
throw new UnexpectedServerErrorException( throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build()); new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} catch (OperationManagementException e) {
String msg = "Error occurred while enforcing default enrollment policy upon android " +
"', which carries the id '" +
androidDevice.getDeviceIdentifier() + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} catch (InvalidDeviceException e) {
String msg = "Error occurred while enforcing default enrollment policy upon android " +
"', which carries the id '" +
androidDevice.getDeviceIdentifier() + "'";
log.error(msg, e);
throw new UnexpectedServerErrorException(
new ErrorResponse.ErrorResponseBuilder().setCode(500l).setMessage(msg).build());
} }
} }

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project name="create-geo-fence-capps" default="zip" basedir=".">
<property name="project-name" value="${ant.project.name}"/>
<property name="target-dir" value="target/"/>
<property name="src-dir" value="src/main/resources/android-tryit"/>
<target name="clean">
<delete dir="${target-dir}" />
</target>
<target name="zip" depends="clean">
<zip destfile="${target-dir}/android-tryit.ZIP">
<zipfileset dir="src/main/resources/jaggeryapps/android-web-agent/app/pages/mdm.page.enrollments.android.download-agent/public/asset/" includes="android-agent.apk" fullpath="resources/android-agent.apk"/>
<zipfileset dir="${src-dir}"/>
</zip>
</target>
</project>

@ -35,6 +35,23 @@
<build> <build>
<plugins> <plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>${maven-antrun-plugin.version}</version>
<executions>
<execution>
<phase>process-resources</phase>
<configuration>
<target>
<ant antfile="build.xml" target="zip" />
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin> <plugin>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version> <version>2.5.5</version>

@ -43,4 +43,13 @@
<useDefaultExcludes>true</useDefaultExcludes> <useDefaultExcludes>true</useDefaultExcludes>
</fileSet> </fileSet>
</fileSets> </fileSets>
<files>
<file>
<source>
${basedir}/target/android-tryit.ZIP
</source>
<outputDirectory>/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/assets/</outputDirectory>
<fileMode>755</fileMode>
</file>
</files>
</assembly> </assembly>

@ -0,0 +1,21 @@
Prerequisites
===============
1. You should have curl in your computer.
2. Java 7 or higher.
Instructions
=================
1. Run 'start' script in your terminal.
2. If you already have android sdk in your computer, please provide location of the sdk.
Otherwise this tool will download and install minimum SDK components which needs to run the emulator.
This is a one time process.
3. This tool will ask to create AVD if you don't have any in your computer.
Otherwise you can select existing AVD to try out IoT Agent.
Troubleshooting
==================
1. If your exisitng SDK doen't work or giving any errors, delete 'sdklocation' file and try agin without selecting the existing SDK path.
2. If your emulator does not start correctly, please remove all files and directories in $HOME/.android/avd/ directory. Then try again with a new emulator.

@ -0,0 +1,29 @@
avd.ini.encoding=UTF-8
abi.type=x86
disk.dataPartition.size=200M
hw.accelerometer=yes
hw.audioInput=yes
hw.battery=yes
hw.camera.back=none
hw.camera.front=none
hw.cpu.arch=x86
hw.dPad=no
hw.device.hash2=MD5:6930e145748b87e87d3f40cabd140a41
hw.device.manufacturer=Google
hw.device.name=Galaxy Nexus
hw.gps=yes
hw.keyboard=yes
hw.lcd.density=320
hw.mainKeys=no
hw.ramSize=1024
hw.sdCard=no
hw.sensors.orientation=yes
hw.sensors.proximity=yes
hw.trackBall=no
image.sysdir.1=system-images/android-23/default/x86/
skin.dynamic=no
skin.name=720x1280
skin.path=720x1280
tag.display=Default
tag.id=default
vm.heapSize=64

@ -0,0 +1,244 @@
#!/bin/bash
#Make sure we have got everything we need
command -v curl >/dev/null || { echo "curl is not installed. Aborting." >&2; exit 1; }
command -v unzip >/dev/null || { echo "unzip is not installed. Aborting." >&2; exit 1; }
SCRIPT_HOME=$PWD
OS_SUFFIX="linux"
if [[ "$OSTYPE" == "darwin"* ]]; then
OS_SUFFIX="macosx"
fi
downloadArtifacts() {
curl -D headers -O $1
httpStatus=$(head -1 headers | awk '{print $2}')
[ "$httpStatus" != "200" ] && { echo "Download failed. Aborting." ; exit 1 ;}
rm headers
echo
}
setSDKPath () {
echo -n "Please provide Android SDK location (ex: /mnt/tools/android-sdk):"
read answer
emulator="$answer/tools/emulator"
if [ -f "$emulator" ]; then
echo "$answer" > sdklocation
else
echo "Invalid SDK location"
setSDKPath
fi
}
getAndroidSDK() {
echo
echo "Downloading Android SDK tools..."
mkdir android-sdk
cd android-sdk
downloadArtifacts "https://dl.google.com/android/repository/tools_r25.2.5-$OS_SUFFIX.zip"
echo -n "Configuring Android SDK tools..."
unzip -q tools_r25.2.5-$OS_SUFFIX.zip
rm tools_r25.2.5-$OS_SUFFIX.zip
echo " Done!"
echo
echo "Downloading Android platform tools..."
downloadArtifacts "http://dl.google.com/android/repository/platform-tools_r25.0.3-$OS_SUFFIX.zip"
echo -n "Configuring Android platform tools..."
unzip -q platform-tools_r25.0.3-$OS_SUFFIX.zip
rm platform-tools_r25.0.3-$OS_SUFFIX.zip
cd ..
echo "$PWD/android-sdk" > sdklocation
echo " Done!"
}
createAVD() {
if [ ! -d "$ANDROID_TRYIT_SDK_HOME/platforms/android-23" ]; then
echo
echo "Downloading Android platform..."
cd $ANDROID_TRYIT_SDK_HOME
downloadArtifacts "https://dl.google.com/android/repository/platform-23_r03.zip"
echo -n "Configuring Android platform..."
unzip -q platform-23_r03.zip
mkdir -p platforms/android-23
mv android-6.0/* platforms/android-23/
rm -r android-6.0
rm platform-23_r03.zip
cd ..
echo " Done!"
fi
if [ ! -d "$ANDROID_TRYIT_SDK_HOME/system-images/android-23/default" ]; then
echo "Downloading Android system image..."
cd $ANDROID_TRYIT_SDK_HOME
downloadArtifacts "https://dl.google.com/android/repository/sys-img/android/x86-23_r09.zip"
echo -n "Configuring Android system image..."
unzip -q x86-23_r09.zip
mkdir -p system-images/android-23/default
mv x86 system-images/android-23/default
rm x86-23_r09.zip
cd ..
echo " Done!"
fi
echo "Creating a new AVD device"
if [ -f "$ANDROID_TRYIT_SDK_HOME/tools/bin/avdmanager" ]; then
$ANDROID_TRYIT_SDK_HOME/tools/bin/avdmanager create avd -k 'system-images;android-23;default;x86' -n WSO2_AVD
else
$ANDROID_TRYIT_SDK_HOME/tools/android create avd -n WSO2_AVD -t android-23
fi
rm $HOME/.android/avd/WSO2_AVD.avd/config.ini
cp $SCRIPT_HOME/resources/config.ini $HOME/.android/avd/WSO2_AVD.avd/
startAVD
}
startAVD() {
if [ ! -d "$HOME/.android/avd/WSO2_AVD.avd" ]; then
echo -n "Looks you don't have the WSO2_AVD. Do you want to create WSO2_AVD with default configs (Y/n)?: "
read answer
if ! echo "$answer" | grep -iq "^n" ;then
createAVD
return
fi
fi
echo
echo "------------------------------"
echo "Available AVDs in the system:"
echo "------------------------------"
devices=()
count=0
if [ ! -f "mypipe" ]; then
mkfifo mypipe
fi
$ANDROID_TRYIT_SDK_HOME/tools/emulator -list-avds > mypipe &
while IFS= read -r line
do
let count++
echo "$count) $line"
devices+=($line)
done < mypipe
rm mypipe
echo "------------------------------"
echo
if [ $count = 0 ]; then
echo -n "No AVDs found on your system. Do you want to create new AVD (Y/n)?: "
read answer
if echo "$answer" | grep -iq "^n" ;then
exit;
else
createAVD
fi
elif [ $count = 1 ]; then
runEmulator ${devices[0]}
else
echo -n "Enter AVD number to start (eg: 1): "
read answer
let answer--
runEmulator ${devices[$answer]}
fi
}
runEmulator(){
if [ $OS_SUFFIX = "macosx" -a ! -d $ANDROID_TRYIT_SDK_HOME/extras/intel/Hardware_Accelerated_Execution_Manager ]; then
cd $ANDROID_TRYIT_SDK_HOME
echo "Downloading intel HAXM..."
mkdir -p extras/intel/Hardware_Accelerated_Execution_Manager
cd extras/intel/Hardware_Accelerated_Execution_Manager
downloadArtifacts "https://dl.google.com/android/repository/extras/intel/haxm-macosx_r6_0_5.zip"
echo -n "Configuring HAXM..."
unzip -q haxm-macosx_r6_0_5.zip
rm haxm-macosx_r6_0_5.zip
./"HAXM installation" -m 2048 -log $SCRIPT_HOME/haxm_silent_run.log
echo " Done!"
echo "Please restart your computer and run this script again."
exit
fi
cd $SCRIPT_HOME
$ANDROID_TRYIT_SDK_HOME/platform-tools/adb kill-server
echo "Starting AVD $1"
$ANDROID_TRYIT_SDK_HOME/tools/emulator -avd $1 > emulator.log &
while [ ! -f "$HOME/.android/avd/$1.avd/cache.img" ]
do
sleep 1
echo -n "."
done
count=0
while [ $count -lt 5 ]
do
sleep 1
echo -n "."
let count++
done
echo
}
echo "+----------------------------------------------------------------+"
echo "| WSO2 Android Tryit |"
echo "+----------------------------------------------------------------+"
echo "Detected OS: " $OSTYPE
if [ ! -f "sdklocation" ]; then
echo -n "Do you have an Android SDK installed on your computer (y/N)?: "
read answer
if echo "$answer" | grep -iq "^y" ;then
setSDKPath
else
getAndroidSDK
fi
fi
export ANDROID_TRYIT_SDK_HOME=$(<sdklocation)
if [ ! -d "$ANDROID_TRYIT_SDK_HOME/build-tools/25.0.2" ]; then
echo
echo "Downloading Android build tools..."
cd $ANDROID_TRYIT_SDK_HOME
downloadArtifacts "https://dl.google.com/android/repository/build-tools_r25.0.2-$OS_SUFFIX.zip"
echo -n "Configuring Android build tools..."
unzip -q build-tools_r25.0.2-$OS_SUFFIX.zip
mkdir -p build-tools/25.0.2
mv android-7.1.1/* build-tools/25.0.2/
rm -r android-7.1.1
rm build-tools_r25.0.2-$OS_SUFFIX.zip
echo " Done!"
fi
startAVD
while [ "`$ANDROID_TRYIT_SDK_HOME/platform-tools/adb shell getprop sys.boot_completed | tr -d '\r' `" != "1" ] ; do sleep 1; done
echo "AVD Started!"
sleep 1
if [ ! -f "mypipe" ]; then
mkfifo mypipe
fi
app=$SCRIPT_HOME/resources/android-agent.apk
pkg=$($ANDROID_TRYIT_SDK_HOME/build-tools/25.0.2/aapt dump badging $app|awk -F" " '/package/ {print $2}'|awk -F"'" '/name=/ {print $2}')
act=$($ANDROID_TRYIT_SDK_HOME/build-tools/25.0.2/aapt dump badging $app|awk -F" " '/launchable-activity/ {print $2}'|awk -F"'" '/name=/ {print $2}')
hasAgent=false
$ANDROID_TRYIT_SDK_HOME/platform-tools/adb shell pm list packages > mypipe &
while IFS= read -r line
do
if [ $line = "package:$pkg" ]; then
let hasAgent=true
fi
done < mypipe
rm mypipe
if [ $hasAgent = false ]; then
echo
echo "Installing agent..."
cd $SCRIPT_HOME/resources
$ANDROID_TRYIT_SDK_HOME/platform-tools/adb install android-agent.apk
fi
echo
echo "Staring agent..."
$ANDROID_TRYIT_SDK_HOME/platform-tools/adb shell am start -n $pkg/$act
echo
echo "Connected to device shell"
$ANDROID_TRYIT_SDK_HOME/platform-tools/adb shell
echo
echo "Good bye!"

@ -35,7 +35,6 @@ var InitiateViewOption = null;
serviceUrl = "/api/device-mgt/android/v1.0/admin/devices/info"; serviceUrl = "/api/device-mgt/android/v1.0/admin/devices/info";
serviceUrlLocal = "/api/device-mgt/android/v1.0/admin/devices/location"; serviceUrlLocal = "/api/device-mgt/android/v1.0/admin/devices/location";
} }
if (serviceUrl) { if (serviceUrl) {
invokerUtil.post( invokerUtil.post(
serviceUrl, serviceUrl,
@ -51,8 +50,6 @@ var InitiateViewOption = null;
$(".panel-body").append(defaultInnerHTML); $(".panel-body").append(defaultInnerHTML);
} }
); );
invokerUtil.post( invokerUtil.post(
serviceUrlLocal, serviceUrlLocal,
payload, payload,
@ -70,7 +67,6 @@ var InitiateViewOption = null;
} }
$(".media.tab-responsive [data-toggle=tab]").on("shown.bs.tab", function (e) { $(".media.tab-responsive [data-toggle=tab]").on("shown.bs.tab", function (e) {
var activeTabPane = $(e.target).attr("href"); var activeTabPane = $(e.target).attr("href");
var activeListGroupItem = $(".media .list-group-item.active"); var activeListGroupItem = $(".media .list-group-item.active");

@ -113,11 +113,6 @@
</div> </div>
{{/each}} {{/each}}
</div> </div>
{{else}}
<div align="center">
<h4 style="color: #D8000C"><i class="icon fw fw-error" style="color: #D8000C"></i>
Operations Loading Failed!</h4>
</div>
{{/if}} {{/if}}
<div id="operation-response-template" style="display: none"> <div id="operation-response-template" style="display: none">

@ -31,8 +31,8 @@ function onRequest(context) {
var pathParams = []; var pathParams = [];
for (var i = 0; i < allControlOps.length; i++) { for (var i = 0; i < allControlOps.length; i++) {
var controlOperation = {}; var controlOperation = {};
var uiPermission = allControlOps[i]["uiPermission"]; var uiPermission = allControlOps[i]["permission"];
if (uiPermission && !userModule.isAuthorized("/permission/admin/" + uiPermission)) { if (uiPermission && !userModule.isAuthorized("/permission/admin" + uiPermission)) {
continue; continue;
} }
controlOperation = allControlOps[i]; controlOperation = allControlOps[i];

@ -1,7 +1,8 @@
{ {
"deviceType": { "deviceType": {
"label": "Android", "label": "Android",
"category": "mobile", "virtualLabel": "virtual Android",
"category": "hybrid",
"analyticsEnabled": "false", "analyticsEnabled": "false",
"groupingEnabled": "false", "groupingEnabled": "false",
"scopes" : [ "scopes" : [

@ -59,5 +59,11 @@ hr {
color: #006eff; color: #006eff;
} }
.enrollment-qr-container canvas { .enrollment-qr-container canvas {
width: 24%; width: 14%;
}
@media (min-width:992px){
.add-min-height {
min-height: 115px;
}
} }

@ -378,7 +378,7 @@ $(document).ready(function () {
// on error // on error
function () { function () {
var content = "<li class='message message-danger'><h4><i class='icon fw fw-error'></i>Warning</h4>" + var content = "<li class='message message-danger'><h4><i class='icon fw fw-error'></i>Warning</h4>" +
"<p>Unexpected error occurred while loading notification. Please refresh the page and" + "<p>Unexpected error occurred while loading notification. Please refresh the pa{{#if isCloud}}ge and" +
" try again</p></li>"; " try again</p></li>";
$(messageSideBar).html(content); $(messageSideBar).html(content);
} }

@ -4,7 +4,11 @@
<div class="row"> <div class="row">
<div class="col-lg-12"> <div class="col-lg-12">
{{#if isVirtual}}
<h1 class="grey ">DOWNLOAD THE VIRTUAL ANDROID DEVICE</h1>
{{else}}
<h1 class="grey ">DOWNLOAD THE ANDROID AGENT</h1> <h1 class="grey ">DOWNLOAD THE ANDROID AGENT</h1>
{{/if}}
<hr> <hr>
</div> </div>
</div> </div>
@ -13,15 +17,34 @@
<!--<div class="col-xs-12 col-sm-4 col-md-3 col-lg-3 add-padding-top-2x"> <!--<div class="col-xs-12 col-sm-4 col-md-3 col-lg-3 add-padding-top-2x">
<img src="{{@unit.publicUri}}/images/android-icon.png" class="img-responsive"> <img src="{{@unit.publicUri}}/images/android-icon.png" class="img-responsive">
</div>--> </div>-->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 add-padding-top-2x"> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 add-padding-top-2x add-padding-bottom-2x">
<h3 class="text-center">Scan to download the Android Agent.</h3> {{#if isVirtual}}
<h3 class="text-center add-padding-bottom-4x">Download our Android-try-it emulator, enroll it with WSO2 Device Cloud and try it out!</h3>
<div class="text-center"><a
href="{{@unit.publicUri}}/assets/android-tryit.ZIP"
class="btn-operations remove-margin download_agent">
<i class="fw fw-download fw-inverse fw-lg add-margin-1x"></i>Download the android-try-it Emulator</a></div>
{{else}}
<h3 class="text-center">Scan to get the Android Agent.</h3>
<div class="enrollment-qr-container text-center"></div> <div class="enrollment-qr-container text-center"></div>
<h3 class="text-center add-margin-bottom-2x add-margin-top-2x">or</h3> <h3 class="text-center add-margin-bottom-2x add-margin-top-2x">or</h3>
<div class="text-center"><a {{#if isCloud}}
href="{{host}}/android-web-agent/public/mdm.page.enrollments.android.download-agent/asset/android-agent.apk" <div class="text-center">
<a href='https://play.google.com/store/apps/details?id=org.wso2.iot.agent&pcampaignid=MKT-Other-global-all-co-prtnr-py-PartBadge-Mar2515-1'
target="_blank">
<img alt='Get it on Google Play'
src='{{@unit.publicUri}}/images/en_badge_web_generic_export.png'/>
</a>
</div>
{{else}}
<div class="text-center">
<a href="{{host}}/android-web-agent/public/mdm.page.enrollments.android.download-agent/asset/android-agent.apk"
class="btn-operations remove-margin download_agent"> class="btn-operations remove-margin download_agent">
<i class="fw fw-download fw-inverse fw-lg add-margin-1x"></i> Download APK</a></div> <i class="fw fw-download fw-inverse fw-lg add-margin-1x"></i> Download APK</a>
</div>
{{/if}}
{{/if}}
</div>
<!--<p class="doc-link">Please scan the QR code to download the APK on to your android device or click <!--<p class="doc-link">Please scan the QR code to download the APK on to your android device or click
<a href="{{host}}/android-web-agent/public/mdm.page.enrollments.android.download-agent/asset/android-agent.apk">here</a> <a href="{{host}}/android-web-agent/public/mdm.page.enrollments.android.download-agent/asset/android-agent.apk">here</a>
to save it to your computer.</p> to save it to your computer.</p>
@ -29,51 +52,121 @@
target="_blank">link</a>.</p>--> target="_blank">link</a>.</p>-->
{{#if isCloud}} {{#if isCloud}}
<p class="doc-link text-center">Need help? Read <a <p class="doc-link text-center">Need help? Read <a
href="https://docs.wso2.com/display/IoTS300/Android" target="_blank">WSO2 Device {{#if isVirtual}}
Cloud documentation.</a></p> href="https://docs.wso2.com/display/DeviceCloud/Quick+Start+Guide"
{{else}}
href="https://docs.wso2.com/display/DeviceCloud/Enrolling+an+Android+Device"
{{/if}}
target="_blank">WSO2 Device Cloud documentation.</a>
</p>
{{else}} {{else}}
<p class="doc-link text-center">Need help? Read <a <p class="doc-link text-center">Need help? Read <a
href="https://docs.wso2.com/display/DeviceCloud/Enrolling+an+Android+Device" target="_blank">WSO2 href="https://docs.wso2.com/display/IoTS310/Android" target="_blank">WSO2
IoT Server documentation.</a></p> IoT Server documentation.</a></p>
{{/if}} {{/if}}
</div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-xs-12 col-sm-12 col-md-8 col-lg-12 add-padding-top-2x "> <div class="col-xs-12 col-sm-12 col-md-8 col-lg-12 add-padding-top-2x ">
{{#if isVirtual}}
<h3 class="uppercase">TRY OUT THE VIRTUAL ANDROID DEVICE</h3>
{{else}}
<h3 class="uppercase">START ENROLLING YOUR DEVICE</h3> <h3 class="uppercase">START ENROLLING YOUR DEVICE</h3>
{{/if}}
<hr> <hr>
</div> </div>
</div> </div>
{{#if isCloud}} {{#if isCloud}}
<div class="row grey-bg"> <div class="row grey-bg">
{{#if isVirtual}}
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-4 col-md-offset-1 col-lg-offset-1 add-padding-top-2x add-padding-bottom-2x"> <div class="col-xs-12 col-sm-6 col-md-3 col-lg-4 col-md-offset-1 col-lg-offset-1 add-padding-top-2x add-padding-bottom-2x">
<h5><strong>Step 1</strong></h5> <h5><strong>Step 1</strong></h5>
<p>Let's start by installing the Android agent on your device. Open the downloaded file, and tap <div class="add-min-height">
<b>INSTALL</b>.</p> <ol>
<img src="{{@unit.publicUri}}/images/install_agent.png" class="img-responsive"> <li>Unzip the 'android-tryit.zip file and run the 'start' script on your terminal.</li>
<li>Download and install the Android SDK.
<ul>
<li>If you already have an Android SDK on your computer, please provide the location of
the SDK.
</li>
<li>Else, this tool will download and install the minimum SDK components required to run
the emulator.
This is a one-time process.
</li>
</ul>
</li>
<li>Next, you will be asked to create an AVD:
<ul>
<li>If you don't have one, the WSO2_AVD will be created for you.</li>
<li>Else, you can use an existing AVD to try out IoT Android agent.</li>
</ul>
</li>
</ol>
</div>
<img src="{{@unit.publicUri}}/images/android-tryit.png" class="img-responsive">
</div>
{{else}}
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3 col-md-offset-1 col-lg-offset-1 add-padding-top-2x add-padding-bottom-2x">
<h5><strong>Step 1</strong></h5>
<div class="add-min-height">
<p>Let's start by opening the Android agent on your device.
<br/>Tap on <b>WSO2 Device Management Agent</b>.
</p>
</div> </div>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-4 col-md-offset-2 col-lg-offset-2 add-padding-top-2x add-padding-bottom-2x"> <img src="{{@unit.publicUri}}/images/launch_agent.png" class="img-responsive">
</div>
{{/if}}
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2 col-md-offset-1 col-lg-offset-1 add-padding-top-2x add-padding-bottom-2x">
<h5><strong>Step 2</strong></h5> <h5><strong>Step 2</strong></h5>
<div class="add-min-height">
<p>Enter your: <p>Enter your:
<p> <p>
<ul> <ul>
<li>Username: username/email that you used to sign in.</li> <li>Organization: <b>{{@user.domain}}</b></li>
<li>Password: the WSO2 Cloud password.</li> <li>Username: <b>{{@user.username}}</b></li>
<li>Organization: the name of the organization.</li> <li>Password: <i>Your Cloud password.</i></li>
</ul> </ul>
<img src="{{@unit.publicUri}}/images/login.png" class="img-responsive"> </div>
<img src="{{@unit.publicUri}}/images/register.png" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-2 col-md-offset-1 col-lg-offset-1 add-padding-top-2x add-padding-bottom-2x">
<h5><strong>Step 3</strong></h5>
<div class="add-min-height">
<p>To successfully register the virtual device,</p>
<ul>
<li>Tap <b>ALLOW</b> to provide the necessary permissions.</li>
<li>Tap <b>ACTIVATE</b> to enable the device administrator.</li>
</ul>
</div>
</div> </div>
{{else}} {{else}}
<div class="row grey-bg"> <div class="row grey-bg">
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3 add-padding-top-2x add-padding-bottom-2x"> <div class="col-xs-12 col-sm-6 col-md-3 col-lg-3 add-padding-top-2x add-padding-bottom-2x">
<h5><strong>Step 1</strong></h5> <h5><strong>Step 1</strong></h5>
{{#if isVirtual}}
<ol>
<li>Unzip the 'android-tryit.zip file and run the 'start' script on your terminal.</li>
<li>Download and install the Android SDK.
<ul>
<li>If you already have an Android SDK on your computer, please provide the location of the SDK.</li>
<li>Else, this tool will download and install the minimum SDK components required to run the emulator.
This is a one-time process.</li>
</ul>
</li>
<li>Next, you will be asked to create an AVD:
<ul>
<li>If you don't have one, the WSO2_AVD will be created for you.</li>
<li>Else, you can use an existing AVD to try out IoT Android agent.</li>
</ul>
</li>
</ol>
<img src="{{@unit.publicUri}}/images/android-tryit.png" class="img-responsive">
{{else}}
<p>Let's start by installing the Android agent on your device. Open the downloaded file, and tap <p>Let's start by installing the Android agent on your device. Open the downloaded file, and tap
<b>INSTALL</b>.</p> <b>INSTALL</b>.</p>
<img src="{{@unit.publicUri}}/images/install_agent.png" class="img-responsive"> <img src="{{@unit.publicUri}}/images/install_agent.png" class="img-responsive">
{{/if}}
</div> </div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3 add-padding-top-2x add-padding-bottom-2x"> <div class="col-xs-12 col-sm-6 col-md-3 col-lg-3 add-padding-top-2x add-padding-bottom-2x">
@ -91,11 +184,11 @@
<p>Enter your: <p>Enter your:
<p> <p>
<ul> <ul>
<li>Username: username/email that you used to sign in to IoT server.</li> <li>Organization: <b>{{@user.domain}}</b></li>
<li>Password: the WSO2 Iot server password.</li> <li>Username: <b>{{@user.username}}</b></li>
<li>Domain: the name of the domain.</li> <li>Password: <i>Your password.</i></li>
</ul> </ul>
<img src="{{@unit.publicUri}}/images/install_agent.png" class="img-responsive"> <img src="{{@unit.publicUri}}/images/register.png" class="img-responsive">
</div> </div>
{{/if}} {{/if}}
@ -158,8 +251,6 @@
</center> </center>
</div>--> </div>-->
<br/>
{{#zone "topCss"}} {{#zone "topCss"}}
{{css "css/styles.css"}} {{css "css/styles.css"}}
{{/zone}} {{/zone}}

@ -16,7 +16,7 @@
* under the License. * under the License.
*/ */
function onRequest(context){ function onRequest(context) {
var viewModel = {}; var viewModel = {};
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
//uncomment this to enable analytics artifact deployment //uncomment this to enable analytics artifact deployment
@ -34,8 +34,14 @@ function onRequest(context){
// //do nothing. // //do nothing.
// } // }
//); //);
viewModel["isCloud"] = devicemgtProps["isCloud"]; var isCloud = devicemgtProps["isCloud"];
viewModel["isVirtual"] = request.getParameter("type") == 'virtual';
viewModel["isCloud"] = isCloud;
viewModel["hostName"] = devicemgtProps["httpsURL"]; viewModel["hostName"] = devicemgtProps["httpsURL"];
if (isCloud) {
viewModel["enrollmentURL"] = "https://play.google.com/store/apps/details?id=org.wso2.iot.agent";
} else {
viewModel["enrollmentURL"] = devicemgtProps["generalConfig"]["host"] + devicemgtProps["androidEnrollmentDir"]; viewModel["enrollmentURL"] = devicemgtProps["generalConfig"]["host"] + devicemgtProps["androidEnrollmentDir"];
}
return viewModel; return viewModel;
} }

@ -80,6 +80,9 @@
<bundleDef> <bundleDef>
io.github.openfeign:feign-gson:${io.github.openfeign.version} io.github.openfeign:feign-gson:${io.github.openfeign.version}
</bundleDef> </bundleDef>
<bundleDef>
io.github.openfeign:feign-slf4j:${io.github.openfeign.version}
</bundleDef>
</bundles> </bundles>
<importFeatures> <importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}</importFeatureDef> <importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}</importFeatureDef>

@ -198,6 +198,9 @@
<bundleDef> <bundleDef>
io.github.openfeign:feign-core:${io.github.openfeign.version} io.github.openfeign:feign-core:${io.github.openfeign.version}
</bundleDef> </bundleDef>
<bundleDef>
io.github.openfeign:feign-slf4j:${io.github.openfeign.version}
</bundleDef>
<bundleDef> <bundleDef>
io.github.openfeign:feign-gson:${io.github.openfeign.version} io.github.openfeign:feign-gson:${io.github.openfeign.version}
</bundleDef> </bundleDef>

@ -1072,6 +1072,11 @@
<artifactId>feign-gson</artifactId> <artifactId>feign-gson</artifactId>
<version>${io.github.openfeign.version}</version> <version>${io.github.openfeign.version}</version>
</dependency> </dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-slf4j</artifactId>
<version>${io.github.openfeign.version}</version>
</dependency>
<!-- dependencies for siddhi extension --> <!-- dependencies for siddhi extension -->
<dependency> <dependency>

Loading…
Cancel
Save