Search in sources :

Example 1 with ZipArchive

use of org.wso2.iot.sampledevice.api.util.ZipArchive in project product-iots by wso2.

the class DeviceTypeServiceImpl method downloadSketch.

/**
 * To download device type agent source code as zip file.
 *
 * @param deviceName name for the device type instance
 * @param sketchType folder name where device type agent was installed into server
 * @return Agent source code as zip file
 */
@Path("/device/download")
@GET
@Produces("application/zip")
public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType) {
    try {
        ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
        Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
        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) {
        // bad request
        return Response.status(400).entity(ex.getMessage()).build();
    } catch (DeviceManagementException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } catch (JWTClientException ex) {
        log.error(ex.getMessage(), ex);
        return Response.status(500).entity(ex.getMessage()).build();
    } 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();
    }
}
Also used : Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException) APIManagerException(org.wso2.carbon.apimgt.application.extension.exception.APIManagerException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ZipArchive(org.wso2.iot.sampledevice.api.util.ZipArchive) IOException(java.io.IOException) JWTClientException(org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 2 with ZipArchive

use of org.wso2.iot.sampledevice.api.util.ZipArchive in project product-iots by wso2.

the class DeviceTypeServiceImpl method createDownloadFile.

private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType) throws DeviceManagementException, JWTClientException, APIManagerException, UserStoreException {
    // create new device id
    String deviceId = shortUUID();
    if (apiApplicationKey == null) {
        String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName();
        applicationUsername = applicationUsername + "@" + APIUtil.getAuthenticatedUserTenantDomain();
        APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
        String[] tags = { DeviceTypeConstants.DEVICE_TYPE };
        apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(DeviceTypeConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true, "3600");
    }
    JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
    String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId;
    AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret(), owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(), scopes);
    // create token
    String accessToken = accessTokenInfo.getAccessToken();
    String refreshToken = accessTokenInfo.getRefreshToken();
    boolean status = register(deviceId, deviceName);
    if (!status) {
        String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
        throw new DeviceManagementException(msg);
    }
    ZipUtil ziputil = new ZipUtil();
    ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, deviceId, deviceName, accessToken, refreshToken, apiApplicationKey.toString());
    return zipFile;
}
Also used : AccessTokenInfo(org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo) DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException) APIManagementProviderService(org.wso2.carbon.apimgt.application.extension.APIManagementProviderService) JWTClient(org.wso2.carbon.identity.jwt.client.extension.JWTClient) ZipUtil(org.wso2.iot.sampledevice.api.util.ZipUtil) ZipArchive(org.wso2.iot.sampledevice.api.util.ZipArchive)

Example 3 with ZipArchive

use of org.wso2.iot.sampledevice.api.util.ZipArchive in project product-iots by wso2.

the class ZipUtil method createZipFile.

/**
 * Create agent zip file.
 *
 * @param owner             Owner of device.
 * @param tenantDomain      Tenant of the device.
 * @param deviceType        Device type.
 * @param deviceId          Device ID.
 * @param deviceName        Device Name
 * @param token             Auth token to access the api.
 * @param refreshToken      Refresh token to generate new auth token.
 * @param apiApplicationKey Application key.
 * @return Zip archive.
 * @throws DeviceManagementException Error creating zip archive.
 */
