From eda471021111a070f7df141bc30beb0308b3d81f Mon Sep 17 00:00:00 2001 From: ayyoob Date: Thu, 2 Mar 2017 00:32:39 +0530 Subject: [PATCH 1/8] resolved device type download issue in windows OS and added log support for service clients. --- .../sense/util/SenseClientAsyncExecutor.java | 3 +- .../sense/util/dto/TokenIssuerService.java | 2 +- .../service/impl/ArduinoServiceImpl.java | 6 +- .../arduino/service/impl/util/ZipArchive.java | 10 +- .../arduino/service/impl/util/ZipUtil.java | 196 +++++++---------- .../service/impl/RaspberryPiServiceImpl.java | 6 +- .../service/impl/util/ZipArchive.java | 12 +- .../service/impl/util/ZipUtil.java | 201 +++++++---------- .../pom.xml | 12 - .../impl/VirtualFireAlarmServiceImpl.java | 10 +- .../service/impl/util/ZipArchive.java | 12 +- .../service/impl/util/ZipUtil.java | 207 +++++++----------- .../service/impl/util/util/Utils.java | 61 ------ .../ApplicationOperationsImpl.java | 38 +++- .../client/OAuthRequestInterceptor.java | 43 +++- .../http/authorization/DeviceAuthorizer.java | 44 +++- .../client/OAuthRequestInterceptor.java | 52 ++++- .../authorization/DeviceAuthorizer.java | 42 +++- .../client/OAuthRequestInterceptor.java | 52 ++++- .../DeviceAccessBasedMQTTAuthorizer.java | 43 +++- .../client/OAuthRequestInterceptor.java | 41 +++- 21 files changed, 570 insertions(+), 523 deletions(-) delete mode 100644 components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/util/Utils.java diff --git a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/util/SenseClientAsyncExecutor.java b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/util/SenseClientAsyncExecutor.java index 6b1591ce9..fbfa0c014 100755 --- a/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/util/SenseClientAsyncExecutor.java +++ b/components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.agent/app/src/main/java/org/wso2/carbon/iot/android/sense/util/SenseClientAsyncExecutor.java @@ -118,7 +118,8 @@ public class SenseClientAsyncExecutor extends AsyncTask> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties"); List templateFiles = properties.get("templates"); + List processTemplateFiles = new ArrayList<>(); for (String templateFile : templateFiles) { - parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath + File.separator + templateFile, - contextParams); + TemplateFile tFile = new TemplateFile(); + tFile.setContent(parseTemplate(templateSketchPath + File.separator + templateFile, contextParams)); + tFile.setFileName(templateFile); + processTemplateFiles.add(tFile); } templateFiles.add("sketch.properties"); // ommit copying the props file - copyFolder(new File(sketchPath), new File(archivesPath), templateFiles); - createZipArchive(archivesPath); - FileUtils.deleteDirectory(new File(archivesPath)); - File zip = new File(archivesPath + ".zip"); + + byte[] zip = createZipArchive(templateSketchPath, processTemplateFiles); return new ZipArchive(zipFileName, zip); } catch (IOException ex) { 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 FileInputStream inputStream = null; - FileOutputStream outputStream = null; try { inputStream = new FileInputStream(srcFile); - outputStream = new FileOutputStream(dstFile); String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString()); Iterator iterator = contextParams.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) iterator.next(); content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString()); } - IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString()); + return content; } finally { if (inputStream != null) { inputStream.close(); } - if (outputStream != null) { - outputStream.close(); - } - } - } - - private static void copyFolder(File src, File dest, List 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 { - BufferedInputStream origin = null; + private static byte[] createZipArchive(String srcFolder, List processTemplateFiles) throws IOException { ZipOutputStream out = null; - + ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { - final int BUFFER = 2048; - FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip")); - out = new ZipOutputStream(new BufferedOutputStream(dest)); - byte data[] = new byte[BUFFER]; + out = new ZipOutputStream(new BufferedOutputStream(baos)); File subDir = new File(srcFolder); String subdirList[] = subDir.list(); if (subdirList == null) { log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty"); - return false; + return null; } for (String sd : subdirList) { // 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()) { String files[] = f.list(); if (files == null) { log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files"); - return false; + return null; } for (int i = 0; i < files.length; i++) { - FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]); - origin = new BufferedInputStream(fi, BUFFER); - ZipEntry entry = new ZipEntry(sd + "/" + files[i]); - out.putNextEntry(entry); - int count; - while ((count = origin.read(data, 0, BUFFER)) != -1) { - out.write(data, 0, count); - out.flush(); + boolean fileAdded = false; + for (TemplateFile templateFile : processTemplateFiles) { + if (files[i].equals(templateFile.getFileName())) { + ZipEntry entry = new ZipEntry(templateFile.getFileName()); + out.putNextEntry(entry); + out.write(templateFile.getContent().getBytes()); + out.closeEntry(); + fileAdded = true; + 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 { - FileInputStream fi = new FileInputStream(f); - origin = new BufferedInputStream(fi, BUFFER); + boolean fileAdded = false; + for (TemplateFile templateFile : processTemplateFiles) { + if (f.getName().equals(templateFile.getFileName())) { + ZipEntry entry = new ZipEntry(templateFile.getFileName()); + out.putNextEntry(entry); + out.write(templateFile.getContent().getBytes()); + out.closeEntry(); + fileAdded = true; + break; + } else if (f.getName().equals("sketch.properties")) { + fileAdded = true; + break; + } + } + if (fileAdded) { + continue; + } ZipEntry entry = new ZipEntry(sd); out.putNextEntry(entry); - int count; - while ((count = origin.read(data, 0, BUFFER)) != -1) { - out.write(data, 0, count); - out.flush(); - } + out.write(IOUtils.toByteArray(new FileInputStream(f))); + out.closeEntry(); } } - out.flush(); + out.finish(); } finally { - if (origin != null) { - origin.close(); - } if (out != null) { 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; + } } } diff --git a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/RaspberryPiServiceImpl.java b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/RaspberryPiServiceImpl.java index f87439123..fdd36862a 100644 --- a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/RaspberryPiServiceImpl.java +++ b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/RaspberryPiServiceImpl.java @@ -144,12 +144,11 @@ public class RaspberryPiServiceImpl implements RaspberryPiService { String username = APIUtil.getAuthenticatedUser() + "@" + PrivilegedCarbonContext .getThreadLocalCarbonContext().getTenantDomain(); 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.type("application/zip"); response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); Response resp = response.build(); - zipFile.getZipFile().delete(); return resp; } catch (IllegalArgumentException ex) { return Response.status(400).entity(ex.getMessage()).build();//bad request @@ -162,9 +161,6 @@ public class RaspberryPiServiceImpl implements RaspberryPiService { } catch (APIManagerException ex) { log.error(ex.getMessage(), ex); 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) { log.error(ex.getMessage(), ex); return Response.status(500).entity(ex.getMessage()).build(); diff --git a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/util/ZipArchive.java b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/util/ZipArchive.java index eb5ed95da..2d955240e 100644 --- a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/util/ZipArchive.java +++ b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/util/ZipArchive.java @@ -18,23 +18,21 @@ package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util; -import java.io.File; - /** * This is an utility class to hold zip files. */ public class ZipArchive { - private File zipFile = null; + private byte[] zipFileContent = null; private String fileName = null; - public ZipArchive(String fileName, File zipFile) { + public ZipArchive(String fileName, byte[] zipFile) { this.fileName = fileName; - this.zipFile = zipFile; + this.zipFileContent = zipFile; } - public File getZipFile() { - return zipFile; + public byte[] getZipFileContent() { + return zipFileContent; } public String getFileName() { diff --git a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/util/ZipUtil.java b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/util/ZipUtil.java index e902609de..bb2a92b85 100644 --- a/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/util/ZipUtil.java +++ b/components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/src/main/java/org/wso2/carbon/device/mgt/iot/raspberrypi/service/impl/util/ZipUtil.java @@ -18,27 +18,22 @@ 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.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.base.ServerConfiguration; import org.wso2.carbon.core.util.Utils; 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.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.utils.CarbonUtils; -import org.wso2.carbon.utils.NetworkUtils; -import java.io.BufferedInputStream; import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; 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; @@ -69,8 +64,6 @@ public class ZipUtil { String refreshToken) throws DeviceManagementException { 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 iotServerIP; @@ -117,7 +110,7 @@ public class ZipUtil { contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken); ZipArchive zipFile; - zipFile = getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName); + zipFile = getSketchArchive(templateSketchPath, contextParams, deviceName); return zipFile; } catch (IOException 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 { return org.apache.axis2.util.Utils.getIpAddress(); } 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) throws DeviceManagementException, IOException { 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"; try { Map> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties"); List templateFiles = properties.get("templates"); + List processTemplateFiles = new ArrayList<>(); for (String templateFile : templateFiles) { - parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath + File.separator + templateFile, - contextParams); + TemplateFile tFile = new TemplateFile(); + tFile.setContent(parseTemplate(templateSketchPath + File.separator + templateFile, contextParams)); + tFile.setFileName(templateFile); + processTemplateFiles.add(tFile); } templateFiles.add("sketch.properties"); // ommit copying the props file - copyFolder(new File(sketchPath), new File(archivesPath), templateFiles); - createZipArchive(archivesPath); - FileUtils.deleteDirectory(new File(archivesPath)); - File zip = new File(archivesPath + ".zip"); + + byte[] zip = createZipArchive(templateSketchPath, processTemplateFiles); return new ZipArchive(zipFileName, zip); } catch (IOException ex) { 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 FileInputStream inputStream = null; - FileOutputStream outputStream = null; try { inputStream = new FileInputStream(srcFile); - outputStream = new FileOutputStream(dstFile); String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString()); Iterator iterator = contextParams.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) iterator.next(); content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString()); } - IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString()); + return content; } finally { if (inputStream != null) { inputStream.close(); } - if (outputStream != null) { - outputStream.close(); - } - } - } - - private static void copyFolder(File src, File dest, List 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 { - BufferedInputStream origin = null; + private static byte[] createZipArchive(String srcFolder, List processTemplateFiles) throws IOException { ZipOutputStream out = null; - + ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { - final int BUFFER = 2048; - FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip")); - out = new ZipOutputStream(new BufferedOutputStream(dest)); - byte data[] = new byte[BUFFER]; + out = new ZipOutputStream(new BufferedOutputStream(baos)); File subDir = new File(srcFolder); String subdirList[] = subDir.list(); if (subdirList == null) { log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty"); - return false; + return null; } for (String sd : subdirList) { // 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()) { String files[] = f.list(); if (files == null) { log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files"); - return false; + return null; } for (int i = 0; i < files.length; i++) { - FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]); - origin = new BufferedInputStream(fi, BUFFER); - ZipEntry entry = new ZipEntry(sd + "/" + files[i]); - out.putNextEntry(entry); - int count; - while ((count = origin.read(data, 0, BUFFER)) != -1) { - out.write(data, 0, count); - out.flush(); + boolean fileAdded = false; + for (TemplateFile templateFile : processTemplateFiles) { + if (files[i].equals(templateFile.getFileName())) { + ZipEntry entry = new ZipEntry(templateFile.getFileName()); + out.putNextEntry(entry); + out.write(templateFile.getContent().getBytes()); + out.closeEntry(); + fileAdded = true; + 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 { - FileInputStream fi = new FileInputStream(f); - origin = new BufferedInputStream(fi, BUFFER); + boolean fileAdded = false; + for (TemplateFile templateFile : processTemplateFiles) { + if (f.getName().equals(templateFile.getFileName())) { + ZipEntry entry = new ZipEntry(templateFile.getFileName()); + out.putNextEntry(entry); + out.write(templateFile.getContent().getBytes()); + out.closeEntry(); + fileAdded = true; + break; + } else if (f.getName().equals("sketch.properties")) { + fileAdded = true; + break; + } + } + if (fileAdded) { + continue; + } ZipEntry entry = new ZipEntry(sd); out.putNextEntry(entry); - int count; - while ((count = origin.read(data, 0, BUFFER)) != -1) { - out.write(data, 0, count); - out.flush(); - } + out.write(IOUtils.toByteArray(new FileInputStream(f))); + out.closeEntry(); } } - out.flush(); + out.finish(); } finally { - if (origin != null) { - origin.close(); - } if (out != null) { 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; + } } } diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/pom.xml b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/pom.xml index 024ef6b57..9a894884d 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/pom.xml +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/pom.xml @@ -51,18 +51,6 @@ - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.analytics.data.publisher - provided - - - org.apache.axis2.wso2 - axis2-client - - - - org.wso2.carbon.devicemgt org.wso2.carbon.certificate.mgt.core diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmServiceImpl.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmServiceImpl.java index fbebe12f9..faec317e0 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmServiceImpl.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/VirtualFireAlarmServiceImpl.java @@ -58,15 +58,11 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; -import java.io.IOException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; -import java.security.PrivateKey; import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.Properties; import java.util.UUID; @@ -175,12 +171,11 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService { String user = APIUtil.getAuthenticatedUser() + "@" + PrivilegedCarbonContext.getThreadLocalCarbonContext() .getTenantDomain(); 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.type("application/zip"); response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\""); Response resp = response.build(); - zipFile.getZipFile().delete(); return resp; } catch (IllegalArgumentException ex) { return Response.status(400).entity(ex.getMessage()).build();//bad request @@ -193,9 +188,6 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService { } catch (APIManagerException ex) { log.error(ex.getMessage(), ex); 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) { log.error(ex.getMessage(), ex); return Response.status(500).entity(ex.getMessage()).build(); diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/ZipArchive.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/ZipArchive.java index 22fda92b3..2152a5e36 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/ZipArchive.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/ZipArchive.java @@ -18,23 +18,23 @@ 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. */ public class ZipArchive { - private File zipFile = null; + private byte[] zipFileContent = null; private String fileName = null; - public ZipArchive(String fileName, File zipFile) { + public ZipArchive(String fileName, byte[] zipFile) { this.fileName = fileName; - this.zipFile = zipFile; + this.zipFileContent = zipFile; } - public File getZipFile() { - return zipFile; + public byte[] getZipFileContent() { + return zipFileContent; } public String getFileName() { diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/ZipUtil.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/ZipUtil.java index e9bcb6c60..496d5eb5a 100644 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/ZipUtil.java +++ b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/ZipUtil.java @@ -19,7 +19,6 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util; import org.apache.commons.codec.binary.Base64; -import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.logging.Log; 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.utils.CarbonUtils; -import java.io.BufferedInputStream; import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; 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; @@ -59,24 +56,18 @@ import java.util.zip.ZipOutputStream; public class ZipUtil { 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 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 CONFIG_TYPE = "general"; 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, String apiApplicationKey, String token, String refreshToken) throws DeviceManagementException { 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 iotServerIP; @@ -141,7 +132,7 @@ public class ZipUtil { ? "" : XmppConfig.getInstance().getJid()); ZipArchive zipFile; - zipFile = getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName); + zipFile = getSketchArchive(templateSketchPath, contextParams, deviceName); return zipFile; } catch (IOException e) { throw new DeviceManagementException("Zip File Creation Failed", e); @@ -159,7 +150,7 @@ public class ZipUtil { return Base64.encodeBase64String(stringToEncode.getBytes()); } - public static String getServerUrl() { + private static String getServerUrl() { try { return org.apache.axis2.util.Utils.getIpAddress(); } 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) throws DeviceManagementException, IOException { 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"; try { Map> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties"); List templateFiles = properties.get("templates"); + List processTemplateFiles = new ArrayList<>(); for (String templateFile : templateFiles) { - parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath + File.separator + templateFile, - contextParams); + TemplateFile tFile = new TemplateFile(); + tFile.setContent(parseTemplate(templateSketchPath + File.separator + templateFile, contextParams)); + tFile.setFileName(templateFile); + processTemplateFiles.add(tFile); } templateFiles.add("sketch.properties"); // ommit copying the props file - copyFolder(new File(sketchPath), new File(archivesPath), templateFiles); - createZipArchive(archivesPath); - FileUtils.deleteDirectory(new File(archivesPath)); - File zip = new File(archivesPath + ".zip"); - return new org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipArchive(zipFileName, zip); + + byte[] zip = createZipArchive(templateSketchPath, processTemplateFiles); + return new ZipArchive(zipFileName, zip); } catch (IOException ex) { throw new DeviceManagementException( "Error occurred when trying to read property " + "file sketch.properties", ex); @@ -206,9 +191,7 @@ public class ZipUtil { InputStream input = null; try { - input = new FileInputStream(propertyFilePath); - // load a properties file prop.load(input); Map> properties = new HashMap>(); @@ -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 FileInputStream inputStream = null; - FileOutputStream outputStream = null; try { inputStream = new FileInputStream(srcFile); - outputStream = new FileOutputStream(dstFile); String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString()); Iterator iterator = contextParams.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) iterator.next(); content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString()); } - IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString()); + return content; } finally { if (inputStream != null) { inputStream.close(); } - if (outputStream != null) { - outputStream.close(); - } } } - private static void copyFolder(File src, File dest, List 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 { - BufferedInputStream origin = null; + private static byte[] createZipArchive(String srcFolder, List processTemplateFiles) throws IOException { ZipOutputStream out = null; - + ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { - final int BUFFER = 2048; - FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip")); - out = new ZipOutputStream(new BufferedOutputStream(dest)); - byte data[] = new byte[BUFFER]; + out = new ZipOutputStream(new BufferedOutputStream(baos)); File subDir = new File(srcFolder); String subdirList[] = subDir.list(); if (subdirList == null) { log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty"); - return false; + return null; } for (String sd : subdirList) { // 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()) { String files[] = f.list(); if (files == null) { log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files"); - return false; + return null; } for (int i = 0; i < files.length; i++) { - FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]); - origin = new BufferedInputStream(fi, BUFFER); - ZipEntry entry = new ZipEntry(sd + "/" + files[i]); - out.putNextEntry(entry); - int count; - while ((count = origin.read(data, 0, BUFFER)) != -1) { - out.write(data, 0, count); - out.flush(); + boolean fileAdded = false; + for (TemplateFile templateFile : processTemplateFiles) { + if (files[i].equals(templateFile.getFileName())) { + ZipEntry entry = new ZipEntry(templateFile.getFileName()); + out.putNextEntry(entry); + out.write(templateFile.getContent().getBytes()); + out.closeEntry(); + fileAdded = true; + 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 { - FileInputStream fi = new FileInputStream(f); - origin = new BufferedInputStream(fi, BUFFER); + boolean fileAdded = false; + for (TemplateFile templateFile : processTemplateFiles) { + if (f.getName().equals(templateFile.getFileName())) { + ZipEntry entry = new ZipEntry(templateFile.getFileName()); + out.putNextEntry(entry); + out.write(templateFile.getContent().getBytes()); + out.closeEntry(); + fileAdded = true; + break; + } else if (f.getName().equals("sketch.properties")) { + fileAdded = true; + break; + } + } + if (fileAdded) { + continue; + } ZipEntry entry = new ZipEntry(sd); out.putNextEntry(entry); - int count; - while ((count = origin.read(data, 0, BUFFER)) != -1) { - out.write(data, 0, count); - out.flush(); - } + out.write(IOUtils.toByteArray(new FileInputStream(f))); + out.closeEntry(); } } - out.flush(); + out.finish(); } finally { - if (origin != null) { - origin.close(); - } if (out != null) { 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; + } } } diff --git a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/util/Utils.java b/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/util/Utils.java deleted file mode 100644 index 586de223c..000000000 --- a/components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/src/main/java/org/wso2/carbon/device/mgt/iot/virtualfirealarm/service/impl/util/util/Utils.java +++ /dev/null @@ -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); - - - -} diff --git a/components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.restconnector/src/main/java/org/wso2/carbon/appmgt/mdm/restconnector/ApplicationOperationsImpl.java b/components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.restconnector/src/main/java/org/wso2/carbon/appmgt/mdm/restconnector/ApplicationOperationsImpl.java index 4d829a738..ac6cf2fe1 100644 --- a/components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.restconnector/src/main/java/org/wso2/carbon/appmgt/mdm/restconnector/ApplicationOperationsImpl.java +++ b/components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.restconnector/src/main/java/org/wso2/carbon/appmgt/mdm/restconnector/ApplicationOperationsImpl.java @@ -19,6 +19,9 @@ package org.wso2.carbon.appmgt.mdm.restconnector; import feign.Client; import feign.Feign; +import feign.Logger; +import feign.Request; +import feign.Response; import feign.gson.GsonDecoder; import feign.gson.GsonEncoder; import feign.jaxrs.JAXRSContract; @@ -51,6 +54,7 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; +import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; @@ -71,13 +75,13 @@ public class ApplicationOperationsImpl implements ApplicationOperations { public ApplicationOperationsImpl() { String authorizationConfigManagerServerURL = AuthorizationConfigurationManager.getInstance().getServerURL(); OAuthRequestInterceptor oAuthRequestInterceptor = new OAuthRequestInterceptor(); - deviceManagementAdminService = Feign.builder().client(getSSLClient()) - .requestInterceptor(oAuthRequestInterceptor) + deviceManagementAdminService = Feign.builder().client(getSSLClient()).logger(getLogger()).logLevel( + Logger.Level.FULL).requestInterceptor(oAuthRequestInterceptor) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(DeviceManagementAdminService.class, authorizationConfigManagerServerURL + CDMF_SERVER_BASE_CONTEXT); - applicationManagementAdminService = Feign.builder().client(getSSLClient()) - .requestInterceptor(oAuthRequestInterceptor) + applicationManagementAdminService = Feign.builder().client(getSSLClient()).logger(getLogger()).logLevel( + Logger.Level.FULL).requestInterceptor(oAuthRequestInterceptor) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(ApplicationManagementAdminService.class, authorizationConfigManagerServerURL + CDMF_SERVER_BASE_CONTEXT); @@ -311,6 +315,32 @@ public class ApplicationOperationsImpl implements ApplicationOperations { } catch (KeyManagementException | NoSuchAlgorithmException e) { return null; } + } + + private static Logger getLogger() { + return new Logger() { + @Override + protected void log(String configKey, String format, Object... args) { + if (log.isDebugEnabled()) { + log.debug(String.format(methodTag(configKey) + format, args)); + } + } + + @Override + protected void logRequest(String configKey, Level logLevel, Request request) { + if (log.isDebugEnabled()) { + super.logRequest(configKey, logLevel, request); + } + } + @Override + protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, + long elapsedTime) throws IOException { + if (log.isDebugEnabled()) { + return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime); + } + return response; + } + }; } } \ No newline at end of file diff --git a/components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.restconnector/src/main/java/org/wso2/carbon/appmgt/mdm/restconnector/authorization/client/OAuthRequestInterceptor.java b/components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.restconnector/src/main/java/org/wso2/carbon/appmgt/mdm/restconnector/authorization/client/OAuthRequestInterceptor.java index 91ed76bce..e3f5858d4 100755 --- a/components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.restconnector/src/main/java/org/wso2/carbon/appmgt/mdm/restconnector/authorization/client/OAuthRequestInterceptor.java +++ b/components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.restconnector/src/main/java/org/wso2/carbon/appmgt/mdm/restconnector/authorization/client/OAuthRequestInterceptor.java @@ -19,12 +19,17 @@ package org.wso2.carbon.appmgt.mdm.restconnector.authorization.client; import feign.Client; import feign.Feign; +import feign.Logger; +import feign.Request; import feign.RequestInterceptor; import feign.RequestTemplate; +import feign.Response; import feign.auth.BasicAuthRequestInterceptor; import feign.gson.GsonDecoder; import feign.gson.GsonEncoder; import feign.jaxrs.JAXRSContract; +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.authorization.client.dto.AccessTokenInfo; import org.wso2.carbon.appmgt.mdm.restconnector.authorization.client.dto.ApiApplicationKey; @@ -40,6 +45,7 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; +import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; @@ -56,6 +62,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private static final String REFRESH_GRANT_TYPE = "refresh_token"; private ApiApplicationRegistrationService apiApplicationRegistrationService; private TokenIssuerService tokenIssuerService; + private static Log log = LogFactory.getLog(OAuthRequestInterceptor.class); + /** * Creates an interceptor that authenticates all requests. @@ -64,8 +72,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor { refreshTimeOffset = AuthorizationConfigurationManager.getInstance().getTokenRefreshTimeOffset(); String username = AuthorizationConfigurationManager.getInstance().getUserName(); String password = AuthorizationConfigurationManager.getInstance().getPassword(); - apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).requestInterceptor( - new BasicAuthRequestInterceptor(username, password)) + apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).logger(getLogger()).logLevel( + Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password)) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(ApiApplicationRegistrationService.class, AuthorizationConfigurationManager.getInstance().getServerURL() + @@ -92,8 +100,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor { String consumerSecret = apiApplicationKey.getConsumerSecret(); String username = AuthorizationConfigurationManager.getInstance().getUserName(); String password = AuthorizationConfigurationManager.getInstance().getPassword(); - tokenIssuerService = Feign.builder().client(getSSLClient()).requestInterceptor( - new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) + tokenIssuerService = Feign.builder().client(getSSLClient()).logger(getLogger()).logLevel(Logger.Level.FULL) + .requestInterceptor(new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(TokenIssuerService.class, AuthorizationConfigurationManager.getInstance().getTokenApiURL()); tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password); @@ -139,6 +147,33 @@ public class OAuthRequestInterceptor implements RequestInterceptor { } catch (KeyManagementException | NoSuchAlgorithmException e) { return null; } + } + + private static Logger getLogger() { + return new Logger() { + @Override + protected void log(String configKey, String format, Object... args) { + if (log.isDebugEnabled()) { + log.debug(String.format(methodTag(configKey) + format, args)); + } + } + @Override + protected void logRequest(String configKey, Level logLevel, Request request) { + if (log.isDebugEnabled()) { + super.logRequest(configKey, logLevel, request); + } + } + + @Override + protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, + long elapsedTime) throws IOException { + if (log.isDebugEnabled()) { + return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime); + } + return response; + } + }; } + } diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/authorization/DeviceAuthorizer.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/authorization/DeviceAuthorizer.java index e317199d1..3c3386583 100644 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/authorization/DeviceAuthorizer.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/authorization/DeviceAuthorizer.java @@ -20,6 +20,9 @@ package org.wso2.carbon.device.mgt.input.adapter.http.authorization; import feign.Client; import feign.Feign; import feign.FeignException; +import feign.Logger; +import feign.Request; +import feign.Response; import feign.gson.GsonDecoder; import feign.gson.GsonEncoder; import feign.jaxrs.JAXRSContract; @@ -40,10 +43,10 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; +import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import java.util.Map; @@ -55,17 +58,17 @@ public class DeviceAuthorizer { private static DeviceAccessAuthorizationAdminService deviceAccessAuthorizationAdminService; private static final String CDMF_SERVER_BASE_CONTEXT = "/api/device-mgt/v1.0"; 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 globalProperties) { try { - deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()) - .requestInterceptor(new OAuthRequestInterceptor(globalProperties)) + deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()).logger(getLogger()) + .logLevel(Logger.Level.FULL).requestInterceptor(new OAuthRequestInterceptor(globalProperties)) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(DeviceAccessAuthorizationAdminService.class, getDeviceMgtServerUrl(globalProperties) + CDMF_SERVER_BASE_CONTEXT); } catch (InputEventAdapterException e) { - logger.error("Invalid value for deviceMgtServerUrl in globalProperties."); + log.error("Invalid value for deviceMgtServerUrl in globalProperties."); } } @@ -94,7 +97,7 @@ public class DeviceAuthorizer { } } } catch (FeignException e) { - logger.error(e.getMessage(), e); + log.error(e.getMessage(), e); } } return false; @@ -103,7 +106,7 @@ public class DeviceAuthorizer { private String getDeviceMgtServerUrl(Map properties) throws InputEventAdapterException { String deviceMgtServerUrl = PropertyUtils.replaceProperty(properties.get(DEVICE_MGT_SERVER_URL)); if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) { - logger.error("deviceMgtServerUrl can't be empty "); + log.error("deviceMgtServerUrl can't be empty "); } return deviceMgtServerUrl; } @@ -138,6 +141,33 @@ public class DeviceAuthorizer { } catch (KeyManagementException | NoSuchAlgorithmException e) { return null; } + } + private static Logger getLogger() { + return new Logger() { + @Override + protected void log(String configKey, String format, Object... args) { + if (log.isDebugEnabled()) { + log.debug(String.format(methodTag(configKey) + format, args)); + } + } + + @Override + protected void logRequest(String configKey, Level logLevel, Request request) { + if (log.isDebugEnabled()) { + super.logRequest(configKey, logLevel, request); + } + } + + @Override + protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, + long elapsedTime) throws IOException { + if (log.isDebugEnabled()) { + return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime); + } + return response; + } + }; } + } \ No newline at end of file diff --git a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/authorization/client/OAuthRequestInterceptor.java b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/authorization/client/OAuthRequestInterceptor.java index bc8cfd709..e09357f76 100755 --- a/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/authorization/client/OAuthRequestInterceptor.java +++ b/components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/src/main/java/org/wso2/carbon/device/mgt/input/adapter/http/authorization/client/OAuthRequestInterceptor.java @@ -16,8 +16,11 @@ package org.wso2.carbon.device.mgt.input.adapter.http.authorization.client; import feign.Client; import feign.Feign; +import feign.Logger; +import feign.Request; import feign.RequestInterceptor; import feign.RequestTemplate; +import feign.Response; import feign.auth.BasicAuthRequestInterceptor; import feign.gson.GsonDecoder; import feign.gson.GsonEncoder; @@ -38,6 +41,7 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; +import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; @@ -58,7 +62,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private ApiApplicationRegistrationService apiApplicationRegistrationService; 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_PASSWORD = "password"; @@ -85,13 +89,13 @@ public class OAuthRequestInterceptor implements RequestInterceptor { username = getUsername(globalProperties); password = getPassword(globalProperties); tokenEndpoint = getTokenEndpoint(globalProperties); - apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).requestInterceptor( - new BasicAuthRequestInterceptor(username, password)) + apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).logger(getLogger()).logLevel( + Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password)) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(ApiApplicationRegistrationService.class, deviceMgtServerUrl + API_APPLICATION_REGISTRATION_CONTEXT); } catch (InputEventAdapterException e) { - logger.error("Invalid url: deviceMgtServerUrl" + deviceMgtServerUrl + " or tokenEndpoint:" + tokenEndpoint, + log.error("Invalid url: deviceMgtServerUrl" + deviceMgtServerUrl + " or tokenEndpoint:" + tokenEndpoint, e); } } @@ -108,8 +112,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor { ApiApplicationKey apiApplicationKey = apiApplicationRegistrationService.register(apiRegistrationProfile); String consumerKey = apiApplicationKey.getConsumerKey(); String consumerSecret = apiApplicationKey.getConsumerSecret(); - tokenIssuerService = Feign.builder().client(getSSLClient()).requestInterceptor( - new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) + tokenIssuerService = Feign.builder().client(getSSLClient()).logger(getLogger()).logLevel(Logger.Level.FULL) + .requestInterceptor(new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(TokenIssuerService.class, tokenEndpoint); tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password, REQUIRED_SCOPE); @@ -128,7 +132,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private String getUsername(Map globalProperties) { String username = globalProperties.get(CONNECTION_USERNAME); if (username == null || username.isEmpty()) { - logger.error("username can't be empty "); + log.error("username can't be empty "); } return username; } @@ -136,7 +140,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private String getPassword(Map globalProperties) { String password = globalProperties.get(CONNECTION_PASSWORD);; if (password == null || password.isEmpty()) { - logger.error("password can't be empty "); + log.error("password can't be empty "); } return password; } @@ -144,7 +148,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private String getDeviceMgtServerUrl(Map globalProperties) throws InputEventAdapterException { String deviceMgtServerUrl = globalProperties.get(DEVICE_MGT_SERVER_URL); if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) { - logger.error("deviceMgtServerUrl can't be empty "); + log.error("deviceMgtServerUrl can't be empty "); } return PropertyUtils.replaceProperty(deviceMgtServerUrl); } @@ -152,7 +156,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private String getTokenEndpoint(Map globalProperties) throws InputEventAdapterException { String tokenEndpoint = globalProperties.get(TOKEN_ENDPOINT_CONTEXT); if ( tokenEndpoint.isEmpty()) { - logger.error("tokenEndpoint can't be empty "); + log.error("tokenEndpoint can't be empty "); } return PropertyUtils.replaceProperty(tokenEndpoint); } @@ -162,7 +166,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { try { refreshTimeOffset = Long.parseLong(globalProperties.get(TOKEN_REFRESH_TIME_OFFSET)); } catch (NumberFormatException e) { - logger.error("refreshTimeOffset should be a number", e); + log.error("refreshTimeOffset should be a number", e); } return refreshTimeOffset; } @@ -197,7 +201,33 @@ public class OAuthRequestInterceptor implements RequestInterceptor { } catch (KeyManagementException | NoSuchAlgorithmException e) { return null; } + } + private static Logger getLogger() { + return new Logger() { + @Override + protected void log(String configKey, String format, Object... args) { + if (log.isDebugEnabled()) { + log.debug(String.format(methodTag(configKey) + format, args)); + } + } + + @Override + protected void logRequest(String configKey, Level logLevel, Request request) { + if (log.isDebugEnabled()) { + super.logRequest(configKey, logLevel, request); + } + } + + @Override + protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, + long elapsedTime) throws IOException { + if (log.isDebugEnabled()) { + return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime); + } + return response; + } + }; } } diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/DeviceAuthorizer.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/DeviceAuthorizer.java index 489c16956..6cb9e04ee 100644 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/DeviceAuthorizer.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/DeviceAuthorizer.java @@ -20,6 +20,9 @@ package org.wso2.carbon.device.mgt.output.adapter.websocket.authorization; import feign.Client; import feign.Feign; import feign.FeignException; +import feign.Logger; +import feign.Request; +import feign.Response; import feign.gson.GsonDecoder; import feign.gson.GsonEncoder; import feign.jaxrs.JAXRSContract; @@ -43,6 +46,7 @@ import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import javax.websocket.Session; +import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; @@ -61,7 +65,7 @@ public class DeviceAuthorizer implements Authorizer { private static final String STAT_PERMISSION = "statsPermission"; private static final String DEVICE_ID = "deviceId"; 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 statPermissions; public DeviceAuthorizer() { @@ -76,13 +80,13 @@ public class DeviceAuthorizer implements Authorizer { } } try { - deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()) - .requestInterceptor(new OAuthRequestInterceptor(globalProperties)) + deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()).logger(getLogger()) + .logLevel(Logger.Level.FULL).requestInterceptor(new OAuthRequestInterceptor(globalProperties)) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(DeviceAccessAuthorizationAdminService.class, getDeviceMgtServerUrl(globalProperties) + CDMF_SERVER_BASE_CONTEXT); } catch (OutputEventAdapterException e) { - logger.error("Invalid value for deviceMgtServerUrl in globalProperties."); + log.error("Invalid value for deviceMgtServerUrl in globalProperties."); } } @@ -118,7 +122,7 @@ public class DeviceAuthorizer implements Authorizer { } } } catch (FeignException e) { - logger.error(e.getMessage(), e); + log.error(e.getMessage(), e); } } return false; @@ -127,7 +131,7 @@ public class DeviceAuthorizer implements Authorizer { private String getDeviceMgtServerUrl(Map properties) throws OutputEventAdapterException { String deviceMgtServerUrl = PropertyUtils.replaceProperty(properties.get(DEVICE_MGT_SERVER_URL)); if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) { - logger.error("deviceMgtServerUrl can't be empty "); + log.error("deviceMgtServerUrl can't be empty "); } return deviceMgtServerUrl; } @@ -170,6 +174,32 @@ public class DeviceAuthorizer implements Authorizer { } catch (KeyManagementException | NoSuchAlgorithmException e) { return null; } + } + + private static Logger getLogger() { + return new Logger() { + @Override + protected void log(String configKey, String format, Object... args) { + if (log.isDebugEnabled()) { + log.debug(String.format(methodTag(configKey) + format, args)); + } + } + + @Override + protected void logRequest(String configKey, Level logLevel, Request request) { + if (log.isDebugEnabled()) { + super.logRequest(configKey, logLevel, request); + } + } + @Override + protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, + long elapsedTime) throws IOException { + if (log.isDebugEnabled()) { + return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime); + } + return response; + } + }; } } \ No newline at end of file diff --git a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/client/OAuthRequestInterceptor.java b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/client/OAuthRequestInterceptor.java index 21ba423c2..d8f168da5 100755 --- a/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/client/OAuthRequestInterceptor.java +++ b/components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/src/main/java/org/wso2/carbon/device/mgt/output/adapter/websocket/authorization/client/OAuthRequestInterceptor.java @@ -16,8 +16,11 @@ package org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client import feign.Client; import feign.Feign; +import feign.Logger; +import feign.Request; import feign.RequestInterceptor; import feign.RequestTemplate; +import feign.Response; import feign.auth.BasicAuthRequestInterceptor; import feign.gson.GsonDecoder; import feign.gson.GsonEncoder; @@ -38,6 +41,7 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; +import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.Map; @@ -58,7 +62,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private ApiApplicationRegistrationService apiApplicationRegistrationService; 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_PASSWORD = "password"; @@ -86,13 +90,13 @@ public class OAuthRequestInterceptor implements RequestInterceptor { username = getUsername(globalProperties); password = getPassword(globalProperties); tokenEndpoint = getTokenEndpoint(globalProperties); - apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).requestInterceptor( - new BasicAuthRequestInterceptor(username, password)) + apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).logger(getLogger()) + .logLevel(Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password)) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(ApiApplicationRegistrationService.class, deviceMgtServerUrl + API_APPLICATION_REGISTRATION_CONTEXT); } catch (OutputEventAdapterException e) { - logger.error("Invalid url: deviceMgtServerUrl" + deviceMgtServerUrl + " or tokenEndpoint:" + tokenEndpoint, + log.error("Invalid url: deviceMgtServerUrl" + deviceMgtServerUrl + " or tokenEndpoint:" + tokenEndpoint, e); } } @@ -109,8 +113,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor { ApiApplicationKey apiApplicationKey = apiApplicationRegistrationService.register(apiRegistrationProfile); String consumerKey = apiApplicationKey.getConsumerKey(); String consumerSecret = apiApplicationKey.getConsumerSecret(); - tokenIssuerService = Feign.builder().client(getSSLClient()).requestInterceptor( - new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) + tokenIssuerService = Feign.builder().client(getSSLClient()).logger(getLogger()).logLevel(Logger.Level.FULL) + .requestInterceptor(new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(TokenIssuerService.class, tokenEndpoint); tokenInfo = tokenIssuerService.getToken(PASSWORD_GRANT_TYPE, username, password, REQUIRED_SCOPE); @@ -129,7 +133,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private String getUsername(Map globalProperties) { String username = globalProperties.get(CONNECTION_USERNAME); if (username == null || username.isEmpty()) { - logger.error("username can't be empty "); + log.error("username can't be empty "); } return username; } @@ -137,7 +141,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private String getPassword(Map globalProperties) { String password = globalProperties.get(CONNECTION_PASSWORD);; if (password == null || password.isEmpty()) { - logger.error("password can't be empty "); + log.error("password can't be empty "); } return password; } @@ -145,7 +149,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private String getDeviceMgtServerUrl(Map globalProperties) throws OutputEventAdapterException { String deviceMgtServerUrl = globalProperties.get(DEVICE_MGT_SERVER_URL); if (deviceMgtServerUrl == null || deviceMgtServerUrl.isEmpty()) { - logger.error("deviceMgtServerUrl can't be empty "); + log.error("deviceMgtServerUrl can't be empty "); } return PropertyUtils.replaceProperty(deviceMgtServerUrl); } @@ -153,7 +157,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private String getTokenEndpoint(Map globalProperties) throws OutputEventAdapterException { String tokenEndpoint = globalProperties.get(TOKEN_ENDPOINT_CONTEXT); if ( tokenEndpoint.isEmpty()) { - logger.error("tokenEndpoint can't be empty "); + log.error("tokenEndpoint can't be empty "); } return PropertyUtils.replaceProperty(tokenEndpoint); } @@ -163,7 +167,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { try { refreshTimeOffset = Long.parseLong(globalProperties.get(TOKEN_REFRESH_TIME_OFFSET)); } catch (NumberFormatException e) { - logger.error("refreshTimeOffset should be a number", e); + log.error("refreshTimeOffset should be a number", e); } return refreshTimeOffset; } @@ -198,7 +202,33 @@ public class OAuthRequestInterceptor implements RequestInterceptor { } catch (KeyManagementException | NoSuchAlgorithmException e) { return null; } + } + private static Logger getLogger() { + return new Logger() { + @Override + protected void log(String configKey, String format, Object... args) { + if (log.isDebugEnabled()) { + log.debug(String.format(methodTag(configKey) + format, args)); + } + } + + @Override + protected void logRequest(String configKey, Level logLevel, Request request) { + if (log.isDebugEnabled()) { + super.logRequest(configKey, logLevel, request); + } + } + + @Override + protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, + long elapsedTime) throws IOException { + if (log.isDebugEnabled()) { + return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime); + } + return response; + } + }; } } diff --git a/components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/src/main/java/org/wso2/carbon/andes/extensions/device/mgt/mqtt/authorization/DeviceAccessBasedMQTTAuthorizer.java b/components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/src/main/java/org/wso2/carbon/andes/extensions/device/mgt/mqtt/authorization/DeviceAccessBasedMQTTAuthorizer.java index b1d075ac5..bffe0d565 100644 --- a/components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/src/main/java/org/wso2/carbon/andes/extensions/device/mgt/mqtt/authorization/DeviceAccessBasedMQTTAuthorizer.java +++ b/components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/src/main/java/org/wso2/carbon/andes/extensions/device/mgt/mqtt/authorization/DeviceAccessBasedMQTTAuthorizer.java @@ -21,6 +21,9 @@ package org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization; import feign.Client; import feign.Feign; import feign.FeignException; +import feign.Logger; +import feign.Request; +import feign.Response; import feign.gson.GsonDecoder; import feign.gson.GsonEncoder; import feign.jaxrs.JAXRSContract; @@ -44,7 +47,6 @@ import org.wso2.carbon.user.api.UserStoreException; import javax.cache.Cache; import javax.cache.CacheConfiguration; -import javax.cache.CacheManager; import javax.cache.Caching; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; @@ -52,6 +54,7 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; +import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; @@ -67,7 +70,7 @@ import java.util.concurrent.TimeUnit; public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer { 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; private static final String CDMF_SERVER_BASE_CONTEXT = "/api/device-mgt/v1.0"; private static final String CACHE_MANAGER_NAME = "mqttAuthorizationCacheManager"; @@ -77,8 +80,8 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer { public DeviceAccessBasedMQTTAuthorizer() { this.MQTTAuthorizationConfiguration = AuthorizationConfigurationManager.getInstance(); - deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()) - .requestInterceptor(new OAuthRequestInterceptor()) + deviceAccessAuthorizationAdminService = Feign.builder().client(getSSLClient()).logger(getLogger()) + .logLevel(Logger.Level.FULL).requestInterceptor(new OAuthRequestInterceptor()) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(DeviceAccessAuthorizationAdminService.class, MQTTAuthorizationConfiguration.getDeviceMgtServerUrl() + CDMF_SERVER_BASE_CONTEXT); @@ -117,7 +120,7 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer { } return false; } catch (FeignException e) { - logger.error(e.getMessage(), e); + log.error(e.getMessage(), e); return false; } } @@ -160,7 +163,7 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer { } } } catch (FeignException e) { - logger.error(e.getMessage(), e); + log.error(e.getMessage(), e); } } finally { PrivilegedCarbonContext.endTenantFlow(); @@ -204,7 +207,7 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer { userRealm.getAuthorizationManager().isUserAuthorized(username, permission, action); } catch (UserStoreException e) { String errorMsg = String.format("Unable to authorize the user : %s", username); - logger.error(errorMsg, e); + log.error(errorMsg, e); return false; } finally { PrivilegedCarbonContext.endTenantFlow(); @@ -263,7 +266,33 @@ public class DeviceAccessBasedMQTTAuthorizer implements IAuthorizer { } catch (KeyManagementException | NoSuchAlgorithmException e) { return null; } + } + + private static Logger getLogger() { + return new Logger() { + @Override + protected void log(String configKey, String format, Object... args) { + if (log.isDebugEnabled()) { + log.debug(String.format(methodTag(configKey) + format, args)); + } + } + + @Override + protected void logRequest(String configKey, Level logLevel, Request request) { + if (log.isDebugEnabled()) { + super.logRequest(configKey, logLevel, request); + } + } + @Override + protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, + long elapsedTime) throws IOException { + if (log.isDebugEnabled()) { + return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime); + } + return response; + } + }; } } \ No newline at end of file diff --git a/components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/src/main/java/org/wso2/carbon/andes/extensions/device/mgt/mqtt/authorization/client/OAuthRequestInterceptor.java b/components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/src/main/java/org/wso2/carbon/andes/extensions/device/mgt/mqtt/authorization/client/OAuthRequestInterceptor.java index 1f1af5a21..a49af5c83 100755 --- a/components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/src/main/java/org/wso2/carbon/andes/extensions/device/mgt/mqtt/authorization/client/OAuthRequestInterceptor.java +++ b/components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/src/main/java/org/wso2/carbon/andes/extensions/device/mgt/mqtt/authorization/client/OAuthRequestInterceptor.java @@ -16,14 +16,19 @@ package org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client; import feign.Client; import feign.Feign; +import feign.Logger; +import feign.Request; import feign.RequestInterceptor; import feign.RequestTemplate; +import feign.Response; import feign.auth.BasicAuthRequestInterceptor; import feign.codec.EncodeException; import feign.codec.Encoder; import feign.gson.GsonDecoder; import feign.gson.GsonEncoder; import feign.jaxrs.JAXRSContract; +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.ApiApplicationKey; import org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.client.dto.ApiApplicationRegistrationService; @@ -37,6 +42,7 @@ import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; +import java.io.IOException; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; @@ -55,6 +61,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor { private static final String REQUIRED_SCOPE = "perm:authorization:verify"; private ApiApplicationRegistrationService apiApplicationRegistrationService; private TokenIssuerService tokenIssuerService; + private static Log log = LogFactory.getLog(OAuthRequestInterceptor.class); /** * Creates an interceptor that authenticates all requests. @@ -63,8 +70,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor { refreshTimeOffset = AuthorizationConfigurationManager.getInstance().getTokenRefreshTimeOffset() * 1000; String username = AuthorizationConfigurationManager.getInstance().getUsername(); String password = AuthorizationConfigurationManager.getInstance().getPassword(); - apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).requestInterceptor( - new BasicAuthRequestInterceptor(username, password)) + apiApplicationRegistrationService = Feign.builder().client(getSSLClient()).logger(getLogger()).logLevel( + Logger.Level.FULL).requestInterceptor(new BasicAuthRequestInterceptor(username, password)) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(ApiApplicationRegistrationService.class, AuthorizationConfigurationManager.getInstance().getDeviceMgtServerUrl() + @@ -85,8 +92,8 @@ public class OAuthRequestInterceptor implements RequestInterceptor { String consumerSecret = apiApplicationKey.getConsumerSecret(); String username = AuthorizationConfigurationManager.getInstance().getUsername(); String password = AuthorizationConfigurationManager.getInstance().getPassword(); - tokenIssuerService = Feign.builder().client(getSSLClient()).requestInterceptor( - new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) + tokenIssuerService = Feign.builder().client(getSSLClient()).logger(getLogger()).logLevel(Logger.Level.FULL) + .requestInterceptor(new BasicAuthRequestInterceptor(consumerKey, consumerSecret)) .contract(new JAXRSContract()).encoder(new GsonEncoder()).decoder(new GsonDecoder()) .target(TokenIssuerService.class, AuthorizationConfigurationManager.getInstance().getTokenEndpoint()); @@ -133,7 +140,33 @@ public class OAuthRequestInterceptor implements RequestInterceptor { } catch (KeyManagementException | NoSuchAlgorithmException e) { return null; } + } + private static Logger getLogger() { + return new Logger() { + @Override + protected void log(String configKey, String format, Object... args) { + if (log.isDebugEnabled()) { + log.debug(String.format(methodTag(configKey) + format, args)); + } + } + + @Override + protected void logRequest(String configKey, Level logLevel, Request request) { + if (log.isDebugEnabled()) { + super.logRequest(configKey, logLevel, request); + } + } + + @Override + protected Response logAndRebufferResponse(String configKey, Level logLevel, Response response, + long elapsedTime) throws IOException { + if (log.isDebugEnabled()) { + return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime); + } + return response; + } + }; } } From 6604c23257f222bdfd73fa9bab634059bffdadb9 Mon Sep 17 00:00:00 2001 From: kamidu Date: Thu, 2 Mar 2017 15:20:27 +0530 Subject: [PATCH 2/8] fix for leaflet tile not loading issues --- .../public/js/load-map.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/load-map.js b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/load-map.js index 8ce98731b..af0d1e5d8 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/load-map.js +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.device-view/public/js/load-map.js @@ -46,9 +46,10 @@ function loadLeafletMap() { this.closePopup(); }); } - $("#map-error").hide(); $("#device-location").show(); + setTimeout(function(){ map.invalidateSize()}, 400); + } else if (location_long && location_lat) { map = L.map(container).setView([location_lat, location_long], zoomLevel); @@ -61,7 +62,9 @@ function loadLeafletMap() { m.on('mouseout', function (e) { this.closePopup(); }); - + $("#map-error").hide(); + $("#device-location").show(); + setTimeout(function(){ map.invalidateSize()}, 400); } else { $("#device-location").hide(); $("#map-error").show(); From 77ec1c4107466879f263f1ec08daf919faf89423 Mon Sep 17 00:00:00 2001 From: ayyoob Date: Thu, 2 Mar 2017 20:27:46 +0530 Subject: [PATCH 3/8] fixed operation bar permission rendering issue --- .../app/modules/business-controllers/operation.js | 14 +++++++++++++- .../operation-bar.hbs | 5 ----- .../operation-bar.js | 4 ++-- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/app/modules/business-controllers/operation.js b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/app/modules/business-controllers/operation.js index e96ffcdec..58d0f5f2b 100755 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/app/modules/business-controllers/operation.js +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/android-web-agent/app/modules/business-controllers/operation.js @@ -60,7 +60,19 @@ var operationModule = function () { feature["description"] = features[i].description; feature["deviceType"] = deviceType; feature["params"] = []; - var metaData = features[i].metadataEntries; + var featuresEntry = utility.getDeviceTypeConfig(deviceType)["deviceType"]["features"]; + if (featuresEntry) { + var featureEntry = featuresEntry[features[i].code]; + if (featureEntry) { + var permissionEntry = featureEntry["permission"]; + log.error(permissionEntry); + if (permissionEntry) { + feature["permission"] = permissionEntry + } + } + } + + var metaData = features[i].metadataEntries; if (metaData) { for (var j = 0; j < metaData.length; j++) { feature["params"].push(metaData[j].value); diff --git a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.operation-bar/operation-bar.hbs b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.operation-bar/operation-bar.hbs index 688302a90..3a5a60956 100644 --- a/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.operation-bar/operation-bar.hbs +++ b/components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.operation-bar/operation-bar.hbs @@ -113,11 +113,6 @@ {{/each}} -{{else}} -
-

- Operations Loading Failed!

-
{{/if}}