public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType, String deviceId, String deviceName, String token, String refreshToken, String apiApplicationKey) 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;
    try {
        iotServerIP = getServerUrl();
        String httpsServerEP = Utils.replaceSystemProperty(HTTPS_PROTOCOL_URL);
        String httpServerEP = Utils.replaceSystemProperty(HTTP_PROTOCOL_URL);
        String mqttEndpoint = Utils.replaceSystemProperty(DEFAULT_MQTT_ENDPOINT);
        if (mqttEndpoint.contains(LOCALHOST)) {
            mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP);
            httpsServerEP = httpsServerEP.replace(LOCALHOST, iotServerIP);
            httpServerEP = httpServerEP.replace(LOCALHOST, iotServerIP);
        }
        String base64EncodedApplicationKey = getBase64EncodedAPIAppKey(apiApplicationKey).trim();
        Map<String, String> contextParams = new HashMap<>();
        contextParams.put("SERVER_NAME", APIUtil.getTenantDomainOftheUser());
        contextParams.put("DEVICE_OWNER", owner);
        contextParams.put("DEVICE_ID", deviceId);
        contextParams.put("DEVICE_NAME", deviceName);
        contextParams.put("HTTPS_EP", httpsServerEP);
        contextParams.put("HTTP_EP", httpServerEP);
        contextParams.put("APIM_EP", httpsServerEP);
        contextParams.put("MQTT_EP", mqttEndpoint);
        contextParams.put("DEVICE_TOKEN", token);
        contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
        contextParams.put("API_APPLICATION_KEY", base64EncodedApplicationKey);
        ZipArchive zipFile;
        zipFile = getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
        return zipFile;
    } catch (IOException e) {
        throw new DeviceManagementException("Zip File Creation Failed", e);
    }
}
Also used : DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException) HashMap(java.util.HashMap) IOException(java.io.IOException)

Example 4 with ZipArchive

use of org.wso2.iot.sampledevice.api.util.ZipArchive in project product-iots by wso2.

the class ZipUtil method getSketchArchive.

/**
 * Get agent sketch.
 *
 * @param archivesPath       Path of the zip file to create.
 * @param templateSketchPath Path of the sketch.
 * @param contextParams      Map of parameters to be included in the zip file.
 * @param zipFileName        Name of the zip file.
 * @return Created zip archive.
 * @throws DeviceManagementException
 * @throws IOException
 */
public static ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams, String zipFileName) throws DeviceManagementException, IOException {
    String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath;
    // clear directory
    FileUtils.deleteDirectory(new File(archivesPath));
    // clear zip
    FileUtils.deleteDirectory(new File(archivesPath + ".zip"));
    if (!new File(archivesPath).mkdirs()) {
        // new dir
        String message = "Could not create directory at path: " + archivesPath;
        throw new DeviceManagementException(message);
    }
    zipFileName = zipFileName + ".zip";
    try {
        Map<String, List<String>> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties");
        List<String> templateFiles = properties.get("templates");
        for (String templateFile : templateFiles) {
            parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath + File.separator + templateFile, contextParams);
        }
        // ommit copying the props file
        templateFiles.add("sketch.properties");
        copyFolder(new File(sketchPath), new File(archivesPath), templateFiles);
        createZipArchive(archivesPath);
        FileUtils.deleteDirectory(new File(archivesPath));
        File zip = new File(archivesPath + ".zip");
        return new ZipArchive(zipFileName, zip);
    } catch (IOException ex) {
        throw new DeviceManagementException("Error occurred when trying to read property " + "file sketch.properties", ex);
    }
}
Also used : DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException) ArrayList(java.util.ArrayList) List(java.util.List) IOException(java.io.IOException) File(java.io.File)

Aggregations

DeviceManagementException (org.wso2.carbon.device.mgt.common.DeviceManagementException)4 IOException (java.io.IOException)3 ZipArchive (org.wso2.iot.sampledevice.api.util.ZipArchive)2 File (java.io.File)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 GET (javax.ws.rs.GET)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1 Response (javax.ws.rs.core.Response)1 APIManagementProviderService (org.wso2.carbon.apimgt.application.extension.APIManagementProviderService)1 APIManagerException (org.wso2.carbon.apimgt.application.extension.exception.APIManagerException)1 JWTClient (org.wso2.carbon.identity.jwt.client.extension.JWTClient)1 AccessTokenInfo (org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo)1 JWTClientException (org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException)1 UserStoreException (org.wso2.carbon.user.api.UserStoreException)1 ZipUtil (org.wso2.iot.sampledevice.api.util.ZipUtil)1